将request.user.email放在另一个模型字段中

时间:2019-03-10 14:29:57

标签: python django

我尝试从用户模型中获取用户电子邮件,并将其放置在代码正在运行且计数器计数完美的另一个模型的字段中,但添加一行不是代码:

models.py

class Posts(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(blank=True, max_length=100)
    slug = models.SlugField(null=True, blank=True)
    contain = models.TextField(blank=True)
    post_image = models.ImageField(upload_to="post_img", default='post_img/humanity.jpg')
    post_published = models.DateTimeField(blank=True, auto_now_add=True)
    post_updated = models.DateTimeField(blank=True, auto_now=True)
    post_deleted = models.BooleanField(default=False)
    post_approved = models.BooleanField(default=False)
    post_sponsored = models.CharField(max_length=100, null=True, blank=True, default = None)
    post_sponsored_accepted = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug= slugify(self.title)
            super(Posts, self).save(*args, **kwargs)

    def __str__(self):
        return f'Author: {self.author}, Title:{self.title}, Posted: {self.post_published}'

views.py

def post_check(request, pk):
    pos = Posts.objects.get(pk=pk)
    u = UserProfile.objects.get(user=request.user)
    if u.sp_counter < 3:
        pos.post_sponsored = request.user.email
        u.sp_counter += 1
        u.save()
        messages.success(request, 'طلبك قيد المراجعة، الرجاء انتظار الموافقة')
        return redirect('index')
    else:
        messages.warning(request, 'وصلت الحد الاقصى للكفالات')
        return redirect('index')

0 个答案:

没有答案