使用多个相关的django模型

时间:2017-12-04 21:38:07

标签: python django django-models django-forms django-views

我试图从相关模型中获取两个表单,以显示在同一页面上并保存在一起。

这是我的models.py:

class userinfo(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key= True, 
on_delete=models.CASCADE)
    name = models.CharField(max_length = 200, blank = True)
    email = models.EmailField(max_length= 300, default = 'Null')
    phone = models.CharField(max_length= 10, default = 'Null')

    def __unicode__(self):
        return self.user

class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=False)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id) + str(self.title)

如您所见,用户(在我的sqlite3 db中保存为user_id)是userinfo表中的外键。我试图为每个卖家列出多个活动。

forms.py:

class Userinfo(forms.ModelForm):

    class Meta:
        model = userinfo
        exclude = {'user'}

class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

views.py:

def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            userinfo_form = Userinfo(request.POST, instance = user.userinfo)
            seller_event_form = Seller_event(request.POST, instance = 
user.seller_event)
            if userinfo_form.is_valid() and seller_event_form.is_valid():
                userinfo_form.save()
                seller_event_form.save()
                return redirect('/home')
        else:
            userinfo_form = Userinfo()
            seller_event_form = Seller_event()

        return render(request, 'home/newlist.html', {'userinfo_form': 
userinfo_form, 'seller_event_form': seller_event_form })

HTML:

{% load static %}


<form action="/home/newlist/" method="post">

{% csrf_token %}
{{ userinfo_form.as_p }}
{{ seller_event_form.as_p }}

<input type="submit">

</form>

我怀疑问题是,对于userinfo,用户pk是一个onetoone,识别模型没有问题。但是,对于seller_event来说情况并非如此。这是一个fk。那么,我如何让它接受用户作为fk?

提前致谢!

1 个答案:

答案 0 :(得分:2)

表单验证后,保存表单而不提交,然后设置外键并保存。

if userinfo_form.is_valid() and seller_event_form.is_valid():
    userinfo_form.save()

    new_seller_event = seller_event_form.save(commit=False)
    new_seller_event.user = user
    new_seller_event.save()

    return redirect('/home')