On Jan 13, 3:58 pm, Roboto <robc...@gmail.com> wrote: > Hi everyone, > I've been building with Django for a while now [having learned Python > at the same time], I am about to start my next project and looking > back into some of my older code I can see right away that it's a > terrible way to code Django. > > For instance: > Task: Build a web form that can will add, or edit an entry and save it > to the database. > > A quick glimpse at my code reveals the following [Actually it's > embarrassing looking at it because it's so basic]: > My question is --- what is the best way to minimize code, keep it > cleaner, and simply adhere to DRY. I'm stumped! I've seen a couple > of different methods of how people handle this, but I've never been > sure as to why. > > Any thoughts would be appreciated > > views.py > def viewSaveEditWebform(request, pid = None): > if request.POST: > form = webForm(request.POST) > if form.is_valid() > if pid: > p = p.objects.get(id = pid) > p.Item1 = form.cleaned_data[item1] > p.Item2 = form.cleaned_data[item2] > p.Item3 = form.cleaned_data[item3] > p.save() > else: > p = pModel(Item1 = form.cleaned_data[item1], Item 2 = > Form.cleaned_data[item2], Item 3 = Form.cleaned_data[item3]) > p.save() > else > if pid: > p = p.objects.get(id = pid) > form.item1 = p.item1 > form.item2= p.item2 > form.item3 = p.item3 > else: > form = webForm()
You should be using a ModelForm, which takes care of creating and updating the model instance for you. This cuts your code down massively: def viewSaveEditWebform(request, pid=None): if pid: p = pModel.objects.get(id=pid) else: p = pModel() if request.POST: form = webForm(request.POST, instance=p) if form.is_valid(): p.save() return HttpResponseRedirect(reverse('success_view')) else form = webForm(instance=p) return render_to_response('template.html', {'form':form}) -- DR.
-- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.