current position:Home>Django form

Django form

2022-06-24 08:58:26My talented girlfriend

Django To ensure the correct display of the form, you need to add CSRF( It is a protection method to prevent cross site requests from being forged and opened by default ), stay <form></form> Add... Between

{% csrf_token %}

 Insert picture description here
In the project settings.py in * ‘django.middleware.csrf.CsrfViewMiddleware’, * introduce , Without this middleware , Manually add .

Upload files

First open path is GET request , If you click upload, it is POST request , If the file content is not empty , Then upload the file , The upload path is... Under the main project media/uploads/, If the path does not exist, create a new .open(os.path.join(path + myFile.name), ‘wb+’) Binary read / write opens the corresponding file ,chunks() Read and write files in blocks .

def upload_file(request):
    if request.method == "GET":
        return render(request, 'app1/upload.html')
    if request.method == "POST":
        myFile = request.FILES.get("myfile", None)
        if myFile:
            path = 'media/uploads/'
            if not os.path.exists(path):
                os.makedirs(path)
            dest = open(os.path.join(path + myFile.name), 'wb+')
            for chunk in myFile.chunks():
                dest.write(chunk)
            dest.close()
            return HttpResponse(" Upload to complete ")
        else:
            return HttpResponse(" No files uploaded ")

Add route .
 Insert picture description here
 Insert picture description here
The file has been uploaded successfully .

Form Forms

Create a new one as follows form.py Write the following code

from django import forms


class UserInfoForm(forms.Form):
    ''' User state '''
    STATUS = ((None, ' Please select '), (0, ' normal '), (1, ' Invalid '),)
    username = forms.CharField(label=" User name ", min_length=6, widget=forms.widgets.TextInput(
        attrs={
    'class': 'form-control', 'placeholder': ' Please enter the user name '}
    ))
    password = forms.CharField(label=" password ", min_length=6, max_length=10, widget=forms.widgets.PasswordInput(
        attrs={
    'class': 'password'}, render_value=True
    ))
    age = forms.IntegerField(label=" Age ", initial=1)
    mobile = forms.IntegerField(label=" Phone number ")
    status = forms.ChoiceField(label=" User state ", choices=STATUS)
    createdate = forms.DateTimeField(label=" Creation time ", required=False)

form field

form field explain
CharField Text input
InterField/FloatField/DecimalField Value input
ChoiceField Select the input box choices Specify the drop-down list
FileField file
BooleanField Check box
DateField/DateTimeField/TimeField/ Time input box , Input format can be set input_format=[“%Y-%m-%d %H:%M”]
EmailField Mail input box
URLField Road strength input box
ModelChoiceField Get the drop-down list from the database

Field parameters

Field explain
labellabel label
label_suffixLabel Label uniform suffix information
initial Initial value
help_text Field description information
error_messages Field description information
validators Validation rule
required Whether must
disabled Whether the field is editable
widget Appoint HTML style

widget Parameters

Parameters explain
PasswordInput Password input box
HiddenInput Hidden elements
Textarea Text domain
CheckboxInput Check box
FileInput File input box
RadioSelect Radio button
DateTimeInput Time input box
Select The drop-down list
SelectMuitiple Checkbox

Configure the view and path to display the corresponding form
app1 Under the views.py

def userinfo_form(request):
    if request.method == "GET":
        myForm = UserInfoForm()

        return render(request, 'app1/userinfo.html', {
    'form_obj': myForm})

userinfo.html

<html>
  <head></head>
  <body>
    <form action="" method="POST">
      {% csrf_token %} {
   { form_obj.as_p }}
      <input type="submit" value=" Submit " />
    </form>
  </body>
</html>

 Insert picture description here

  • as_p Provide... For the form <p> label
  • as_table Provide... For the form <table> label
  • as_ui Provide... For the form <ui> label
    The above uses as_p, So the source code shows p label .
     Insert picture description here

Form validation

  • is_valid() Verify that the form data is legal
  • cleaned_data Get the data that the form has passed the validation
  • errors Error message of form validation

stay form Add the following code to

class UserInfoForm__Msg(forms.Form):
    ''' User state '''
    STATUS = ((None, ' Please select '), (0, ' normal '), (1, ' Invalid '),)
    username = forms.CharField(label=" User name ", min_length=6, widget=forms.widgets.TextInput(
        attrs={
    'class': 'form-control', 'placeholder': ' Please enter the user name '}
    ), error_messages={
    
        'required': ' User name cannot be empty ', 'min_length': ' Length not less than 6 position ', 'invalid': ' Can't contain special characters '
    })
    password = forms.CharField(label=" password ", min_length=6, max_length=10, widget=forms.widgets.PasswordInput(
        attrs={
    'class': 'password'}, render_value=True
    ), error_messages={
    
        'required': ' The password cannot be empty ', 'min_length': ' The password cannot be less than 6 position ', 'max_length': ' The password cannot be redundant 10 position ',
    })
    age = forms.IntegerField(label=" Age ", initial=1, validators=[age_validate], error_messages={
    
        'required': ' Age cannot be empty ',
    })
    mobile = forms.IntegerField(label=" Phone number ", validators=[mobile_validate], error_messages={
    
        'required': ' Mobile number cannot be empty ',
    })
    status = forms.ChoiceField(label=" User state ", choices=STATUS, error_messages={
    
        'required': ' User status cannot be empty ',
    })
    createdate = forms.DateTimeField(label=" Creation time ", required=False)
  • required Error message when empty
  • invalid Format validation error message
  • min_length and max_length Error message that the length is not within the set range

