8π
Iβm not sure what the point is of wanting to send it to the template. You have it in the view both before and after validation, after all: better to deal with it there.
The thing to do is to exclude the user
field from the form definition, then set it manually on save:
class NoteForm(ModelForm):
class Meta:
model = Note
exclude = ('user',)
if request.method == 'POST':
model_form = NoteForm(request.POST, request.FILES)
if model_form.is_valid():
note = model_form.save(commit=True)
note.user = request.user
note.save()
return...
Also note that your view never sends any validation errors to the template, and your template doesnβt show errors or the invalid values that the user has entered. Please follow the structure set out in the documentation.
2π
You can extend the save method of the form,
def save(self, user):
note = super(NoteForm, self)
note.user = user
note.save()
return note
Also your view must be in this structure:
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
# note: NoteForm.save(request.user)
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
(copied from https://docs.djangoproject.com/en/dev/topics/forms/)
- [Django]-Django static templatetag not displaying SVG
- [Django]-Server lagging β Django + mongodb + cronjob
- [Django]-Converting only one entry of django model object to json
- [Django]-How much flexibility is there in a Django for loop?
- [Django]-Django 1.6 + RabbitMQ 3.2.3 + Celery 3.1.9 β why does my celery worker die with: WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV)
0π
Look here https://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext
- [Django]-Hosting Admin Media Locally During Development
- [Django]-How does djangoproject.com do its deploy to prod? Should I package my django project to deploy it?
- [Django]-Django β how to restrict DeleteView to object owner