Django - 以

时间:2018-02-25 18:32:08

标签: django

我正在尝试在Django中创建一个表单,提交时应该只为注册用户在DB中保存数据。

基本上,学生字段默认情况下应该是登录用户

问题是,当我提交表单时,我收到以下错误消息: 无法指定“< SimpleLazyObject:< User:123>>”:“RegistrationRequest.student”必须是“学生”实例。

Models.py:

class Students(models.Model):
    Username = models.ForeignKey(User)
    FirstName = models.CharField(max_length=50)
    LastName = models.CharField(max_length=50)
    Group = models.CharField(max_length=4)

    def __str__(self):
        return str(self.Username) + ' ' + self.FirstName +' ' + self.LastName

class RegistrationRequest(models.Model):
    date = models.CharField(max_length = 20)
    title = models.CharField(max_length = 150)
    description = models.CharField(max_length = 500)
    teacher = models.CharField(max_length = 50)
    student = models.ForeignKey(Students)


    def __str__(self):
        return str(self.date) + ' ' + str(self.title) + ' ' + str(self.description) + ' ' + str(self.teacher)

forms.py

class RegistrationRequestForm(forms.ModelForm):
    date = forms.CharField()
    title = forms.CharField()
    description = forms.CharField()
    teacher = forms.CharField()


    class Meta:
        model = RegistrationRequest
        exclude = ["student"]

views.py

def registrationRequest(request):
    form = RegistrationRequestForm(request.POST or None)
    if request.method == 'POST':

        if form.is_valid():
            publish = form.save(commit=False)
            publish.student = request.user
            publish.save()

    return render(request, 'users/RegistrationRequest.html', {'form':form})

您能否告知如何解决此问题 谢谢!

1 个答案:

答案 0 :(得分:1)

student中的

RegistrationRequest字段是Students模型的外键,而不是User

<强>修正

user = request.user
try:
    student = Students.objects.get(Username=user)
except Students.DoesNotExist:
    # handle Student not found error here
    pass

publish.student = student