Win7
Python2.7
Django 1.6.5
Because the database SQLite is used and the project contains models. py, forms. modelform is easy to use to process forms.
The default defastorage storage is used to upload image files.
1. Add two media definitions in settings. py:
#MediaMEDIA_ROOT = 'e:/Depot/media'MEDIA_URL = '/media/'
2. Models. py
# Coding: utf8from Django. DB import modelsclass product (models. model): Title = models. charfield (max_length = 50, verbose_name = 'title') Description = models. textfield (verbose_name = 'description') Photo = models. imagefield (upload_to = 'product', verbose_name = 'image') Price = models. decimalfield (max_digits = 8, decimal_places = 2, verbose_name = 'price ')
3. Forms. py
from django import formsfrom models import *class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['title', 'description', 'photo', 'price']
No other code is written.
4. Views. py
def create_product(request): #create new if request.method == 'POST': form = ProductForm(request.POST or None, request.FILES) if form.is_valid(): form.save() return render(request, 'depot2/create_product.html', locals())
There are image fields in the Data. Therefore, when instantiating the Form class, add 2nd parameters requst. Files.
The model is used here, so you do not need to manually assign values to the request. File field.
5. Template File
To display the HTML file of a form, you only need to note that when uploading a file, add enctype = "multipart/form-Data" to the <form> label ".
This parameter must be set to the 2nd value of views.
Otherwise, you can see the data in the submitted Form and view, but you cannot submit the data to sqlite3 or upload files.
To create a media folder in the project root directory, you can see that a sub-directory is created under the name of upload_to.
After models. py is created, Django-groundwork is used to generate code and templates.
Learning about this storyMethodI wrote Django practice, but he didn't use the imagefield field, so I stuck it here.
It also shows that you are familiar with HTML Object Attributes and are more useful than you are familiar with Python syntax.
To use a media image, go to the main URL. py file as follows:
from django.conf.urls import patterns, include, urlfrom django.conf.urls.static import staticfrom django.contrib import adminimport settingsadmin.autodiscover()urlpatterns = patterns('', # Examples: # url(r'^$', 'depot.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)),)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
However, the above is only used for testing, saying that the production environment should be released as static.