Form 'POST' to a database

61 views
Skip to first unread message

JJ Zolper

unread,
Jul 10, 2012, 11:48:14 PM7/10/12
to django...@googlegroups.com
I honestly just have a general question.

If I have one database set in my settings file in settings.py and I try to execute a simple HTML Form using 'POST' how do I get that data into my PostgreSQL database?

In my view do I have to interface with my model and thus the model takes care of the rest?


This link seems to be down the right road I think?

I'm sorry if this question does not make a lot of sense but I really am trying to find some direction as to how once I have a view, model, urlconf, and settings file with a database tied to it (i checked using the import django.db connection/cursor test) how do I get the request.POST data sent to my database?

Thanks,

JJ

Lee Hinde

unread,
Jul 11, 2012, 12:31:44 AM7/11/12
to django...@googlegroups.com
I recommend the tutorial. It walks you through the process, soup to nuts.


Message has been deleted

JJ Zolper

unread,
Jul 11, 2012, 11:36:39 AM7/11/12
to django...@googlegroups.com
I guess on Part 4 is what I need...

So hmmm.

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
So originally:

        selected_choice = p.choice_set.get(pk=request.POST['choice'])
this requests the submitted choice from the POST data and 

The part that says:

        selected_choice.votes += 1
        selected_choice.save()
Actually saves the choice to the database?

Is it just two lines? requesting the data form request.POST and then that variable.save() to store it in the database?

JJ

Andre Schemschat

unread,
Jul 11, 2012, 11:51:19 AM7/11/12
to django...@googlegroups.com
Hey,

yeah, it basicly is. Just a very, very basic example (And sorry if i could highlight this as code, i didnt find something in the format-menu :/ ).
Of course you should validate your input first. And if you just want to edit a Model within a form, you should check on the ModelForm-Class https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

def vote(request, poll_id):
    try:
        obj = YourModel.objects.get(pk=poll_id)
        obj.attributea = request.POST['attributea']
        obj.attributeb = request.POST['attributeb']
        obj.save()
        return HttpResponse(validparamshere)
    except ObjectDoesNotExist:
        return HttpResponse(show_some_error)


Message has been deleted

Jani Tiainen

unread,
Jul 11, 2012, 2:50:21 PM7/11/12
to django...@googlegroups.com
Django makes always (at least currently) full record update (iow: there is no dirty flag for fields).

Example given is "poor" in the sense that it uses directly POST data. I strongly would suggest leveraging modelforms when ever possible - it saves time and nerves. You get all the validation and other goodies for free.

On Wed, Jul 11, 2012 at 8:09 PM, Dennis Lee Bieber <wlf...@ix.netcom.com> wrote:
On Wed, 11 Jul 2012 08:36:39 -0700 (PDT), JJ Zolper
<codin...@gmail.com> declaimed the following in
gmane.comp.python.django.user:



> So originally:
>
>         selected_choice = p.choice_set.get(pk=request.POST['choice'])
>
        If I understand this (I've not run the tutorial, and only browsed
the now-outdated print books), this statement is using the value from
the "choice" field of the submitted form as the primary key to retrieve
a record (model instance) from the database.

pseudo-SQL
select * from choice_set where pk = "request.POST['choice']"


> this requests the submitted choice from the POST data and
>
> The part that says:
>
>         selected_choice.votes += 1
>         selected_choice.save()
>
> Actually saves the choice to the database?
>
        This then increments the votes field of the record (model instance)
retrieved from the database, and then saves the record back.

p-SQL
update choice_set set
        votes = votes + 1
where pk = selected_choice.pk

{I don't know if Django is smart enough to only update the changed
field, or if it updates the entire record}
--
        Wulfraed                 Dennis Lee Bieber         AF6VN
        wlf...@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.




--
Jani Tiainen

- Well planned is half done, and a half done has been sufficient before...

JJ Zolper

unread,
Jul 11, 2012, 9:44:31 PM7/11/12
to django...@googlegroups.com
I was able to make it work!

from django.core.context_processors import csrf
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from MadTrak.manageabout.models import AboutMadtrak, AboutMadtrakForm

def about(request):
AboutMadtrakInstance = AboutMadtrak()
result = AboutMadtrakForm(request.POST, instance=AboutMadtrakInstance)
result.save()
        return HttpResponse('It worked?!? Of course it did. I knew that.')

def about_form(request):
    return render_to_response('about_form.html', context_instance = RequestContext(request))

I ended up looking at ModelForms and trying that since I was having issues.

So does this method handle all validation and security issues for me?

Or do I still need a "result.is_valid()" among other things?

JJ Zolper

unread,
Jul 11, 2012, 9:44:54 PM7/11/12
to django...@googlegroups.com
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

JJ Zolper

unread,
Jul 11, 2012, 9:46:29 PM7/11/12
to django...@googlegroups.com
On Wednesday, July 11, 2012 1:09:32 PM UTC-4, Dennis Lee Bieber wrote:
On Wed, 11 Jul 2012 08:36:39 -0700 (PDT), JJ Zolper
<codin...@gmail.com> declaimed the following in
gmane.comp.python.django.user:


> So originally:
>
>         selected_choice = p.choice_set.get(pk=request.POST['choice'])
>
        If I understand this (I've not run the tutorial, and only browsed
the now-outdated print books), this statement is using the value from
the "choice" field of the submitted form as the primary key to retrieve
a record (model instance) from the database.

pseudo-SQL
select * from choice_set where pk = "request.POST['choice']"

> this requests the submitted choice from the POST data and
>
> The part that says:
>
>         selected_choice.votes += 1
>         selected_choice.save()
>
> Actually saves the choice to the database?
>

Jani Tiainen

unread,
Jul 13, 2012, 5:24:18 PM7/13/12
to django...@googlegroups.com
You still need to call result.is_valid() since it actually runs actual validation rules.

Very basic form processing is usually done like this:

so in case of GET you return empty form. in case of invalid POST you return form with values and error messages.

After successful POST you do redirect-after-post to avoid problems with browser history back-button.

def form_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/some/result/form")
    else:
        form = MyForm()    
    return HttpResponse("form/form.html", { 'form': form })

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/JTdViX4I6HEJ.

To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

JJ Zolper

unread,
Jul 13, 2012, 9:20:38 PM7/13/12
to django...@googlegroups.com
Thank you so much for the clarification!
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Reply all
Reply to author
Forward
0 new messages