2017-02-19 122 views
0

我使用Django創建一個名爲CampaignProfile的模型,然後每個登錄用戶都可以填寫表單來構建這樣一個對象,並擁有他們的所有'CampaignProfile顯示在他們的個人儀表板上。Python - 創建新的模型對象導致更新以前創建的對象

我發現的是,當我填寫此表單時,並沒有像我需要的那樣創建新的CampaignProfile對象,而是輸入的信息(標題等)替換了第一個CampaignProfile。

我很努力去理解模型對象更新的原因,而不是創建一個新的對象。

Models.py:

def get_file_name(instance, filename): 
    return ('uploads/%s_%s' % (str(time())).replace('.','_'), filename) 

class CampaignProfile(models.Model): 
    user = models.OneToOneField(UserModel, related_name='campaignprofile', on_delete=models.CASCADE, null=True) 
    campaign_title = models.CharField(max_length=50, verbose_name='Title') 
    campaign_dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') 
    campaign_dt_updated = models.DateTimeField(auto_now=True, verbose_name='Date Updated') 
    campaign_docs = models.FileField(upload_to=get_file_name, verbose_name='Files', blank=True, null=True) 

    slug = models.SlugField(unique=True, blank=True) 

    class Meta: 
     verbose_name = 'Campaign Profile' 

    def __str__(self): 
     return 'Campaign Title: ' + self.campaign_title + ' - ' + str(self.user) 

    def save(self, *args, **kwargs): 
     if self.user is None: # Set default reference 
      self.user = UserModel.objects.get(id=pk) 
     super(CampaignProfile, self).save(*args, **kwargs) 

Forms.py

class NewCampaignForm(forms.ModelForm): 
    campaign_title = forms.CharField(min_length=1, max_length=80, label='Campaign Name', required=True, 
    widget=forms.TextInput(attrs={'autofocus':'autofocus'})) 
    campaign_docs = forms.FileField(label='Attach .png and .docx files to your campaign', required=False, 
    widget=forms.ClearableFileInput(attrs={'id':'fileupl'})) 

    class Meta: 
     model = CampaignProfile 
     fields = ['campaign_title', 'campaign_docs'] 

    def clean(self): 
     cleaned_data = super(NewCampaignForm, self).clean() 
     return self.cleaned_data 

    def save(self, commit=True): 
     campaign = super(NewCampaignForm, self).save(commit=False) 
     if commit: 
      campaign.save() 
     return campaign 

Views.py

def campaign_create(request): 
    user=request.user.id 
    if request.user.is_authenticated: 
     try: 
      campaign = request.user.campaignprofile 
     except CampaignProfile.DoesNotExist: 
      campaign = CampaignProfile(user) 
     if request.method == 'POST': 
      form = NewCampaignForm(request.POST, request.FILES, instance=campaign) 
      if form.is_valid(): 
       form.save() 
       return redirect('/dashboard/') 
      else: 
       form = NewCampaignForm(instance=campaign) 
      return render(request, 'campaign-create.html', {'form': form}) 
     else: 
      form = NewCampaignForm() 
     return render(request, 'campaign-create.html', {'form': form}) 
    else: 
     return redirect('/users/login/') 

我沒有得到任何錯誤,當我提交表單,並嘗試了一些與代碼不同的東西。

任何幫助將是偉大的,謝謝。

回答

0

因爲您已將用戶關係定義爲一對一。根據定義,這意味着用戶只能有一個配置文件。

如果您想允許多個配置文件,請改用ForeignKey。

+0

我將OneToOneField更改爲ForeignKey並從我的views.py中刪除了「instance = campaign」,但是這次我提交表單時它只返回一個空表單,並且不會創建新的配置文件對象,也不會更新舊對象。關於爲什麼它不保存新表單條目的任何想法? – jayt

+0

那麼,大概這個表單是無效的,但是你已經通過在else子句中重新實例化表單來隱藏任何錯誤。不要這樣做。 –