Add view

def userinfo_form_msg(request):
    if request.method == "GET":
        myForm = UserInfoForm__Msg()
        return render(request, 'app1/userinfoform.html', {
    'form_obj': myForm})
    else:
        f = UserInfoForm__Msg(request.POST)
        if f.is_valid():
            print(f.cleaned_data['username'])
        else:
            errors = f.errors
            print(errors)
            return render(request, 'app1/userinfoform.html', {
    'form_obj': f, 'errors': errors})
        return render(request, 'app1/userinfoform.html', {
    'form_obj': f})

Template file

<form action="" method="POST" novalidate>
  {% csrf_token %}
  <p>
    {
   { form_obj.username.label }}:{
   { form_obj.username }} {
   { errors.username.0 }}
  </p>
  <p>{
   { form_obj.password}}{
   { errors.password.0 }}</p>
  <p>{
   { form_obj.status.label }}:{
   { form_obj.status }} {
   { errors.status.0 }}</p>
  <p>{
   { form_obj.age.label }}:{
   { form_obj.age }} {
   { errors.age.0 }}</p>
  <p>{
   { form_obj.mobile.label }}:{
   { form_obj.mobile }} {
   { errors.mobile.0 }}</p>
   Error message summary : {
   { errors }}
  <input type="submit" value=" Submit " />
</form>

 Insert picture description here
The self format verification of the form is also added here , Get data for the form

  • f.clean() Get all the data
  • f.clean_date[] Get the data of the corresponding value
  • f.data Get all the data

Form model file upload example

Template file :upload_form.html

<form enctype="multipart/form-data" action="" method="post">
  {% csrf_token %} {
   { form_obj.as_p }}
  <br />
  <input type="submit" value=" Upload files " />
  <img src="media/uploads/{
   { user.heading }}"
</form>

Model file
stay models.py Add model to , If there is no primary key, it will be generated by default id Primary key of

class ImgFile(models.Model):
    name = models.CharField(verbose_name=' User name ', max_length=300, default="")
    heading = models.FileField(verbose_name=' file name ', upload_to='media/uploads/')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '  User avatar information '
        db_table = 'user_img'

Form model form.py

class ImgFileForm(forms.Form):
    name = forms.CharField()
    heading = forms.FileField()

Model view

If you upload a file , Save the file in the corresponding directory , And return the information of the file .


def ingfileform(request):
    if request.method == "GET":
        f = ImgFileForm()
        return render(request, 'app1/upload_form.html', {
    'form_obj': f})
    else:
        f = ImgFileForm(request.POST, request.FILES)
        if f.is_valid():
            name = f.cleaned_data['name']
            heading = f.cleaned_data['heading']
            path = 'media/uploads/'
            if not os.path.exists(path):
                os.makedirs(path)
            dest = open(os.path.join(path + heading.name), 'wb+')
            for chunk in heading.chunks():
                dest.write(chunk)
            dest.close()

            userimg = ImgFile()
            userimg.name = name
            userimg.heading = heading
            userimg.save()
            print(' Upload successful ')
            return render(request, 'app1/upload_form.html', {
    'form_obj': f, 'user': userimg})
        else:
            print(f.errors)

route
re_path It is configured that the corresponding files can be accessed directly in the browser ,

from django.urls import path, include, re_path
from django.views.static import serve
from mywed import settings
    path('app1/userimg/', views.ingfileform),
    re_path('media/uploads/(?P<path>.*)', serve,
            {
    "document_root": settings.MEDIA_ROOT}),

settings.py
The path here is set in the project file to facilitate unification , In practical applications, it should also be set in public files

MEDIA_URL = "media/uploads/"
MEDIA_ROOT = os.path.join(MEDIA_URL, "")

 Insert picture description here
 Insert picture description here
db The corresponding information is also logged in
 Insert picture description here

Model form

Django Provides ModelForm It can be directly associated with the model , omitted Form Actions defined in the form .

AJAX

Template file , In order to be able to access , You must add csrfmiddlewaretoken Or comment in the view function @csrf_exempt, The first method is recommended

 user name :<input type="text" id="username"></input>
 password :<input type="password" id="password"></input>
{% csrf_token %}
<button id="submit"> Submit </button>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> $("#submit").click(function(){
       var csrf = $('input[name="csrfmiddlewaretoken"]').val(); $.ajax({
       url: '/app1/ajax_login_data', type: "post", data: {
       'username': $("#username").val(), 'password': $("#password").val(), 'csrfmiddlewaretoken': csrf }, success: function(data){
       console.log(data) }, error: function(jqXHR, textStatus, err){
       console.log(arguments); } }); }); </script>

view file

from django.views.decorators.csrf import csrf_exempt
def ajax_login(request):
    return render(request, 'app1/ajax.html')


# @csrf_exempt
def ajax_login_data(request):

    if request.method == "GET":
        HttpResponse(" Internal own url")
    username = request.POST.get('username')
    password = request.POST.get('password')
    print(username)
    if username == 'admin' and password == '123456':
        return JsonResponse({
    
            'code': 1,
            'msg': " Landing successful "
        })
    else:
        print("222")
        return JsonResponse({
    
            'code': 0,
            'msg': " Login failed "

 Insert picture description here
What is used here is online jquery Address , Also available at settings.py Match as follows , Create... In the root directory of the web site static Catalog , Put in jquery file .

<script src=“/statics/jquery.min.js”></script>

STATIC_URL = '/statics/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "statics"),
]

copyright notice
author[My talented girlfriend],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/175/202206240641393209.html

Random recommended