'django: how to save ModelForm data with foregin key?
I'm face an issue while saving data to database! let me explain..... I'm trying to make a app like blog... & there is a comment section. There have three fields for submit comment.... name, email & message. but when someone submit an comment it should save into database for a specific blog post, so I've defined a foreign key on comment model. but its not work! whenever I submit it show NOT NULL constraint failed error! even if I change this table null=True then it doesn't show any error but it don't save any foregin key! please help me!
models.py
from django.db import models
from ckeditor.fields import RichTextField
class Event(models.Model):
title = models.CharField(max_length=255)
description = RichTextField()
thumb = models.ImageField(upload_to="events")
amount = models.IntegerField()
location = models.CharField(max_length=255)
calender = models.DateField()
def __str__(self):
return self.title
class Comment(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
username = models.CharField(max_length=255, null=False, blank=False)
email = models.EmailField(max_length=255, null=False, blank=False)
message = models.TextField(null=False, blank=False)
date = models.DateField(auto_now_add=True)
def __str__(self):
return self.username
forms.py
from django.forms import ModelForm, TextInput, EmailInput, Textarea
from .models import Comment
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ["username", "email", "message"]
widgets = {
"username": TextInput(attrs={"placeholder":"Name *"}),
"email": EmailInput(attrs={"placeholder":"Email *"}),
"message": Textarea(attrs={"placeholder":"Message"})
}
views.py
from django.shortcuts import redirect
from django.views.decorators.http import require_http_methods
from .forms import CommentForm
@require_http_methods(["POST"])
def comment(request):
form = CommentForm(request.POST)
if form.is_valid():
form.save()
return redirect("event")
Solution 1:[1]
You have to assign each comment to a specific event so in your views.py you have to get specified event. For doing this, one way is pass id of event through url as parameter, for example in your urlpattern you can make a path like this:
urlpatterns = [
# your paths
path('<int:event_id>/', views.comment())
]
and in your views.py :
# parameters request & event_id
@require_http_methods(["POST"])
def comment(request, event_id):
form = CommentForm(request.POST)
if form.is_valid():
# get event by id
try:
event = Event.objects.get(id=event_id)
except ObjectDoesNotExist:
# redirect to somewhere because the event does not exists
return redirect()
# and last step
comment = form.save(commit=false)
comment.event = event
comment.save()
return redirect("event")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
