Upload a picture page using Django's ImageField and from production

Source: Internet
Author: User
Tags html form

Requirements Description:

Make a simple registration page that allows users to upload avatars on the registration page.

Workaround:

When you used Java to write this, you need to accept the file with IO on the action, then generate a file name, and then save the relative path to the user table in the IMG field.

On the Django model layer, there is a field called ImageField (and Filefield, which is almost the same), and looking at the description of the field in the document, the general meaning is to automatically save the file in the media folder. The resulting file path is then saved to a field of Var char. If a model has a ImageField field, there will be a var char field in its corresponding table, which is used to save the path.

1. Set the Media_root in setting:

If you use Django's shortcut method, all user-uploaded files should be saved to the Media_root defined folder. Note that absolute paths are required here. My settings are:

# in settings.py

here = Os.path.dirname (Os.path.abspath (__file__))

Media_root = Os.path.join (here, ' media '). replace (' \ \ ', '/') + '/'

This allows the media_root to be set to the media directory under the project directory. Note the last slash, and if you don't add the last slash, there will be a strange error when you save it.

2. Set Model:

For convenience, a user's model has been built:

# in myapp1/models.py

Class User (models. Model):

Name = models. Charfield (max_length=30)

Password = models. Charfield (max_length=30)

Gender_choice = (

(U ' M ', U ' Male '),

(U ' F ', U ' Female '),

)

Gender = models. Charfield (max_length=2,choices = gender_choice)

Birthday = models. Datefield (Null=true)

IMG = models. ImageField (upload_to= ' photo ', null=true,blank=true)

Phonenum = models. Charfield (Max_length=13,null=true,blank=true)

email = models. Emailfield (Null=true,blank=true)

Hobbies = models. Charfield (Max_length=100,null=true,blank=true)

Regtime = models. Datetimefield (Null=true,blank=true)

Bio = models. TextField (null = true,blank=true)

def __unicode__ (self):

Return Self.name

The place to pay attention to here is after null=true, should also add blank=true. Where Null=true is for the database, and Blank=true is for validation. If the blank=true is not added, then when you do the form below, omit the field validation will not pass.

There is an IMG field, which is the ImageField type, which plays a crucial role in quickly making a form for uploading images. There is a sentence upload_to= ' xxxxx ', which is the file stored in Media_root in which subdirectory.

3. Set up the forms from models:

Django has a form class, which abstracts out the HTML form. Using the view, you can generate the HTML for the form in the template. However, you can find that when the user registers, the fields of the form are very similar to the model fields, so you can generate the form class from the model.

In the model class, not all the content needs to be filled out, such as regtime do not need. You can specify that those fields become form fields (using fields= (xxxx)), or you can specify which fields do not become form fields (using exclude= (XXX)). Here, we seem to have only one regtime that does not need to be displayed.

In addition, the password field in our model is Charfield,django not clever enough to generate a form by the meaning of the variable name, so the default generation will be input type= "text" form, we need a way to modify it. In summary, the final form code is this:

# in myapp1/models.py

From django.db import Models

From django.forms import Modelform

From Django Import forms

Class UserForm (Modelform):

Class Meta:

Model = User #通过上面的User model generation form

Exclude = (' Regtime ') #将regTime字段排除在外

Widgets = {

' Password ': forms. Passwordinput (), #将password字段的input type set to Password

}

This makes it possible to create a simple form. There is one difference between the forms from models and the normal form class, which is that it has the save () method, which is used in the view.

4. Call form in view

Here, assume that the registration page is/reg/. If you use the Get method, the registration form is given in the browser, and if you use the Post method, the contents of the form are saved to the database.

If you use the forms from models, it will be very simple on the view:

#in myapp1/views.py

DEF reg (Request):

if Request.method = = ' POST ': #提交表单

form = models. UserForm (Request. Post,request. FILES) #如果表单中要传文件, picture, you need to pass two parameters

If Form.is_valid (): #这个is_valid通过model的配置定义, it shows the meaning of blank=true.

Form.save () #这一句save, not only saved the fields, but also automatically saved the uploaded file to the specified directory, and generated the file path, saved to the user table in the IMG field.

else: #显示表单

form = models. UserForm ()

Return Render_to_response (' reg_form.html ', {' form ': Form})

Use in 5.template:

<body>

<form enctype= "Multipart/form-data" action= "/reg/" method= "POST" >

{{form.as_p}}

<input type= "Submit" value= "Submit"/>

</form>

</body>

This is the same as the normal form. Of course, you can also set the format manually, see the documentation.

Finally configure the Urlpattern, you can upload images in this form.

Insufficient:

There is a disadvantage to this registration form alone, that is, there is no Confirm password this field. But we can add a form field to the UserForm class, and the result will be:

Class UserForm (Modelform):

Confirm_password = forms. Charfield (widget=forms. Passwordinput ())

Class Meta:

Model = User

Exclude (' Regtime ')

Widgets = {

' Password ': forms. Passwordinput (),

}

However, the form generated in the template will place the Confirm_password field at the bottom. So you have to set the format manually. In addition, Form.is_valid () does not monitor password and it is not the same as it needs to be manually added in the rear logic.

The above method is not necessarily the best, but it also provides some ideas. In addition, even if you do not use the forms from models, you can easily save pictures using ImageField:

The problem encountered:

And Media_root should have a media_url. According to reason, Media_root is a public folder, do not need to through the urlpatterns mapping can directly access the files inside (at least Django 1.3 inside Static_root plus static_url can do this), But I have tested it several times and have passed the URL mapping. Currently do not know how to solve.

Attention:

Read the documentation to learn more about the Media_url issue: Django does not automatically open this directory as a static file directory. In the development phase, you use the urlpatterns mapping.
But this is limited to the development phase (same as static files), which, according to Django, is "very inefficient" to map a static file with Urlpatterns, and after entering the use phase, media_root and static_root need to be published to the A true static file server. " This is also why Django itself provides a static file scan, but also provides Python manage.py collectstatic This command to assemble the static files of each app into the Static_root folder.

Upload a picture page using Django's ImageField and from production

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.