1

我正在尝试为学生班级创建一个 ModelForm。这使用当前登录的用户作为 Django 的身份验证系统和我的模型之间的一对一关系。我无法验证这一点以挽救我的生命。以下是相关型号:

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>

也许我错过了一些激烈的东西......提前感谢您的帮助。

4

2 回答 2

2

您的表单正在发布 value 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}) 
于 2013-10-15T01:42:02.310 回答
0

是的,您需要通过用户名获取用户对象。

user = request.POST.get(username=username)

然后您可以将用户对象保存到 OneToOneField 中。

于 2013-10-15T06:26:25.557 回答