简体   繁体   English

Django claas Admin自动填充用户字段

[英]Django claas Admin auto-populate user field

I am trying to populate the field 'owner' in the my NoteForm. 我正在尝试在我的NoteForm中填充字段“所有者”。 I read in documentation that I need to use the Admin for that.But i still get this error : note_note.owner_id may not be NULL. 我在文档中读到我需要使用Admin。但是仍然出现此错误:note_note.owner_id可能不为NULL。 Need help. 需要帮忙。 Code: forms.py: 代码:forms.py:

class NoteForm(forms.ModelForm):

class Meta:
    model = Note    
    fields = ('title','body')

models.py: models.py:

class Note(models.Model): 
    title = models.CharField(max_length=200)
    body = models.TextField()
    cr_date = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, blank=False)

class NoteAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
       form.owner = request.user
       form.save()

views.py: views.py:

def create(request):
    if request.POST:
        form = NoteForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()

            return HttpResponceRedirect('/notes/all')


    else:
        form = NoteForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('create_note.html', args)

i also tried to write the class NoteAdmin in admin.py , just in case. 我也试图在admin.py中编写NoteAdmin类,以防万一。 Same error.What i am doing wrong? 同样的错误。我在做什么错? I am just following the documentation. 我只是在遵循文档。

You are trying to save Note without owner field and the error said it. 您正在尝试保存没有owner字段的Note ,并且错误提示它。 Try like: 试试:

if form.is_valid():
    obj = form.save(commit=False)
    obj.owner = request.user
    obj.save()

The other way is to set null=True for the owner field if you can write data without owners. 另一种方法是,如果可以在没有所有者的情况下写入数据,则将owner字段设置为null=True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM