Comment

Comment by vivekd

you reference the model in the view and then tell the view to save it directly to the model using the "model = form field" type syntax to assign value and then .save() method to save.

In the form field you are saving from, you write the form field value and then an empty space where the input value goes sort of like "form.cleaned_data.get("field name", " "). The second blank ""is the empty space where the field value goes. The claned_data is django's internal form validator. That sounds confusing so I'll give an example

This is what your views would look like

    from django.shortcuts import render

    from sample.models import Test

    from sample.forms import TestForm

    def Example(request):

       if request.method == 'POST':

           form = TestForm(request.POST)

           if form.is_valid():

              testmodel = Test()

              testmodel.modelfield1 = form.cleaned_data.get('formfield1','')

              testmodel.modelfield2 = form.cleaned_data.get('formfield2','')

              testmodel.save()
            
              return render(request, 'sample/nextpage.html') 

        else:

            form =TestForm

            context_data = {'form':form}

            return render(request, 'sample/testformpage.html', context_data)
parent vivekd 9 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton