简体   繁体   中英

Django claas Admin auto-populate user field

I am trying to populate the field 'owner' in the my 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. Need help. Code: forms.py:

class NoteForm(forms.ModelForm):

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

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:

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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