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

时间:2016-11-28 17:20:22

标签: django

forms.py

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

models.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中传递那些对象,其作者是创建公司用户的对象?

1 个答案:

答案 0 :(得分:1)

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

首先我在视图中进行更改

form = KommpredForm(request.POST)

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

并在表单内部,在从kwargs弹出用户之后放置super。 KomForm不会期待用户关键字,所以在调用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

尝试一下,然后回复结果。