[Answered ]-Model with instance won't save to DB but no error message in Django

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:

  1. 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 a KeyError (as the key will not be in the session). Using the get method of dictionaries will suppress this error. Instead, if the key doesn’t exists, the method will return None. If the session has expired, we should not move forward – so we redirect to the root.

  2. 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.

  3. 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}) 

Leave a comment