简体   繁体   English

Django form.is_valid()未验证

[英]Django form.is_valid() not validating

I can't seem to get my form to validate with .is_valid() 我似乎无法让我的表格使用.is_valid()进行验证

The associated View 关联的视图

def edit_social_media(request, user_id):

#verify a user is allowed to access the page

# user is saving the form
if request.POST:

form = SocialMediaForm(request.POST)
if form.is_valid():
 ...

  return HttpResponseRedirect(reverse(users.profile,
                                   args = (request.user.id,)))

# displaying the initial form
else:
   try:
     form = SocialMediaForm(instance = SocialMedia.objects.get(user = request.user))
   except SocialMedia.DoesNotExist:
     form = SocialMediaForm()


return render_to_response('users/edit_social_media.html', {'form': form, 'user' : user},
 context_instance = RequestContext(request))

Forms.py Forms.py

class SocialMediaForm(forms.ModelForm):
   class Meta:
      model = SocialMedia
      fields = {'twitter', 'facebook', 'linkedin'}

the template 模板

<form method="post" action=''>
{% csrf_token %}
<div class="form-col-left">
    <p>
    {{ form.as_p }}
</p>
</div>


<div class="submitbutton">
<input type="submit" class="green button" value="Save Social Media Settings" />
</div>

</form>

The model 该模型

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

class SocialMedia(models.Model):
    class Meta:
        app_label = 'dashboard'

  #the user associated with the data
  user = models.ForeignKey(User)

  #Twitter, Facebook, and Linkedin pages
  twitter = models.URLField("Twitter")
  facebook = models.URLField("Facebook")
  linkedin = models.URLField("Linkedin")

Some help would be greatly appreciated. 一些帮助将不胜感激。 I'm rather new to django so I've been missing some of the smaller nuances. 我对Django比较陌生,所以我一直想念一些较小的细微差别。 I've found some similar issues on stackoverflow related to bound vs unbound forms, but from reading the documentation I think I properly bound the data to the form. 我在stackoverflow上发现了一些与绑定表单和未绑定表单有关的类似问题,但是通过阅读文档,我认为我已经将数据正确绑定到了表单。

Since this is a ModelForm it would help seeing the actual Model that this form is using, the SocialMedia class. 由于这是一个ModelForm,它将有助于查看该表单正在使用的实际模型,即SocialMedia类。 Also I am not sure what you mean by not getting it to validate but I am assuming that the is_valid() method returns False. 我也不确定通过不验证它是什么意思,但是我假设is_valid()方法返回False。

My guess is that the method returns False because you are not setting the user on the form. 我的猜测是该方法返回False,因为您没有在窗体上设置用户。 In the POST dictionary you don't have the user or user_id. 在POST词典中,您没有用户或user_id。 Add the following line before the "if form.is_valid()" statement: 在“ if form.is_valid()”语句之前添加以下行:

form.instance.user = self.request.user form.instance.user = self.request.user

Hope this works. 希望这行得通。

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

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