我有一个用于创建和编辑模型实例的表单。但是在编辑模型实例时,表单仍会尝试创建新记录并失败,因为已存在唯一的一起字段。我在初始化表单时已经传递了实例。
views.py
def organization_course_detail(request, org_id):
'''
Get all courses that are associated with an organization
'''
template_name = 'users/organization-course-list.html'
organization = models.Organization.objects.get(id=org_id)
if request.method == 'POST':
print organization.id
form = forms.CreateOrganizationForm(request.POST, instance=organization)
if form.is_valid():
print 'form is valid'
org = form.save(commit=False)
org.save()
return HttpResponseRedirect(
reverse('users:org-course-list',
kwargs={'org_id': org_id}))
else:
form = forms.CreateOrganizationForm(instance=organization)
forms.py
class CreateOrganizationForm(forms.ModelForm):
'''
A form used to create a new organization. At the same time,
we create a new course that is a clone of "Chalk Talk SAT"
and associate the course with the organization and any student
that signs up from that organization
'''
class Meta:
model = models.Organization
fields = ['name', 'country', 'acronym',]
models.py
class Organization(models.Model):
'''
This is a model where we will have every institution
(test prep centers, governments, schools) that we do workshops
at or create school accounts for
'''
name = models.CharField(max_length=2000)
country = CountryField(null=True, blank='(Select Country)')
date = models.DateTimeField(default=timezone.now)
acronym = models.CharField(max_length=7, help_text="(Up to 7 characters)")
expiration_date = models.DateTimeField(default=timezone.now)
def get_org_admins(self):
return self.admin_for_organizations.all()
class Meta:
unique_together = (
('name', 'country')
)
def __str__(self):
return self.name
答案 0 :(得分:0)
您是否查看过db表中的条目? (或者你可以发布它们吗?)
您可以尝试使用django shell并尝试手动执行代码(使用org_id查询数据库并检查结果。编辑一个字段并保存它。这有用吗?)
此外,我认为blank
在这里只能是正确或错误。
country = CountryField(null=True, blank='(Select Country)')
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.blank