【发布时间】:2017-12-31 23:22:49
【问题描述】:
我有一个用于创建和编辑模型实例的表单。但是在编辑模型实例时,表单仍然尝试创建新记录并失败,因为唯一的共同字段已经存在。我在初始化表单时已经传递了实例。
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
【问题讨论】:
标签: django post django-forms django-views