I need to have a form that allows the creation or addition of sessions on a planning
class Session(models.Model):
tutor = models.ForeignKey(User)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
class SessionForm(forms.ModelForm):
class Meta:
model = Session
exclude = ['tutor']
def editor(request):
if request.method == 'GET':
if request.GET['id'] != '0':
# The user has selected a session
session = Session.objects.get(id=request.GET['id'])
form = SessionForm(instance=session)
else:
# The user wants to add a new session
form = SessionForm()
return render_to_response('planner/editor.html',
{'form': form,}, context_instance=RequestContext(request),)
<form action="/planner/post" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
def post(request):
if request.method == 'POST':
form = SessionForm(request.POST)
if form.is_valid():
form.instance.tutor = request.user
form.save()
obj = {'posted': True}
return HttpResponse(json.dumps(obj), mimetype='application/json')
else:
return render_to_response('planner/editor.html',
form, context_instance=RequestContext(request),)
Sessions are always created (never updated)
post
how do I know that the session must be updated and not created ?If you want to update a session, you need to provide the instance when you bind the form.
If the form is valid, you can then save with commit=False
, and update the tutor.
form = SessionForm(instance=instance, data=request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.tutor = request.user
instance.save()
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.template import RequestContext
from application.models import Session
from application.forms import SessionForm
def allInOneView(request):
session_id = request.POST.get('session_id')
if session_id:
session = get_object_or_404(Session, pk=session_id)
else:
session = None
"""
A subclass of ModelForm can accept an existing model instance
as the keyword argument instance;
if this is supplied, save() will update that instance.
If it's not supplied, save() will create a new instance of the specified model.
"""
form = SessionForm(instance=session)
if request.method == 'POST':
form = SessionForm(request.POST, instance=session)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.path)
return render_to_response('planner/editor.html', {
'form': form
}, context_instance=RequestContext(request))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With