我似乎无法使用 .is_valid() 验证我的表单
关联的视图
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))
表格.py
class SocialMediaForm(forms.ModelForm):
class Meta:
model = SocialMedia
fields = {'twitter', 'facebook', 'linkedin'}
模板
<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>
该模型
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")
一些帮助将不胜感激。我对 django 比较陌生,所以我一直错过了一些较小的细微差别。我在 stackoverflow 上发现了一些与绑定和未绑定表单相关的类似问题,但是通过阅读文档,我认为我正确地将数据绑定到表单。