我无法保存与User对象相关的对象

时间:2019-02-23 02:38:32

标签: django

我正在尝试将一个实例添加到Books模型中,该实例是使用ModelForm的继承形式添加的,并且添加了Books实例,但是我无法将用户字段与User模型相关联。

forms.py

from django import forms
from .models import Books

class BooksCreationForm(forms.ModelForm):

    class Meta:
        model = Books
        fields = ('title',
                  'language', 'status', 'short_desc',
                  )

models.py

User = settings.AUTH_USER_MODEL

class Books(models.Model):
    STATUS_CHOICES = (
        ('Reading', 'Reading'),
        ('Finished', 'finished'),
    )
    user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='books',null=True)
    title = models.CharField(max_length=120)
    short_desc = models.TextField(max_length=1000)
    slug = AutoSlugField(populate_from='title', overwrite=True)
    language = models.CharField(max_length=20, blank=True)
    status = models.CharField(max_length=35, choices=STATUS_CHOICES)

views.py

class AddBooksView(View):
    # ....
    def post(self, request, *args, **kwargs):
        template = self.template
        form = self.form(request.POST)
        # ?? user = User.objects.get(request.user)
        user = User.objects.get(username=request.user.username)
        if form.is_valid():
            form.save(commit=False)
            form.user = user
            form.save()
            print("book post sucess")
            return redirect('main:books')

        context = {'form': self.form()}
        return render(request, template, context)

但是当我添加外壳程序时,就可以了:

>>> u = User.objects.get(username='marcos')
>>> u.email
'marcos@marcos.com'
>>> bk = Books.objects.create(title='stackoverflow', language='Python', status='reading', short_desc='desc...')
>>> bk.title
'stackoverflow'
>>> bk.user = u
>>> bk.user.username
'marcos'
>>> bk.save()
>>> for v in Books.objects.filter(user=u):
...     print(v.title, v.user.username)
...
stackoverflow marcos

我尝试通过ModelForm保存的几个实例的用户=无:

>>> for v in Books.objects.all():
...     print(v.user, v.title)
...
None Pyhon2
None dfdsffffff
None fgdfdfd
None fgdfgfg
marcos stackoverflow # that i add before using shell

我还尝试在视图中删除用户并以以下形式使用它:

class BooksCreationForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        return super(BooksCreationForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        kwargs['commit'] = False
        instance = super(BooksCreationForm, self).save(*args, **kwargs)
        if self.request:
            instance.user = self.request.user
        instance.save()
        return instance

    class Meta:
        model = Books
        fields = ('title',
                  'language', 'status', 'short_desc',
                  )

2 个答案:

答案 0 :(得分:1)

您必须获取新的图书实例并将其分配给用户,而不是try形式:

    if form.is_valid():
        book = form.save(commit=False)
        book.user = user
        book.save()
        return redirect('main:books')

在此处查看示例Form's save method

答案 1 :(得分:0)

尝试将AddViews用于CreateView的方式为:

class AddBooksView(CreateView):
    # ...
    #specify your form
    def form_valid(self, form):
        form.save(commit=False)
        form.user = self.request.user
        form.save()
        print("book post sucess")
        return redirect('main:books') 
    #...

供参考,请点击以下链接:http://melardev.com/eng/blog/2017/11/04/createview-django-4-examples/