当新数据保存在Django中时,如何记录当前用户?

时间:2019-05-24 12:42:00

标签: python django python-3.x django-models

在Django中保存新记录时,我正在尝试保存当前用户。我尝试了一些代码,但似乎缺少一些东西。

在我的模式下,我已经为User表创建了ForeignKey,并且正在使用基于通用类的视图。试图使用save_model函数保存当前用户,但操作不正确。

这是我的代码:

我的模型。py:

from django.utils import timezone
from django.conf import settings


class Backlinks(models.Model):

    link = models.URLField(max_length=100,verbose_name="Link")
    keyword = models.CharField(max_length=100,verbose_name="Anahtar Kelime")
    created_date = models.DateTimeField(default=timezone.now,verbose_name="Eklenme Tarihi")
    end_date = models.DateTimeField(default=timezone.now,verbose_name="Bitiş Tarihi")
    description = models.TextField(null=True,blank=True,verbose_name="Ek Bilgi")
    source = models.URLField(max_length=100,verbose_name="Kaynak")
    author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,verbose_name="Kullanıcı",null=True,blank=True)


    def __str__(self):
        return self.link

    class Meta:
        verbose_name = 'Backlink'
        verbose_name_plural = 'Backlinkler'

这是我的views.py:

class LinkCreate(LoginRequiredMixin,CreateView):
    model = Backlinks
    form_class = YeniForm
    success_url = "/"
    login_url = "/hesap/login/"

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()

当我尝试保存表单时,出现此错误:

IntegrityError at /ekle/
NOT NULL constraint failed: backlinks_backlinks.author_id

谢谢。

0 个答案:

没有答案