gpt4 book ai didi

django - 如何获取授权用户创建的对象(Django)

转载 作者:行者123 更新时间:2023-12-05 00:55:56 25 4
gpt4 key购买 nike

表单.py

class KomForm(forms.ModelForm):
class Meta:
model = Kom
fields = ('company', 'title',)

模型.py

class Company(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
self.published_date = timezone.now()
self.save()

def __str__(self):
return self.title


class Kom(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
company = models.ForeignKey(Company, on_delete=models.CASCADE)

def publish(self):
self.published_date = timezone.now()
self.save()

def __str__(self):
return self.title

views.py

def kommpred_new(request):
if request.method == "POST":
user = request.user if request.user.is_authenticated() else None
form = KommpredForm(request.POST)
if form.is_valid():
kp = form.save(commit=False)
kp.author = request.user
kp.company=forms.ModelChoiceField(queryset=Company.objects.filter(author_id = self.user.id))
kp.published_date = timezone.now()
kp.save()
return redirect('kommpred_detail', pk=kp.pk)
else:
form = KommpredForm()
return render (request, 'by/kommpred_new.html', {'form': form})

我试图在通过表单字段 ModelChoiceField 创建新对象时实现用户选择,只有他所在的对象。到目前为止,试错的方法,我做不到。有人告诉我:

class KomForm (forms.ModelForm):
class Meta:
        model = Kom
        fields = ( 'company', 'title',)

def __init __ (self, * args, ** kwargs):
        # Call the constructor form and maintain user
        super (KomForm, self) .__ init __ (* args, ** kwargs)
        if 'user' in kwargs and kwargs [ 'user'] is not None:
            user = kwargs.pop ( 'user')
            qs = Company.objects.filter (author__id = user.id)
            self.fields [ 'company']. queryset = qs

def your_view (request):
    user = request.user if request.user.is_authenticated () else None
    form = KomForm (user = user)
    return render ( 'template.html' { 'form': form})

可是我还是不出去...

如何在ModelChoiceField字段中只传递那些对象,其中author是创建公司用户的对象?

最佳答案

我不确定我是否完全理解,但是,看起来您正在寻找表单中的用户参数,而不是从 View 中传递它。

首先我会改变 View

form = KommpredForm(request.POST)

form = KommpredForm(request.POST, user=user)

在表单内部,在从 kwargs 中弹出用户后放置 super。 KomForm 不会期待 user 关键字,所以在调用 super 之前将其弹出。

def __init __ (self, * args, ** kwargs):
# Call the constructor form and maintain user

if 'user' in kwargs and kwargs [ 'user'] is not None:
user = kwargs.pop ( 'user')
qs = Company.objects.filter (author__id = user.id)
else:
qs = .... what you want when no user was passed in ...

super (KomForm, self) .__ init __ (* args, ** kwargs)
self.fields [ 'company']. queryset = qs

尝试一下并返回结果。

关于django - 如何获取授权用户创建的对象(Django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40850016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com