如何修复“ Django中的更新更新配置文件”

时间:2019-08-13 10:43:43

标签: python django

我遇到了这样的问题。该帐户可以在一定时期内将计划从免费计划更改为高级计划。当用户选择一个程序包并进行同步时,不会保存日期。我怎么了这是代码

# model.py
CHOICES = [('Free', 'free'), ('Premium', 'premium')]
​
​
class MemberShip(models.Model):
    title = models.CharField("Title", max_length=100)
    period = models.IntegerField("Period", default=30)
    price = models.IntegerField("Price", default=2, help_text="Price in dollars")
​
    def __str__(self):
        return f'Plan - {self.title}'
​

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    status = models.CharField("Status", max_length=20, choices=CHOICES, default='Free')
    end_date = models.DateTimeField("End Date", blank=True, null=True)
    membership = models.ForeignKey(MemberShip, on_delete=models.SET_NULL, null=True, default=None)
​
    def __str__(self):
        return self.user.username
​
    # def get_absolute_url(self):
    #     return reverse('account:profile', args=['id', self.id])
​
​
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
​
​
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
​
​
# form.py
class PremiumForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['membership']
​
​
# view.py
​
class GetPremium(LoginRequiredMixin, UpdateView):
    model = Profile
    form_class = PremiumForm
    template_name = 'account/premium.html'
    success_url = reverse_lazy('account:dashboard')
​
    def get_object(self, **kwargs):
        return get_object_or_404(User, pk=self.request.user.id)

1 个答案:

答案 0 :(得分:1)

在您的get_object中,您使用了错误的模型:这里需要一个Profile对象,不是一个User对象:

class GetPremium(LoginRequiredMixin, UpdateView):
    model = Profile
    form_class = PremiumForm
    template_name = 'account/premium.html'
    success_url = reverse_lazy('account:dashboard')
​
    def get_object(self, **kwargs):
        return get_object_or_404(Profile, user=self.request.user)

请注意,对于Profile,您的reverse(..)应该在此处传递一个kwargs=...参数,并带有一个键'id',该键映射到您的Profile的ID:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    status = models.CharField("Status", max_length=20, choices=CHOICES, default='Free')
    end_date = models.DateTimeField("End Date", blank=True, null=True)
    membership = models.ForeignKey(MemberShip, on_delete=models.SET_NULL, null=True, default=None)
​
    def __str__(self):
        return self.user.username
​
    def get_absolute_url(self):
        return reverse('account:profile', kargs={'id': self.id})