Detailed explanation of multi-form processing on the same page of Django; detailed explanation of django

Source: Internet
Author: User

Detailed explanation of multi-form processing on the same page of Django; detailed explanation of django

Quick Start with Django Implementation Project

Recently, the company is working on a Haitao project. The APP is pylot. Because the time is too short, and the guy next door is not there, he can only pick the lead by himself. As a result, after the project was developed, the project was severely approved by the leaders. How can we use django to write? Can you solve the Django memory problem, and can you solve the concurrency problem? Django is so heavy.

Then I had to answer that it was because of its heavy weight that people used to write large projects. Although this is not for the above two problems, it is about how to quickly develop the prototype.

For a model-based Web framework such as Django, it actually solves a lot of tedious work. Since one model corresponds to one table, the prototype is finished in a short time. In fact, I use Django mainly because I don't need to waste my time on pages, so that I can concentrate on writing APIs.

As a result, in addition to being able to see this project, the company also needs to implement a B-end requirement. At this time, my background functions have been completed. How can this be done. The difference is that only registered users can see their own orders, while others remain unchanged.

As a result, I read the form tutorial in the official document and saw a ModelForm. Through this, I can render the form in the background directly, then, the corresponding model can be directly rendered using the instance keyword in the ModelForm class. In this way, it takes one week to complete the API, client B, and company background, efficiency is relatively high.

The following describes how to quickly implement a project through Django:

  1. In fact, the issue of decomposition is critical. Dividing the issue by level helps speed up development.
  2. Skip code that is not frequently written, write it in a cumbersome way, and then replace it with its built-in method.
  3. Don't be nervous, be sure to stay calm, or you will find that you can't write code at all
  4. Do not read official documents, because it is difficult to find the key points
  5. Search for answers on the Internet with questions. If a certain method is not feasible, use another method. For example, to implement an HTML component with many-to-many relationships, directly find the 3rd-party plug-in instead of reading the document for implementation.

I believe that how can we achieve the above can bring django's efficiency into play. Let's take a look at the detailed introduction in this article.

Django processes multiple forms on the same page

The problem of submitting multiple forms on the same page is actually a small problem encountered in the project. There are two main problems to solve:

  1. Rendering of Multiple Forms
  2. Processing of Foreign keys when multiple forms are submitted

Next we will explain it separately.

At that time, the following method was used during Modeling:

From django. db import models class Store (models. model): name = models. charField ('name', max_length = 20) first = models. floatField ('first weight') additional = models. floatField ('secondary resize') img = models. imageField ('image', upload_to = 'store/1') class Depot (models. model): s_name = models. foreignKey (Store, verbose_name = 'warehouse ') src = models. charField ('origin data', max_length = 20) dest = models. charField ('destination', max_length = 20) days = models. positiveSmallIntegerField ('days required ') class Address (models. model): s_name = models. foreignKey (Store, verbose_name = 'warehouse ') country = models. charField ('state', max_length = 20) state = models. charField ('province ', max_length = 10) city = models. charField ('city', max_length = 10) description = models. textField ('description', blank = True)

Here, the data in a warehouse is mainly composed of three tables, which are basic information, distribution range, days, and other additional information. The page is shown as follows:

Multi-form rendering

The requirement of the company is that we need to allow customers to fill in the above content when creating a warehouse on the merchant's terminal. Because of my laziness, the time provided by the company is not very adequate, therefore, we directly use ModelForm instead of creating forms one by one. In other words, we need to render multiple model tables on the same page. There are four solutions to this problem:

  1. Use multiple model form classes in one form component
  2. Use modelform_factory provided by django
  3. Use plug-ins such as django-betterforms or django-multipleformwizard.
  4. Use the metadata class and inherit the BaseForm to rewrite the form.

Here we use 1st solutions to implement multiple forms rendering.

Here we create three model form classes under the forms module:

from django.forms import ModelForm from models import Store, Address, Depot class StoreForm(ModelForm):  class Meta:  model = Store  fields = '__all__' class AddressForm(ModelForm):  class Meta:  model = Address  exclude = ['s_name'] class DepotForm(ModelForm):  class Meta:  model = Depot  exclude = ['s_name']

Then introduce the three forms in the View:

from django.shortcuts import render_to_response, HttpResponseRedirect from django.template import RequestContext from forms import StoreForm, AddressForm, DepotForm def store_add(req):  if req.method == 'POST':  ...  else:  sf = StoreForm()  af = AddressForm()  df = DepotForm()  return render_to_response('store_add.html', {  'sf': sf, 'af': af, 'df': df,  }, context_instance=RequestContext(req))

By default, the corresponding form is first rendered. Here we output multiple variables to the template, and then manually perform the following processing in the template:

<Form action = "" method = 'post' enctype = 'multipart/form-data'> {% csrf_token %} {sf. as_p }}{{ df. as_p }}{{ af. as_p }}< input type = "submit" value = "add"/> </form>

Here, we output multiple forms in one form. The page is as follows:

We can see that the effect is not very different from that on the background page, but there is no corresponding style.

Multi-form commit foreign key processing

Next, we need to solve the problem when multiple forms are submitted.

def store_add(req):  if req.method == 'POST':  sf = StoreForm(req.POST, req.FILES)  af = AddressForm(req.POST)  df = DepotForm(req.POST)  if sf.is_valid() and af.is_valid() and df.is_valid():  sf.save()  df.save()  af.save()  return HttpResponseRedirect('store')  ...

Here we save the three forms directly, and the result shows such an error.

NOT NULL constraint failed: app_depot.s_name_id 

Because we use a foreign key for constraints, using the above method will cause the value of the s_name_id field in the data table to be NULL, leading to errors. The above method is directly submitted to the database, resulting in the subsequent Foreign keys being unable to meet the requirements.

To solve this problem, we use the method of submitting data to the database by delay:

def store_add(req):  if req.method == 'POST':  ...  if sf.is_valid() and af.is_valid() and df.is_valid():  form = sf.save(commit=False)  sf.save()  dform = df.save(commit=False)  dform.s_name = form  dform.save()  aform = af.save(commit=False)  aform.s_name = form  aform.save()  return HttpResponseRedirect('store')  else:  ...

Here, we will not commit the first 1st tables and save them as one variable form. The first 2nd tables are not submitted. We will change the s_name of the instance to the result returned by the previous 1st tables, and then save the result. In this way, the dependency of multiple tables is implemented. Finally, we use redirection to redirect the successfully added page to the repository list of the merchant.

The displayed page is as follows:

This solves the problem of submitting multiple forms on one page. In fact, there are not many issues concerning how Django submits multiple forms on one page. As long as the rendering and submission processing problems are solved, the problem is solved. What is important is how to split the problem and solve the problem.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.