Detailed Explanation of the Use of ImageField in django
- 2021-08-31 08:29:22
- OfStack
Use process
1. Configure setting file 2. Add ImageField attribute in model
3. Form form class
4. html template file (add dishes)
5. Display html template file for dishes
6. Static path
7. Modify uploaded images
8. Set the default picture
References:
Notes on the use of ImageField
Today, the improvement of the order system for homework writing is mainly to add pictures to every dish, which looks more beautiful, but I didn't expect this small demand to take me one day, and it was recorded, which increased my knowledge.
Use process
1. Configure the setting file
MEDIA_ROOT represents the root directory of uploaded pictures, and MEDIA_URL represents the prefix of url when accessing files.
# Image storage root path
MEDIA_ROOT = join('media')
# Picture access url
MEDIA_URL = '/IMG/'
2. Add ImageField attribute to model
up_load1 must be configured, which means that your last image will be stored in the folder MEDIA_ROOT/up_load (actually the name you gave it).
class Menu(models.Model):
"""
Food database
"""
ID = models.BigAutoField(primary_key=True,editable=False)
lastEditTime = models.DateTimeField(auto_now_add=True)
merchantID = models.ForeignKey(Usr, verbose_name=" Merchant account number ", on_delete=models.CASCADE,to_field='ID')
itemName = models.CharField(max_length=20,verbose_name=" Meal name ")
itemText = models.TextField(verbose_name=" Brief introduction of food ")
price = models.FloatField(verbose_name=" Food price ")
################# up_load Represents the name of the folder where you upload pictures
picture = models.ImageField(verbose_name=' Meal pictures ',null=True,upload_to='img/')
class Meta:
db_table = "Menu"
verbose_name = " Food data sheet "
ordering=['-lastEditTime']
3. Form form class
This project uses the Form form class that comes with django to transfer data.
class MerchantDish(forms.Form):
"""
Submission form of merchant dishes
"""
itemName = forms.CharField(max_length=20,label=" Meal name ")
itemText = forms.CharField(max_length=300,label=" Brief introduction of food ")
price = forms.FloatField(label=" Food price ")
picture = forms.ImageField(label=' Meal pictures ')
4. html template file (add dishes)
Note 1 Be sure to add: enctype= "multipart/form-data".
<form action="updateDish_post/" method="post" enctype="multipart/form-data">
{% csrf_token %} {{form.as_p}}
<button type="submit"> Modify </button>
<button type="button"><a href="/MerchantSystem/DelDish/{{dishID}}/" rel="external nofollow" > Delete </a></button>
</form>
5. html template file showing dishes
What is important is the configuration of the path in src. There are two methods. Suggest method 1. I feel safer. Even if there is no picture, I will not report an error. (Note: You can resize the image display)
Fa1:/IMG (your own defined MEDIA_URL)/{{dish. picture}}--dish represents the dish coming from the back end, and dish. picture represents the field in the class you use that has the ImageField attribute;
Method 2: {{dish. picture. url}} Because ImageField is a file class, there are three attributes name, path and url that can be accessed directly.
{% for dish in menu %}
<!-- Displays the data of the directory in the html Medium -->
<!-- Submit to 1 Parameterized url Pay attention to the reception of the back end -->
<form action="/MerchantSystem/Dish/{{dish.ID}}/" method="post">
{% csrf_token %}
<li class="media">
<div class="media-left media-middle" >
<img class="media-object" width="150" height="150" src="/IMG/{{dish.picture}}" alt="">
</div>
<div class="media-body">
<h4 class="media-heading">
<button type='submit' class=" url" title=" Update food information ">
Name of dish: {{dish.itemName|default:"Null"}}
</button>
<span class="label label-default">
Price: {{dish.price|default:"Null"}}
</span>
</h4>
Introduction: {{dish.itemText|default:"Null"}}
</div>
</li>
</form>
{% empty %}
<!-- If there is no data in it, show the following contents -->
<p> Data is not available at present ..</p>
{% endfor %} {% endblock tableBody %}
6. Static path
Configure the following in all url: urlpatterns + static …
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.base_view, name = "base"),# Customer service system
path('order/<int:dishID>/', views.order_view),# Order details
path('order/<int:dishID>/submit/',views.order_submit),# Submit an order
path('pay/<int:orderID>/', views.pay_view),# Payment
path('pay/<int:orderID>/submit/',views.pay_submit),# Confirm the bill
path('order/list/',views.order_list_view),# Historical order list
path('order/confirm/<int:orderID>/',views.order_confirm),# Confirmation of receipt of order
path('order/comment/<int:orderID>/',views.comment),# Arrive at the comment interface of the corresponding dish
path('order/comment_post/<int:orderID>/',views.comment_post)# Submit comments
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
7. Modify uploaded images
First, upload pictures with form form. After checking that it is valid, assign picture data in cleaned_data to picture attribute in the object to be updated, and finally save can be used. The code is as follows:
def updateDish_post(request,dishID):
"""
Accept the request to modify the dish
"""
dish_form = MerchantDish(request.POST,request.FILES)
if dish_form.is_valid() :
dish = Menu.objects.get(ID = dishID)
dish.itemName = dish_form.cleaned_data['itemName']
dish.itemText = dish_form.cleaned_data['itemText']
dish.price = dish_form.cleaned_data['price']
dish.picture = dish_form.cleaned_data['picture']
dish.save()
# dishChange = dish_form.clean()
return redirect('/MerchantSystem/')
elif dish_form.errors is not None:
print(dish_form.errors)
return HttpResponse(str(dish_form.errors))
8. Set the default picture
I checked this step for a long time, but all of them are not good. It seems that I can't set default directly in model. py file. I finally gave up, but I still tried it out by luck. I don't know the principle, but I still put it here, hoping to help everyone.
The method is to write an default at src in the html template that displays the picture, with the following code:
dish is a parameter passed from the back end, and default points to the default image location.
<div class="media-left media-middle" >
<!-- {{dish.url|default:"Null"}} -->
<img class="media-object" width="150" height="150" src="/IMG/{{dish.picture|default:'img/default.jpg'}}" alt="">
</div>
References:
Use of ImageField
Default picture assignment (feeling method is not good)