So, I built a listview which works fine. I was also able to add the form onto the same page as the listview. However, when I submit the form, the listview does not get updated with the recent form I submitted. I also get a strange error as well. I am not sure what went wrong.
views.py
class BlogListView(ListView, ModelFormMixin):
model = Post
context_object_name = 'blog_list'
template_name= 'blog/blog_home.html'
cats = Category.objects.all()
ordering = ['-post_date']
form_class = PostForm
def get(self, request, *args, **kwargs):
self.object = None
self.form = self.get_form(self.form_class)
return ListView.get(self, request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = None
self.form = self.get_form(self.form_class)
if self.form.is_valid():
self.object = self.form.save()
return self.get(request, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(BlogListView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
context["form"] = self.form
return context
urls.py
path('',BlogListView.as_view(),name='blog_home'),
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields =('title', 'category', 'body')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
}
blog_home.html:
<div class="card-body">
<form action="" method="post">
<div class="form-group">
{% csrf_token %}
{{ form.media }}
{{ form|crispy }}
<input type="submit" value="Post"/>
</div>
</form>
</div>
Error when form method is "post":
IntegrityError at / null value in column "author_id" violates not-null constraint DETAIL: Failing row contains...
Error when form method is "get":
GET /?csrfmiddlewaretoken
Edited: models.py
class Post(models.Model):
id = models.UUIDField(
primary_key = True,
default = uuid.uuid4,
editable = False)
title = models.CharField(max_length=200)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
...