我目前正在做一个 Django 项目。这是我对 Python / Django 的第一次介绍,所以我目前正在学习。希望大家能帮忙!
我目前正在尝试通过模型、视图和模板更新我在 UserProfile 模型中设置的一些自定义字段。现在看来,无论我对视图做什么,返回的表单总是返回无效。我已经盯着这个看了很长一段时间,所以这可能没有帮助。这是代码:
模型.py:
class UserProfile(models.Model):
#inherit the base User model
user = models.OneToOneField(User)
#custom fields to be in the User model
phoneNumber = models.IntegerField(null=True)
about = models.TextField(null=True)
gitHubLink = models.URLField(null=True)
linkedInLink = models.URLField(null=True)
gravitarLink = models.URLField(null=True)
facebookLink = models.URLField(null=True)
rating = models.PositiveSmallIntegerField(default=0)
def __unicode__(self):
return u'Profile of user: %s' % self.user.username
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
视图.py:
@login_required
def edit_profile(request):
profile = request.user.get_profile()
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=profile)
if form.is_valid():
userprofile = form.save(commit=False)
userprofile.user = request.user
userprofile.save()
messages.success(request, "Account Updated!")
return render_to_response('profile/edit.html', {"form": form}, context_instance=RequestContext(request))
else:
form = UserProfileForm()
messages.error(request, "There are form errors.")
return render_to_response('profile/edit.html', {"form": form}, context_instance=RequestContext(request))
else:
form = UserProfileForm(instance=profile)
return render_to_response('profile/edit.html', {"form": form}, context_instance=RequestContext(request))
表格.py:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('phoneNumber', 'about', 'gitHubLink', 'linkedInLink', 'gravitarLink', 'facebookLink')
def save(self, commit=True):
userprofile = super(UserProfileForm, self).save(commit=False)
userprofile.phoneNumber = self.cleaned_data['phoneNumber']
if commit:
userprofile.save()
return userprofile
编辑.html(模板):
<form action="/profile/edit/" method="post" class="form-signin">
{% csrf_token %}
<div class="form-group">{{ form.phoneNumber|add_class:"form-control"|attr:"placeholder:Phone Number" }} </div>
<div class="form-group">{{ form.gitHubLink|add_class:"form-control"|attr:"placeholder:GitHub Account URL" }} </div>
<div class="form-group">{{ form.facebookLink|add_class:"form-control"|attr:"placeholder:Facebook Account URL" }} </div>
<div class="form-group">{{ form.linkedInLink|add_class:"form-control"|attr:"placeholder:LinkedIn Account URL" }} </div>
<div class="form-group">{{ form.about|add_class:"form-control"|attr:"placeholder:About Yourself. Interests, Hobbies, etc.." }} </div>
<button class="btn btn-lg btn-success btn-block" type="submit">Save Changes</button>
</form>
感谢您花时间阅读本文。任何帮助/指针都非常感谢!