1👍
✅
Thanks @dan-klasson for the Help.
I finally figured Out How to do this :
Firstly in My CommentsInline
Class i had to add a method to update the formsets like this :
admin.py
from django.core import serializers
from django.http import HttpResponse
from django.utils import timezone
from django.contrib import admin
from .models import Post, Comment
from .forms import CommentInlineFormset
# Register your models here.
class CommentsInline(admin.StackedInline):
model = Comment
extra = 1
fields = ['comment_text']
formsets = CommentInlineFormset
def get_formset(self, request, obj=None, **kwargs):
formset = super(YourInline, self).get_formset(request, obj, **kwargs)
formset.request = request
return formset
class PostAdmin(admin.ModelAdmin):
fieldsets = [
('Content', {'fields': ('title', 'body', 'is_published')}),
('Date Information', {'fields': ('pub_date', )})
]
inlines = [CommentsInline]
def save_model(self, request, obj, form, change):
obj.author = request.user
if not obj.id:
obj.created_date = timezone.now()
obj.updated_date = timezone.now()
super(PostAdmin, self).save_model(request, obj, form, change)
admin.site.register(Post, PostAdmin)
and In my forms.py
from django import forms
from django.utils import timezone
class CommentInlineFormset(forms.models.BaseInlineFormSet):
def save_new(self, form, commit=True):
obj = super(CommentInlineFormset, self).save_new(form, commit=False)
# here you can add anything you need from the request
obj.user = self.request.user
obj.created_on = timezone.now()
if commit:
obj.save()
return obj
0👍
I haven’t tried, this but something like this should work:
def save_related(self, request, form, formsets, change):
post = form.instance
post.user = request.user
post.updated_at = timezone.now()
super(PostAdmin, self).save_related(request, form, formsets, change)
- Django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username
- Why is django displaying white lite on top of the page when using bootstrap
Source:stackexchange.com