我有一个模型表单但是我很难根据需要设置一个字段而不更改模型本身。当用户提交表单时,有没有办法在不更改models.py的情况下强制使用location字段?
modelys.py
class Profile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=120, null=True, blank=True)
picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
gender = models.CharField(max_length=120, null=True, choices=GENDER, blank=True)
bio = models.CharField(max_length=1000, null=True, blank=True)
home_university = models.CharField(max_length=50, null=True, blank=True)
my forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
"location",
"picture",
"bio",
"gender",
"home_university",
]
和我的views.py
@login_required
def profile_complete(request):
profile, created = Profile.objects.get_or_create(user=request.user)
form = ProfileForm(request.POST or None, request.FILES or None, instance=profile)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect("home")
context = {
"form": form,
}
return render(request, "profiles/profile_complete.html", context)
答案 0 :(得分:2)
您可以使用以下选项:
1 - init 功能:
class ProfileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
# Making location required
self.fields['location'].required = True
class Meta:
model = Profile
fields = [
"location",
"picture",
"bio",
"gender",
"home_university",
]
2 - 重新定义字段:
class ProfileForm(forms.ModelForm):
location = forms.CharField(max_length=120, required=True)
class Meta:
model = Profile
fields = [
"location",
"picture",
"bio",
"gender",
"home_university",
]
在您的情况下,没有问题,因为您的模型是null=True
,并且您将字段设置为必需,但如果您对null=False
的其他模型字段执行此操作并覆盖该字段将ModelForm设置为required=False
,然后在将其保存到数据库之前必须在表单或视图中提供一个值,否则会出错。