【问题标题】:Django form not updating existing record even when instance is passed即使传递了实例,Django表单也不会更新现有记录
【发布时间】: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


    【解决方案1】:

    您是否查看过 db 表中的条目? (或者你可以发布它们吗?)

    您可以尝试使用 django shell 并尝试手动执行您的代码(使用 org_id 查询 db 并检查结果。编辑字段并保存它。这样行吗?)

    另外我认为blank在这里只能是True或False。

    country = CountryField(null=True, blank='(Select Country)')

    https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.blank

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2022-07-19
      相关资源
      最近更新 更多