2017-07-25 41 views
0

我有一個用於創建和編輯模型實例的表單。但是,在編輯模型實例時,表單仍嘗試創建新記錄並失敗,因爲唯一的一起字段已存在。初始化表單時,我已經傳遞了該實例。即使實例通過,Django表單也不更新現有記錄

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

你看在你的數據庫表中的項目? (或者你可以發佈它們嗎?)

你可能會嘗試使用django shell並嘗試手工執行你的代碼(用org_id查詢數據庫並檢查結果,編輯一個字段並保存它,這是否工作? )

另外我覺得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

相關問題