How To Post My Html Form To Django Model And Save It?
Solution 1:
You have to pass user instances to your views.py.
Change your views.py as showed below,
views.py:
@login_required()
def userinfo(request):
user = request.user
form = NewMailForm(request.POST or None)
if request.method == 'POST':
if not form.is_valid():
print form.errors
return render(request,'')
else:
sender = user
receiver = form.cleaned_data.get("receiver")
subject = form.cleaned_data.get("subject")
message = form.cleaned_data.get("message")
b = Mail.objects.create_user(
sender=sender,
receiver=receiver,
subject=subject,
message=message)
b.save()
return render(request, 'account/userinfo.html')
and forms.py:
<formaction="."method="POST">{% csrf_token %}
{{ form.as_p }}
</form>This will create a new mail objects with requested user.
Solution 2:
In your views.py create an instance of your model for example m = Mail() then post each of the field using the instance for example m.receiver = request.POST.get('receiver') then save with m.save()
Solution 3:
Before a Many2many field can be linked Django needs the id of the record on the other side of the relationship (in this case your Mail) model.
So you have to actually create it before setting the receiver like this:
b = Mail.objects.create(sender=sender, subject=subject, message=message)
b.receiver = receiver
b.save()
Solution 4:
You have made several mistakes:
forms.py is not required if you have made an HTML form and linked to project.
You have not defined b. Just written
b.save
Just debug these errors and you are Done!
Post a Comment for "How To Post My Html Form To Django Model And Save It?"