简体   繁体   English

如何在Django中将表单数据保存到我的模型中

[英]How to save form data to my model in django

I am creating a newsletter application that requires the user's name and email. 我正在创建一个需要用户名和电子邮件的新闻通讯应用程序。 However each time I input form data . 但是每次我输入表格数据。 no change is reflected in the database 没有变化反映在数据库中

models.py models.py

class NewUsers(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()
    date_added = models.DateField(auto_now_add= True)

    class Meta:
        verbose_name = "NewUser"
        verbose_name_plural = "NewUsers"

    def __str__(seld):
         return self.email

views.py views.py

def newsletter_subscribe(request):
    if request.method == 'POST' :
        form = NewUserForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name'] #variable to store cleaned data
            email = form.cleaned_data['email']
            instance = NewUsers(name= name, email = email)
            instance.save()
            if NewUsers.objects.filter(email = instance.email).exists():
                print("Your email is already added to our database")
            else:
                instance.save()
                print("Thank you for subscribing")

     else:
        form = NewUserForm()#display empty form
        context = {'form':form}
        template = "index.html"
        return render(request ,template ,context )

Here is my template code 这是我的模板代码

template 模板

 <form  method="post" action="{%url 'subscribe'%}">
  {% csrf_token %}
 <label for="id_email_field">Name:</label> <input type="text" 
  name=""
 required="" id="">
<label for="id_email_field">E-mail:</label> <input type="email" 
name="email_field"
 required="" id="id_email_field">
<button id="id_submit" name="submit" value="Subscribe" 
 type="submit">Subscribe
</button>
</form>

A few things I notice: First, a view must return an HttpResponse object. 我注意到一些事情:首先,视图必须返回HttpResponse对象。 Eg, I recommend reading up here: https://docs.djangoproject.com/en/2.1/topics/http/views/ and here: https://docs.djangoproject.com/en/2.1/topics/forms/ So, since apparently you didnt get an error thrown at you pointing to this fact, I assume that the request.method never has been equal "POST". 例如,我建议在这里阅读: https : //docs.djangoproject.com/en/2.1/topics/http/views/和在这里: https : //docs.djangoproject.com/en/2.1/topics/forms/所以,因为显然您没有指出这个事实,所以我认为request.method从未等于“ POST”。 Maybe you could try to find out if this is the case? 也许您可以尝试找出是否是这种情况? Therefore: could you also provide your template code, please. 因此:请您也提供您的模板代码。

Next, your code in the if form.is_valid() is quite contrived. 接下来,您在if form.is_valid()中的代码非常人为设计。 The most natural thing to do here is just calling form.save(). 在这里最自然的事情就是调用form.save()。 This will create an instance in your db out of the cleaned form-data. 这将从清理的表单数据中在数据库中创建一个实例。 In case, you need to do some adjustments, you can extend like this: 万一您需要进行一些调整,可以像这样扩展:

instance = form.save(commit=False)
# add some adjustments (instance.foo = bar)
instance.save()

Last, as noted before, you need to return an HttpResponse object which is usually done via 最后,如前所述,您需要返回一个HttpResponse对象,该对象通常通过

return redirect(url_name, ..)

Edit: since you now added the template code: Try to first let django render the fields for you: https://docs.djangoproject.com/en/2.1/topics/forms/#rendering-fields-manually and then have a look at the source code of the template. 编辑:因为您现在已经添加了模板代码:尝试首先让django为您呈现字段: https : //docs.djangoproject.com/en/2.1/topics/forms/#rendering-fields-manually ,然后看看模板的源代码。 Your name-input-field is missing a name tag and your email-input-field should have name="email" I think. 我认为您的名称输入字段缺少名称标签,并且您的电子邮件输入字段应具有name =“ email”。 You can django even let the whole form render for you (see docs again...) Without (correct) name tags in the input fields - it will not be possible to send or correctly assign the data inputted by the user. 您甚至可以让django为您呈现整个表单(请再次参阅文档...)。在输入字段中没有(正确的)名称标签的情况下-无法发送或正确分配用户输入的数据。

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

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