简体   繁体   English

表单未将用户数据保存到Django数据库中

[英]Form is not saving user data into database Django

Python noob here trying to learn something very simple. Python noob在这里尝试学习一些非常简单的东西。

I'm trying to create a basic form that takes some personal information from a user and saves it into a sqlite3 table with the username of the user as the primary key. 我正在尝试创建一种基本形式,该形式从用户那里获取一些个人信息,并将其保存到sqlite3表中,并以用户名作为主键。

My models.py looks like this: 我的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

forms.py: forms.py:

class NewList(forms.ModelForm):

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

views.py views.py

def newlist(request):
    if request.method == 'POST':
        form = NewList(request.POST)
        if form.is_valid():
            Event = form.save(commit = False)
            Event.save()
            return redirect('/home')

    else:
        form = NewList()

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

html: 的HTML:

{% load static %}

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

{% csrf_token %}
{{ form.as_p }}

<input type="submit">

</form>

urls.py too, but I don't know how that would help: urls.py也是,但是我不知道这将如何帮助:

urlpatterns = [
    url(r'^newlist/$', views.newlist, name='newlist')
]

So when I go to the url, I see the form. 因此,当我转到url时,会看到表格。 I can then fill the form, but when I submit the form, the data doesn't go into the database. 然后可以填写表单,但是当我提交表单时,数据不会进入数据库。

What am I doing wrong here? 我在这里做错了什么?

Thanks in advance! 提前致谢!

I think all you need to do is just save the form if it's valid, probably also add the userinfo as an instance of the form. 我认为您只需要保存表单即可(如果有效),也可以将userinfo添加为表单的实例。 You are also exluding the user from the form and need to assign it manually. 您还从表单中排除了用户,并且需要手动分配它。

def newlist(request):
    if request.user.is_authenticated():
        user = request.user

        if request.method == 'POST':
            form = NewList(request.POST, instance=user.userinfo)
            if form.is_valid():
                form.save(commit=false)  
                form.user = user          
                form.save()
                return redirect('/home')
        else:
            form = NewList(instance=user.userinfo) # add this if you want it to automatically fill the form with the old data if there is any.

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

The rest look like it should work.Except you need to send the post URL back to newlist: 其余的看起来应该可以正常工作,除了您需要将帖子URL发送回newlist:

{% load static %}
<form action="/newlist/" method="POST">

{% csrf_token %}
{{ form.as_p }}
</form>

If users are assigned at the creation of the model the first time, you don't need the user save, but since this is saving a users data you want to make sure they are logged in anyway: 如果是在首次创建模型时分配用户,则不需要用户保存,但是由于这是在保存用户数据,因此您无论如何都要确保他们已登录:

def newlist(request): 
    if request.user.is_authenticated(): 
        user = request.user 
        if request.method == 'POST':
            form = NewList(request.POST, instance=user.userinfo)
            if form.is_valid():          
                form.save()
                return redirect('/home')
        else:
            form = NewList(instance=user.userinfo) # add this if you want it to automatically fill the form with the old data if there is any.

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

The instance is the model it is either going to save to, or copying data from. 实例是将要保存到其中或从中复制数据的模型。 In the: form = NewList(request.POST, instance=user.userinfo) part, it is taking the POST data from the form, and linking that to the specific model entry of user.userinfo, however, it will only save to the database when you call form.save(). 在: form = NewList(request.POST, instance=user.userinfo)部分中,它从表单中获取POST数据,并将其链接到user.userinfo的特定模型条目,但是, 它将仅保存到调用form.save()时的数据库。

The user.userinfo is just so you can get the correct form to save to, as userinfo is a onetoone model to user. user.userinfo只是这样,您可以获取要保存的正确表格,因为userinfo是用户的一个单音模型。 Thus making it possible to get it with user.userinfo. 这样就可以通过user.userinfo获取它。

The form = NewList(instance=user.userinfo) part is where it takes the currently logged in user's userinfo and copies into the form before it is rendered, so the old userinfo data will be prefilled into the form in the html. form = NewList(instance=user.userinfo)部分是将当前登录的用户的userinfo并在呈现之前复制到表单中的位置,因此旧的userinfo数据将被预先填充到html中的表单中。 That being if it got the correct userinfo model. 那就是如果它有正确的userinfo模型。

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

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