我想在我的表单中添加一个多项选择字段,经过搜索,我终于使它工作了。但是,当我创建一个新用户并尝试填写个人信息表单时,它给了我PersonalInfo匹配查询不存在的错误。这些是我的代码:models.py:
class Field(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=16, default='default')
title = CharField(max_length=32)
class PersonalInfo(models.Model):
id = models.AutoField(primary_key=True)
isCompleted = models.BooleanField(default=False)
interested_fields = models.ManyToManyField(Field, blank=True)
forms.py:
class InterestedFieldsForm(forms.ModelForm):
interested_fields = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Field.objects.all(), required=False)
class Meta:
model = PersonalInfo
fields = ['interested_fields']
views.py:
class PersonalView(View):
template_name = 'reg/personal.html'
def get(self, request, *args, **kwargs):
context = {}
context['fields'] = Field.objects.all()
return render(request, self.template_name, context=context)
def post(self, request, *args, **kwargs):
user = request.user
if request.method == 'POST':
form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user))
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
form.save_m2m()
else:
form = InterestedFieldsForm()
return render(request, 'reg/done.html', context={'form': form})
我知道这个问题是因为视图中的这一行:form = interestdfieldsform(请求。帖子,实例= PersonalInfo.objects.get(用户=))当我删除实例时,表单被保存为用户的个人信息,但表单不会取代以前的,它创建一个新的。然后我又把实例放回去,试着保存表单,一切都很好。是什么导致了这个问题?
from django.contrib.auth import get_user_model
class PersonalInfo(models.Model):
id = models.AutoField(primary_key=True)
isCompleted = models.BooleanField(default=False)
interested_fields = models.ManyToManyField(Field, blank=True)
### add this
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='personal_info')
执行迁移过程,然后在您的视图中:
def post(self, request, *args, **kwargs):
user = request.user
if request.method == 'POST':
personalInfo, created = PersonalInfo.objects.get_or_create(user=user)
form = InterestedFieldsForm(request.POST, instance=personalInfo)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
form.save_m2m()
else:
form = InterestedFieldsForm()
return render(request, 'reg/done.html', context={'form': form})