Django Admin class to auto-populate user field

2019-09-04 19:47发布

问题:

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)

admin.py

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

    def save_formset(self, request, form, formset, change):
            instances = formset.save(commit=False)
        for instance in instances:
             instance.user = request.user
             instance.save()
        else:
             fromset.save_m2m()


admin.site.register(Note, Noteadmin)

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)

回答1:

I do not understand the point of Admin over here. From the code, what I understood is you creating a simple django form for your site and getting the error on form submission. If that's case, the solution is quiet easy. This error is generated because you are try to save a record in your Note model without any reference to User. As there's a db constraint on the foreign key field, it raises the error. Solution is easy, just add owner to the list of fields in the form or modify the save method to assign an owner to the note. If you'll use the first option, the user will be able to see and select the owner. And if you want to pre-populate that particular field, pass initial value to the form.