Python - 创建新的模型对象可以更新以前创建的对象

时间:2017-02-19 16:39:24

标签: python django

我使用Django创建一个名为CampaignProfile的模型,然后每个登录的用户都可以填写一个表单来构建这样一个对象,并在他们的所有对象上显示他们的' CampaignProfile个人仪表板。

我发现,当我填写此表单时,我不会创建新的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/')

我提交表单时没有错误,并且已经尝试了一些不同的代码。

任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:0)

因为您已将与User的关系定义为一对一。根据定义,这意味着用户只能拥有一个配置文件。

如果要允许多个配置文件,请改用ForeignKey。