Save data from form

34 views
Skip to first unread message

Артём Мутерко

unread,
Sep 6, 2014, 3:27:23 PM9/6/14
to django...@googlegroups.com
Hello, can anyone please explain how to handle form post action and save it to database

Eddilbert Macharia

unread,
Sep 7, 2014, 3:50:55 AM9/7/14
to django...@googlegroups.com
Hi Aptem,

Your questions is not clearly what exactly do you want, where are you stuck, specifically,
Check this it might assist you https://docs.djangoproject.com/en/1.7/topics/forms/

this is a very basic example if you have an organization mode below

models.py
class Organization(models.Model):
name = models.CharField(max_length=25)

create a forms module and add this
form.py
class NameForm(form.Form):
name = forms.CharField(max_length=25)
 
 view.py
import the model and form to you view
def organization_save(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
cleaned_name = form.cleaned_data['name']
            # save form if its new organization creation
 organization = Organization.objects.create(name=cleaned_name)
        # if its an existing organizanization
organization = Organization.objects.get(id='the id of the organization')
organization .name = cleaned_name
organization .save()
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})


there is an easier way of doing this by use of modelforms check this out  https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/

Hope it assists you.

Regards,
Eddilbert Macharia.

Артём Мутерко

unread,
Sep 7, 2014, 9:17:42 AM9/7/14
to django...@googlegroups.com
Thank you a lot for reply. I thought I could cover Django on fly, but it seems like I have to read some books before. Anyway thank you very much!

воскресенье, 7 сентября 2014 г., 10:50:55 UTC+3 пользователь Eddilbert Macharia написал:

Eddilbert Macharia

unread,
Sep 8, 2014, 2:49:40 AM9/8/14
to django...@googlegroups.com
Hello,

Your welcome, its not that difficult to wrap head around django though, just patience is required

Regards,
Eddilbert Macharia.
Reply all
Reply to author
Forward
0 new messages