用户没有dcf_profile:RelatedObjectDoesNotExist

时间:2017-06-16 10:08:39

标签: django

扩展现有用户模型后,我得到一个UserObject没有dcf_profile的RelatedObjectDoesNotExist异常。我似乎并没有为每个用户自动创建dcf_profile。

请查看我的模型,视图和表格,告诉我如何更正我的观点文件?

我的models.py:

class CustomUser(models.Model):
    auth_user_ptr = models.OneToOneField(
                                User,
                                parent_link=True,
                                related_name='dcf_profile',
                                primary_key=True
                            )
    phone = models.CharField(_('phone'), max_length=30, null=True, blank=True)
    receive_news = models.BooleanField(_('receive news'), default=True, db_index=True)
    class Meta:
        app_label = 'dcf'
    def allow_add_item(self):
        if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT:
            return False
        else:
            return True

class Item(models.Model):
    slug = models.SlugField(blank=True, null=True, max_length=100)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, verbose_name=_('group'))
    title = models.CharField(_('title'), max_length=100)
    description = models.TextField(_('description'))
    price = models.DecimalField(_('price'), max_digits=10, decimal_places=2)
    phone = models.CharField(_('phone'), max_length=30)
    is_active = models.BooleanField(_('display'), default=True, db_index=True)
    updated = models.DateTimeField(_('updated'), auto_now=True, db_index=True)
    posted = models.DateTimeField(_('posted'), auto_now_add=True)
    def __unicode__(self):
        return self.title
    class Meta:
        verbose_name = _('item')
        verbose_name_plural = _('items')
        ordering = ('-updated', )
    def get_absolute_url(self):
        return reverse('item', kwargs={
            'pk': self.pk,
            'slug': self.slug
        })
    def get_title(self):
        return u'%s' % self.title
    def get_description(self):
        return u'%s' % self.description[:155]
    def get_keywords(self):
       # TODO need more optimal keywords selection
        return ",".join(set(self.description.split()))
    def get_related(self):
       # TODO Need more complicated related select
        return Item.objects.exclude(pk=self.pk)[:settings.DCF_RELATED_LIMIT]
    def save(self, *args, **kwargs):
        if self.slug is None:
            self.slug = slugify(unidecode(self.title))
        super(Item, self).save(*args, **kwargs)

我的views.py:

class ItemCreateView(FormsetMixin, CreateView):
is_update_view = False
model = Item
form_class = ItemCreateEditForm
formset_class = inlineformset_factory(Item, Image, extra=3, fields=('file', ))

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
    if not self.request.user.dcf_profile.allow_add_item():
        messages.error(self.request, _('You have reached the limit!'))
        return redirect(reverse('my'))
    return super(ItemCreateView, self).dispatch(*args, **kwargs)
def form_valid(self, form, formset):
    form.instance.user = self.request.user
    form.save()
    return super(ItemCreateView, self).form_valid(form, formset)

我的forms.py

class ItemCreateEditForm(forms.ModelForm):
class Meta:
    model = Item
    fields = ('group', 'title', 'description', 'price', 'phone', 'is_active')

1 个答案:

答案 0 :(得分:0)

为了与您分享一个有效的解决方案,我创建了User模型的代理模型并更新了我的views.py:

更新了models.py

class DcfUser(User):
    class Meta:
        proxy = True
    def allow_add_item(self):
        if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT:
            return False
        else:
            return True

更新了views.py

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
    user = self.request.user
    my_user = DcfUser.objects.get(username=user)
    if not my_user.allow_add_item():
        messages.error(self.request, _('You have reached the limit!'))
        return redirect(reverse('my'))

谢谢