程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django form

編輯:Python

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 %}


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 .


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>

  • 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 .

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>


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, "")



db The corresponding information is also logged in

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 "


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"),
]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved