I would like to fill in the “author” field in a FORM well before the SAVE_MODEL starts.
So when the user get the EntryForm it has to has predefined data in it.
I use two keys “author” and “title”.
My problem is when I enter the same title using same user on second time, I get error message on SAVE_MODEL.
Exception Value: UNIQUE constraint failed: blog_entry.author_id, blog_entry.title
It seems the “EntryForm” will not fill in the “author” fields
Also, when I debug it, it does not stop at clean_author() or clean_last_modified_by() functions in FORMS.PY.
May I ask your help, please?
Models.py
from django.db import models
import datetime
from django.contrib.auth.models import User
# Create your models here.
class Entry(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField()
pub_date = models.DateField(default=datetime.datetime.today)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='entries',
blank=True)
body = models.TextField()
last_modified = models.DateTimeField(auto_now=True)
last_modified_by = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='entry_modifiers',
blank=True)
class Meta:
# unique_together = ('author', 'title')
constraints = [
models.UniqueConstraint(fields=['author', 'title' ], name ='unique_title_by_user')
]
forms.py
from django.contrib.auth.models import User
from django import forms
from blog.models import *
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = '__all__'
def clean_author(self):
if not self.cleaned_data['author']:
return User()
return self.cleaned_data['author']
def clean_last_modified_by(self):
if not self.cleaned_data['last_modified_by']:
return User()
return self.cleaned_data['last_modified_by']
admin.py
from django.contrib import admin
from blog.forms import *
# Register your models here.
class EntryAdmin(admin.ModelAdmin):
form = EntryForm
list_display = ('title', 'pub_date', 'author')
prepopulated_fields = { 'slug': ['title'] }
readonly_fields = ('last_modified', 'last_modified_by',)
fieldsets = ((
None, {
'fields': ('title', 'body', 'pub_date')
}), (
'Other Information', {
'fields': ('last_modified', 'last_modified_by', 'slug'),
'classes': ('collapse',)
})
)
def save_model(self, request, obj, form, change):
# if not obj.author.id:
if not obj.id:
obj.author = request.user
obj.last_modified_by = request.user
obj.save()
admin.site.register(Entry, EntryAdmin)