我正在尝试为学生班级创建一个ModelForm。这使用当前登录的用户作为Django的auth系统和我的模型之间的一对一关系。我无法通过验证来拯救我的生命。以下是相关模型:
class student(models.Model):
user_id = models.OneToOneField(User,unique=True)
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
#enrolled_classes = models.ManyToManyField('agility_class')
#completed_classes = models.ManyToManyField('agility_class')
email_address = models.EmailField()
phone_number = PhoneNumberField()
training_experience = models.CharField(max_length=500)
#training_materials =
def __unicode__(self):
return self.first_name + " " + self.last_name;
class studentForm(ModelForm):
class Meta:
model = student
我的观点如下:
def profile_creation(request):
if request.method == 'POST':
thisform = studentForm(request.POST)
if thisform.is_valid():
thisform.save()
return HttpResponseRedirect('/about')
return render(request, 'profile_registration.html')
以下是我的模板中的表单:
<form class="form-horizontal" method = 'POST'>
{%csrf_token%}
<fieldset>
<!-- Form Name -->
<legend>Profile</legend>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="first_name">First Name</label>
<div class="controls">
<input id="first_name" name="first_name" type="text" placeholder="" class="input-large">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="last_name">Last Name</label>
<div class="controls">
<input id="last_name" name="last_name" type="text" placeholder="" class="input-large">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input id="email_address" name="email_address" type="text" placeholder="" class="input-large">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="phone_number">Phone Number</label>
<div class="controls">
<input id="phone_number" name="phone_number" type="text" placeholder="" class="input-large">
<p class="help-block">Format: 123-456-7890</p>
</div>
</div>
<!-- Textarea -->
<div class="control-group">
<label class="control-label" for="training_experience">Training Experience</label>
<div class="controls">
<textarea id="training_experience" name="training_experience"></textarea>
</div>
</div>
<input type="hidden" name= "user_id" value ="{{ user.username }}">
<input type="submit" value="submit">
</fieldset>
</form>
也许我错过了一些激烈的事情......先谢谢你的帮助。
答案 0 :(得分:2)
您的表单正在发布值request.user.username
,该值不是User
对象的实例。要使代码按原样运行,您必须先按用户名检索用户,然后按如下方式分配属性:
def profile_creation(request):
student_form = StudentForm(request.POST or None)
if request.method == 'POST':
username = request.POST.get('username')
try:
user = User.objects.get(username=username)
student = StudentForm.save(commit=False)
student.user = user
student.save()
except User.DoesNotExist:
# handle the exception
...
你必须填充user_id
,我只想命名user
,因为“user_id”误导了imo,并带有user
个实例。而不是在视图中执行此操作,在上面的示例中变得混乱,您最好在表单类中分配该值以保持视图清洁。
# classes ALWAYS start with a capital letter in Python
class Student(models.Model):
user_id = models.OneToOneField(User,unique=True)
...
class StudentForm(ModelForm):
class Meta:
model = student
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(StudentForm, self).__init__(*args, **kwargs)
self.fields['user'] = user
# views.py
from django.core.urlresolvers import reverse
def profile_creation(request):
# Assumes the user is authenticated, otherwise request.user
# will be an AnonymousUser instance...
student_form = StudentForm(request.POST or None, user=request.user)
if request.method == 'POST':
if student_form.is_valid():
student_form.save()
# don't hard-code urls - use reverse lookups
return HttpResponseRedirect(reverse('about'))
return render(request, 'profile_registration.html',
{'student_form': student_form})
答案 1 :(得分:0)
是的,您需要通过用户名获取User对象。
user = request.POST.get(username=username)
然后您可以将用户对象保存到OneToOneField中。