简体   繁体   English

Django 1.9 在两个页面形式中使用 django 会话

[英]Django 1.9 using django sessions in two page forms

How can I use Django sessions to have a user be able to start a form on one page, and move to the next page and have them complete the form?我如何使用 Django 会话让用户能够在一页上启动表单,然后移动到下一页并让他们完成表单?

I have looked into pagination and wizard forms, but I don't get them at all.我已经研究了分页和向导形式,但我根本不了解它们。

When I have one page with a small portion of a model I'm using - in forms - and another page with the rest of the model - forms.py with the rest of the model info - I can use the first form perfectly.当我有一个页面包含我正在使用的模型的一小部分 - 在表单中 - 另一个页面包含模型的其余部分 - forms.py以及模型信息的其余部分 - 我可以完美地使用第一个表单。

But when I move to the next page, I get an error saying (1048, "Column 'user_id' cannot be null") .但是当我移动到下一页时,我收到一条错误消息(1048, "Column 'user_id' cannot be null")

My best guess is to use Django sessions to fix this issue.我最好的猜测是使用 Django 会话来解决这个问题。 I don't want the user to have to put in their username and password a second time to get this to work.我不希望用户必须再次输入他们的用户名和密码才能使其正常工作。 Any ideas?有任何想法吗?

my models/forms.py:我的模型/forms.py:

class Contact(models.Model):
    user = models.OneToOneField(User)
    subject = models.CharField(max_length=100, blank=True)
    sender = models.EmailField(max_length=100, blank=True)
    message = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.user.username


class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = Contact
        fields = ('username', 'password', 'email')


class ContactForm1(forms.Form):
    class Meta:
        model = Contact
        fields = ('subject', 'sender')


class ContactForm2(forms.Form):
    message = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Contact
        fields = ('message',)

views:意见:

def contact(request):
    registered = False
    if request.method =='POST':
        user = UserForm(request.POST)
        contact = ContactForm1(request.POST)
        if user.is_valid() and contact.is_valid():
            user = user.save()
            user.set_password(user.password)
            user.save()
            contact = contact.save(commit=False)
            contact.user = user
            registered = True
    return render(request, 'mysite/contact.html', {'user': user, 'contact': contact, 'registered': registered})

def contact_second(request):
    if request.method =='POST':
        contact = ContactForm2(request.POST)
        if contact.is_valid():
            contact = contact.save(commit=False)
            contact.save()
    return render(request, 'mysite/contact_two.html', {'contact': contact}

I think it's a good idea to use sessions to store the forms because you don't want on each page to store the user input into the database because what if s/he change mind in the 3rd page and s/he wants to discard the registration or whatever it is?我认为使用会话来存储表单是一个好主意,因为您不希望在每个页面上都将用户输入存储到数据库中,因为如果他/他在第三页改变主意并且他/他想要丢弃注册或其他什么?

I think is better to store the forms in session until you get in the last page, you ensure that everything is valid and then save the data in the database.我认为最好将表单存储在会话中,直到进入最后一页,确保一切都有效,然后将数据保存在数据库中。

So let's say that the bellow code is in one of the view that will serve the first form/page.因此,假设波纹管代码位于为第一个表单/页面提供服务的视图中。 You retrieve the data from the POST request and you check if the given data are valid using the form.is_valid() , you then store the form.cleaned_data (which contains the user's validated data) to a session variable.您从 POST 请求中检索数据,并使用form.is_valid()检查给定数据是否有效,然后将form.cleaned_data (包含用户的验证数据)存储到会话变量中。

form = CustomForm(request.POST)
...
if form.is_valid():
    request.session['form_data_page_1'] = form.cleaned_data

Note here that you may need to add code to redirect the user to the next page if form.is_valid() is true, something like this:请注意, if form.is_valid()为 true,您可能需要添加代码以将用户重定向到下一页,如下所示:

if form.is_valid():
    request.session['form_data_page_1'] = form.cleaned_data
    return HttpResponseRedirect(reverse('url-name-of-second-page'))

Then in any other view let's say in the view that is going to serve the second page you can retreive the from data from the first page like this:然后在任何其他视图中,让我们说在要为第二页提供服务的视图中,您可以像这样从第一页检索 from 数据:

first_page_data = request.session['form_data_page_1']

And you can do whatever you want with them as if it was after you executed the form.is_valid() in the first view.您可以对它们做任何您想做的事情,就像在第一个视图中执行form.is_valid()之后一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM