Can I have a Form in my template which is not backed by a model. I do not need to store the data just need that data to generate a POST request of my own in the view.
Template - The form with text fields. View - get data from form, and generate another request.
Flow --> Form submit takes to a url which calls the view "
def form_handle(request): if request.method=='POST' form = request.POST #blah blah encode parameters for a url blah blah #and make another post request
but this puts only the csrf token into the form variable. Is there some way I can access those text fields of the template in my form_handle view?
I know how to do it with a model but couldn't figure this out!
The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.
Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.
Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on.
If you are using django to develop your website, I think it is best to only use django-forms since they have built in validation and can easily be linked with your models. You also will have consistent formatting and don't need to type out the html every time.
Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm
, except that you are not bound by the model, and you have to explicitly declare all the form attributes.
def form_handle(request): form = MyForm() if request.method=='POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data #now in the object cd, you have the form as a dictionary. a = cd.get('a') #blah blah encode parameters for a url blah blah #and make another post request #edit : added ": " after if request.method=='POST'
and
class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm a = forms.CharField(max_length=20) #All my attributes here
In the template:
<form action="{% url form_handle %}" method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form>
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