我正在尝试从另一个表单中为user
分配views.py
值,但我似乎总是遇到以下错误。 Cannot assign "u'applematter'": "Student.user" must be a "User" instance.
如何让隐藏的字段用户匹配我在另一个字段中写的内容。
views.py文件
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from famu.forms import *
from django.contrib.auth.decorators import login_required
@login_required(login_url='')
def enroll(request):
if request.method == 'POST':
form = UserForm(request.POST,)
form2 = StudentCreate(request.POST)
if form.is_valid() and form2.is_valid():
new_user = form.save(commit=False)
new_student = form2.save(commit=False)
new_student.user = (new_user.username)
new_user.save()
new_student.save()
return HttpResponseRedirect('/')
else:
form = UserForm# An unbound form
form2 = StudentCreate
return render(request, 'famu/enroll.html', {
'form': form,
'form2': form2
})
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from famu.models import Student
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email','username',)
class StudentCreate(forms.ModelForm):
class Meta:
model = Student
exclude =['user',]
model.py
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
CLASSIFICATION = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
('GR', 'Graduate'),
)
TERMS = (
('F', 'Fall'),
('S', 'Spring'),
('Su', 'Summer'),
)
MAJOR = (
('CS', 'Computer Science'),
('CY', 'Computer Systems'),
('IT', 'Information Technology'),
)
user = models.ForeignKey(User)
student_id = models.IntegerField(primary_key=True, max_length=9)
classification = models.CharField(max_length=2, choices=CLASSIFICATION)
enrolled_year = models.IntegerField(max_length=4)
enrolled_term = models.CharField(max_length=2, choices=TERMS)
major = models.CharField(max_length=2, choices=MAJOR)
street_number = models.IntegerField(max_length=10)
street_name = models.CharField(max_length=45)
apt_number = models.CharField('apt #', max_length=10, blank=True, )
city = models.CharField(max_length=30)
state = models.CharField(max_length=2)
zipcode = models.IntegerField('Zip Code', max_length=5, )
last_modified = models.DateTimeField(auto_now=True)
答案 0 :(得分:1)
您应首先保存new_user
个实例,然后将其分配到新的学生实例中。
相关代码
@login_required(login_url='')
def enroll(request):
if request.method == 'POST':
form = UserForm(request.POST,)
form2 = StudentCreate(request.POST)
if form.is_valid() and form2.is_valid():
new_user = form.save(commit=False)
new_user.save() #form.save() should also work rather than this 2 statements
new_student = form2.save(commit=False)
new_student.user = new_user #assign user instance, not username
new_student.save()