2👍
You are passing the wrong instance to the form, because the form is for the Message
model, not your AboutMe
model.
Here is the corrected version, along with some additional checks:
-
You should always make sure you have a valid session. If you have
request.session["AboutMe_id"]
and the session has expired, you’ll get aKeyError
(as the key will not be in the session). Using theget
method of dictionaries will suppress this error. Instead, if the key doesn’t exists, the method will returnNone
. If the session has expired, we should not move forward – so we redirect to the root. -
Even if the session is valid – it may not contain a valid value for your model. In that case, this
AboutMe.objects.get(pk=myid)
will raise an exception. To prevent that, we wrap it in a try/except block. If the object doesn’t exists, it means the value from the session is invalid. We delete the key and then redirect the user to the root. -
Finally, you should always have a condition if the form is invalid; so I added that check as well.
The rest of the changes are mainly formatting. Method names should start with lowercase letters, as should normal names. Only class names should be in InitialCaps.
def contact(request):
myid = request.session.get("AboutMe_id")
if not myid:
# session has expired
return redirect('/')
try:
sender = AboutMe.objects.get(pk=myid)
except AbouMe.DoesNotExist:
# Invalid id in session
del request.session['AboutMe_id']
return redirect('/')
messageForm = ContactForm(request.POST or {})
if request.method == "POST":
if messageForm.is_valid():
message = messageForm.save(commit=False)
message.MyRead = False
message.MyDeleted = False
message.MySpam = False
message.MyDate = datetime.date.today()
message.MyTime = timezone.now()
message.MyToID = 1
message.MyFromID = sender
message.save()
return redirect('/')
else:
# form is not valid
return render(request, "contact.html", {'form': messageForm})
else:
# return empty form
return render(request, 'contact.html', {'form': messageForm})