如何使用用户进行表单视图是外键,一个模型与另一个模型有外键关系?

时间:2017-06-28 20:07:38

标签: django django-forms django-views

我的model.py是

from django.db import models
from django.contrib.auth.models import User

class Question(models.Model):
    asker = models.ForeignKey(User, related_name='questions')
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

forms.py

from django.forms import ModelForm
from django.forms import inlineformset_factory
from .models import Question,Choice

class PollForm(ModelForm):
    class Meta:
        model = Choice
        exclude = ()
postinline=inlineformset_factory(Question, Choice, form=PollForm, extra=1)

我应该如何编辑视图以使最大选择量为3 并使经过身份验证的用户是问题的提问者 提前谢谢

1 个答案:

答案 0 :(得分:1)

也许你想要这样的东西

def post_create(request):
    form = ModelForm (request.POST or None, request.FILES or None)
    user = User.objects.get(username=request.user.username)

    if form.is_valid():
        instance = form.save(commit=False)
        instance.asker= user
        instance.save()

   context = {
        "form": form
    }

    return render (request,"blog/create.html",context)