SoFunction
Updated on 2024-11-14

ImageField in django the use of details

Notes on using ImageField

Today to perfect the homework written order system, mainly to add pictures to each dish, look beautiful, but I did not expect this small demand took me a day, recorded, counting the growth of knowledge.

Usage Process

1. Configure the setting file

MEDIA_ROOT stands for the root directory of the uploaded image, and MEDIA_URL stands for the prefix of the url when accessing the file.

# Image storage root path
MEDIA_ROOT = join('media')
# image access url
MEDIA_URL = '/IMG/'

Add ImageField property inside

The up_load must be configured to represent the folder MEDIA_ROOT/up_load (which is actually the name you gave it) where your final image will be stored.

class Menu():
  """
  Meal Database
  """
  ID = (primary_key=True,editable=False)
  lastEditTime = (auto_now_add=True)
  merchantID = (Usr, verbose_name="Merchant Account Number", on_delete=,to_field='ID')
  itemName = (max_length=20,verbose_name="Name of the meal.")
  itemText = (verbose_name="Meal Profile")
  price = (verbose_name="Price of the meal")
  ################# up_load represents the name of the folder where your uploaded images are stored
  picture = (verbose_name='Meal Pictures',null=True,upload_to='img/')
  class Meta:
    db_table = "Menu"
    verbose_name = "Meal Data Sheet"
    ordering=['-lastEditTime']

form class

This project uses django comes with the Form form class for passing data.

class MerchantDish():
  """
  Merchant dish submission form
  """
  itemName = (max_length=20,label="Name of the meal.")
  itemText = (max_length=300,label="Meal Profile")
  price = (label="Price of the meal")
  picture = (label='Meal Pictures')

Template file (adding dishes)

Note 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">modifications</button> 
  <button type="button"><a href="/MerchantSystem/DelDish/{{dishID}}/" rel="external nofollow" >removing</a></button>
</form>

5. html template file for displaying dishes

The important thing is the configuration of the path in the src, there are two ways to suggest method one, they feel safer, even if there is no picture will not report an error. (Note: you can adjust the picture display size)

Method 1: /IMG(your own defined MEDIA_URL)/{{}} ----dish stands for the dish that comes in from the back-end, and for that field in this class you're using that has the ImageField attribute;

Method 2: {{}} Because ImageField is a file class, there are three attributes name, path, and url in it that can be accessed directly.

{% for dish in menu %}
<!--Display the catalog's data in thehtmlcenter-->
<!-- Submit to a parameterizedurlPay attention to the back-end reception -->
<form action="/MerchantSystem/Dish/{{}}/" method="post">
  {% csrf_token %}
  <li class="media">
    <div class="media-left media-middle" >
        <img class="media-object" width="150" height="150" src="/IMG/{{}}" alt="">
    </div>
    <div class="media-body">
      <h4 class="media-heading">
        <button type='submit' class=" url" title="Updated dish information">
        dish name:{{|default:"Null"}}
        </button>
        <span class="label label-default">
          prices:{{|default:"Null"}}
        </span>

      </h4>
      synopsis:{{|default:"Null"}}
    </div>
  </li>
</form>

{% empty %}

<!--若center无数据展示如下内容-->

<p>No data available..</p>

{% endfor %} {% endblock tableBody %}

6. Path static

Configure the following in all urls: urlpatterns + static...

from  import settings
from  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),# Submission of orders
  path('pay/<int:orderID>/', views.pay_view),# Contributions
  path('pay/<int:orderID>/submit/',views.pay_submit),# Confirmation of bills
  path('order/list/',views.order_list_view),#History Order List
  path('order/confirm/<int:orderID>/',views.order_confirm),#Order acknowledgement of receipt
  path('order/comment/<int:orderID>/',),# Arrive at the review screen for the corresponding dish
  path('order/comment_post/<int:orderID>/',views.comment_post)#Submit a comment
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

7. Modify uploaded images

First upload the picture with the form, after checking the validity, assign the picture data in the cleaned_data to the picture attribute of the object to be updated, and finally save. The code is as follows:

def updateDish_post(request,dishID):
  """
  Accepting requests to modify dishes
  """
  dish_form = MerchantDish(,)
  if dish_form.is_valid() :
    dish = (ID = dishID)
     = dish_form.cleaned_data['itemName']
     = dish_form.cleaned_data['itemText']
     = dish_form.cleaned_data['price']
     = dish_form.cleaned_data['picture']
    ()
    # 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. Setting the default picture

This step I checked for a long time, but it does not work, it seems that you can not set default directly in the file, I finally gave up, but I still tried by luck, do not know the principle, but still put it here, I hope it will help you.
The method is to write a default at src in the html template that displays the image, with the following code:
The dish is a parameter passed from the backend, and default points to where the default image is located.

    <div class="media-left media-middle" >
        <!-- {{|default:"Null"}} -->
        <img class="media-object" width="150" height="150" src="/IMG/{{|default:'img/'}}" alt="">
    </div>

References:

Use of ImageField

Default image assignment (feels like the method doesn't work)

to this article on the use of django ImageField details of the article is introduced to this, more related django ImageField content please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!