Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
gather scheduler run task for using in method of run in task class
I Using CLass based celery task schduler and my task run every 30 days from model i want gather time of execution for clalcualtion in one field I create a base task as below: from datetime import timedelta from celery.task import PeriodicTask class WorflowScheduler(PeriodicTask): abstract = True run_every = None query_task_pk = 1 def run(self): pass I read data from model and create parameter of schedule insert class PMscheduler(models.Model): jobname = models.CharField(max_length=100,unique=True) Days = models.IntegerField(blank=True) Hours = models.IntegerField(blank=True,validators=[MinValueValidator(0), MaxValueValidator(23)]) Minutes = models.IntegerField(blank=True,validators=[MinValueValidator(0), MaxValueValidator(59)]) title = models.CharField(max_length=150) ) in task.py i create schduler paramter for insert from user : shedulelist = PMscheduler.objects.all() for i in shedulelist: class CreatePM(WorflowScheduler): run_every = timedelta(days=i.Days,hours=i.Hours,minutes=i.Minutes) def run(self, **kwargs): PMTicket.objects.create( title=i.title, tobeimplementtime=i.tobeimplementtime, return title I need tobeimplement before mention as task executed every 30 day + 1day, how can i do that -
Django change_list customization add fields and action button to send email
I am a beginner and haven't worked overriding the django admin templates before. I could be really very wrong in my approach here to sincere apologies. I wish to modify the django admin change view to include form fields for email message and email subject. Currently the submit button is not even appearing. How should I proceed? admin.py class EvaluationAdmin(admin.ModelAdmin): change_form_template = "admin/evalutations/change_form.html" form = EvaluationForm def has_change_permission(self, request, obj=None): if obj is not None: if request.user.is_superuser: return True elif obj.decision == "rejected" or obj.decision == "success": return False elif request.user == obj.first_eval and (obj.is_second_review == False): return True elif request.user == obj.second_eval: return True return False def has_delete_permission(self, request, obj=None): if obj is not None: if request.user.is_superuser: return True elif request.user == obj.first_eval and (obj.is_second_review == False): return True elif request.user == obj.second_eval: return True return False def response_change(self, request, obj, form_url=''): if "_send_email" in request.POST: form = EvaluationForm(request.POST) receiver_email = self.get_queryset(request).filter(id=obj.id).lead.user.email sender_email = "pratyushadhikary1152@gmail.com" if form.is_valid: message = form.cleaned_data["message"] subject = form.cleaned_data["subject"] send_mail( subject, message, sender_email, [receiver_email], fail_silently=False, ) return HttpResponseRedirect(".") return super().response_change(request, obj) forms.py class EvaluationForm(forms.ModelForm): email_subject = forms.CharField(max_length=200) email_text = forms.CharField(widget=forms.Textarea) class Meta: model = Evaluation fields = "__all__" and here is the overridden change_form.html {% … -
How to Create Multiple Selection in Django
I'm trying to create like a simple form with multiple choice for my school project. so how do I create a multiple form like this using django? [1]: https://i.stack.imgur.com/ebsBW.png [1] -
Django - How to create an arithmetic relationship between two fields of different models in Django?
I am creating a sales app which has two modules with different models and relationships. The two modules are: Products(to keep track of product inventory) - this has 5 models: Providers, Warehouses, Brands, Products and Entries Sales(will keep track of sales per customer and salesman as well as other relevant sales data) - this has three models: User, Customers, Sales, among others The Entries model in the Products module has a field called "units" which is basically a DecimalField that represents the amount of X product in stock, for example 100 pounds of beef. class Entries(models.Model): user= models.ForeignKey(User,on_delete=models.CASCADE, related_name="entradas", editable=False) brand= models.ForeignKey(Brands, on_delete=models.CASCADE, related_name="marcas") product= models.ForeignKey(Products, on_delete=models.CASCADE, related_name="entradas") warehouse= models.ForeignKey(Warehouses, on_delete=models.CASCADE, related_name="bodegas") method= models.CharField(max_length=256,default="PEPS") created_date = models.DateTimeField(auto_now=True) entry_date= models.DateField() document= models.CharField(max_length=256,default='N/A') lot= models.IntegerField() CAD = models.DateField() UxC = models.IntegerField() unit_type = models.ForeignKey(EntryType, on_delete=models.CASCADE) units= models.DecimalField(max_digits=100,decimal_places=2) In the Sales model I will have a field which represents how much of a product was sold to that customer, I will use a manytomany relationship as you could sell multiple entries of different products to a customer. My question is, how can I create a relationship where for each product sold that Entry field "units" would automatically reflect the substraction of the sale. … -
I'm using 3 chained dropdown in 1 form using Python Django with the help of ajax, But I can't load cities under selected state
Here's my url path('ajax/load-cities/', load_cities, name='ajax_load_cities'), This is the form This is form.py class AddSuburb_form(ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Suburb Name'})) class Meta: model = Suburb fields = ['country', 'state', 'city', 'name'] widgets = { 'country': forms.Select(attrs={'class': 'form-control'}), 'state': forms.Select(attrs={'class': 'form-control'}), 'city': forms.Select(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['state'].queryset = State.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['state'].queryset = State.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['state'].queryset = self.instance.country.state_set.order_by('name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'state' in self.data: try: state_id = int(self.data.get('state')) self.fields['city'].queryset = City.objects.filter(state_id=state_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty District queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.state.city_set.order_by('name') Heres the template In here, only states under the selected country must show and as same, cities under the selected state should showup. I can see, states are working fine but not cities. <div class="col-md-3"> <h3>Template</h3> <div class="drop-down"> <form method="POST" action="{% url 'add_suburb' %}" id="AddSuburbForm" data-cities-url="{% url 'ajax_load_cities' %}"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary"> Save</button> </form> </div> Ajax Second function seems to have some problem but … -
Avoid double call GET Ajax load
Well, I'm trying to create a graphical interface for a database using django. I have to say that I'm trying to learn so I don't have too much experience with Frameworks, just with pure code. The doubt I have is: -When trying to create a filter system with checkboxes I have used Ajax to be able to update the view without having to refresh. Like this: $(document).on('click','#console_check_filter',function(){ var ps_id; ps_id = $(this).attr("data-posts-id"); $.ajax({ url: "{% url 'list-view' %}", method: 'POST', data: { 'getfilter': ps_id, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function (res, status,data) { $("#list").load("/game/list-view"); }, error: function (res,ras,rus) { } }); }); But I had the error that for every call I made with POST the AJAX function ().load() made another call which eliminated the variable that gave me the POST. This made it impossible for me to use the information received from the POST to create the filter. Result: I click on the checkbox and in the console I get a call with the filtered list and then another one without filter, and as it is not only the last one that is rendered, which has no data. To solve this I have used a globar variable to … -
Celery - worker only sometimes picks up tasks
I am building a lead generation portal that can be accessed online. Please don't mind the verbosity of the code, I'm doing a lot of debugging right now. My Celery worker inconsistently picks up tasks assigned to it, and I'm not sure why. The weird thing about this, is that sometimes it works 100% perfect: there never are any explicit errors in the terminal. I am currently in DEBUG = TRUE and REDIS as a broker! views.py class LeadInputView(FormView): template_name = 'lead_main.html' form_class = LeadInput def form_valid(self, form): print("I'm at views") form.submit() print(form.submit) return HttpResponseRedirect('./success/') tasks.py @task(name="submit") def start_task(city, category, email): print("I'm at tasks!") print(city, category, email) """sends an email when feedback form is filled successfully""" logger.info("Submitted") return start(city, category, email) forms.py class LeadInput(forms.Form): city = forms.CharField(max_length=50) category = forms.CharField(max_length=50) email = forms.EmailField() def submit(self): print("I'm at forms!") x = (start_task.delay(self.cleaned_data['city'], self.cleaned_data['category'], self.cleaned_data['email'])) return x celery.py @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' The runserver terminal will look something like this: I'm at views I'm at forms! <bound method LeadInput.submit of <LeadInput bound=True, valid=True, fields=(city;category;email)>> But the worker doesn't say that it picked … -
Can someone explain this error that i get when i try to deploy my django project
Here's the error in the apache log: Exception ignored in: <function Local.__del__ at 0x7fb9a1720310> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fb9a1720310> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fb9a1720310> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fb9a572a310> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fb9a572a310> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fb9a572a310> Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined I'm using a bitnami server on AWS lightsail. All my static webpages load perfectly, but whenever I try to do a from submission there's a 500 server error. I don't know how to fix that. I dont use typerror anywhere in my views.py btw -
Apple Review of iOS Cordova App - No User Agent received
This has happened 3 times over the last ~1.5 years. (Out of about 10 reviews.) On these 3 random occasions Apple reviewers have somehow sent requests which have: Lost their session AND somehow have absolutely NO User Agent at all (this is the one that really confuses us) (This results in our app being rejected because they have receive unintended behavior because they have no session or useragent.) INFO: We have a Cordova app and point it to our website running on a Django server. <!--- config.xml ---> <preference name="AppendUserAgent" value="APP_NAME_cordova" /> This has happened for us: cordova-ios@5.0.1 2/8 times cordova-ios@5.1.1 0/1 times (Lucky?) cordova-ios@6.1.1 1/1 times Never when we are testing ourselves No reports from our ~8,000 iOS users that match this behavior Never on Android (reviews/users/us) How could this be happening? Could this be django dropping the user agent? (and session? :S) Could Cordova be failing to send the userAgent? Is Apple doing something special/weird? Any suggestions? (Right now we are just assuming requests that match the above 2 criteria to be Apple, and forcing the behavior. Not Ideal.) -
Django form-tools ImageField Upload Issue
Want to create multistep registration form using django-formtools Form: class FormStepOne(forms.Form): photo = forms.ImageField() name = forms.CharField(max_length=100) phone = forms.CharField(max_length=100) email = forms.EmailField() class FormStepTwo(forms.Form): job = forms.CharField(max_length=100) salary = forms.CharField(max_length=100) job_description = forms.CharField(widget=forms.Textarea) View: class FormWizardView(SessionWizardView): file_storage = DefaultStorage() template_name = "registration.html" form_list = [forms.FormStepOne, forms.FormStepTwo] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) Image field is not working. Though I give image but it shows field is required. -
SMTPRecipientsRefused at /accounts/signup/ (550)
I have run into a problem with email verification during signup. The problem is: if I register with an existing email, everything works as it should, however, if I try to register with a nonexistent email, I will get an error and the website crashes with the status code 500. I use Django allauth and mail.ru for sending the verification emails. Here is my email configuration in settings.py: EMAIL_HOST = 'smtp.mail.ru' EMAIL_USE_TLS = True EMAIL_PORT = 2525 EMAIL_HOST_USER = os.environ.get('email_address') EMAIL_HOST_PASSWORD = os.environ.get('email_password') DEFAULT_FROM_EMAIL = os.environ.get('email_address') The error message: Exception Type: SMTPRecipientsRefused at /accounts/signup/ Exception Value: {'asd@asd.asd': (550, b'non-local recipient verification failed')} How do I catch that error and avoid 500? Python version: 3.8.6 Django version: 3.1.1 -
Ignore form.is_valid() with multiple submit buttons
Following this thread on how to implement multiple submit buttons for the same form here, I implement a form with two buttons, Confirm and Cancel as following: <form id="item-form" class="item-form-container" method="post"> {{ item_form.as_p }} {% csrf_token %} <button type="submit" class="button-item-order" name="confirm-order">Confirm</button> <button type="submit" class="button-item-order-cancel" name="cancel-order">Cancel</button> </form> In my view, if the button confirm-order is clicked, the view proceeds with validating the form, and process its data. However, if button cancel-order is clicked, I would like for the view to ignore the form validation, since I am not processing any of its data. def item_order_view(request): if request.method == 'POST': item_form = ItemOrderForm(request.POST) if 'confirm-order' in request.POST: if item_form.is_valid(): ... return redirect(reverse(...xxx...)) else: return redirect(reverse(...yyy...)) else: ... return render(request, ...) While the appropriate action is executed based on which button is clicked, the view always validates the form. It means, if I click the cancel-order button without filling the form appropriately, I get the usual validation error. This action return redirect(reverse(...yyy...)) won't execute unless the form is filled properly. How do I bypass / ignore the validation when cancel-order is clicked? -
Best way to speed up Django post requests?
I'm running a local Django server on a virtual machine that is remote interpreted onto a Raspberry Pi. The purpose of the remote connection is to have the Raspberry Pi upload a bunch of data from various sensors to the local server every minute. I'm running into an issue now where the Post request speed is far too slow for the amount of data that will be coming in (Post speed is about one, sometimes two posts a second). I'm assuming this is due to the remote connection and the fact that it is running on a virtual machine as the post speed is exceptional if I run the local server on my physical laptop and post data from a local csv file, not remote interpreted. I'm currently experimenting with the django bulk-create method to post data in bulk instead of hitting the database with every post, but I'm not sure if this will actually speed up the post requests. I'm worried it might just bottleneck the local server. Does anybody know of a good way to speed up these requests? I'm using SQLite3, would switching to POSTGRE or a different database help? -
Automating Django database changes
I'm new to Django, and relatively new to programming in Python. The first project I'm planning to make in Django is going to be a dashboard for monitoring network hosts (access points, switches, routers). I already have classes in Python that can pull the data that I need from the API of the various hosts that I'm intending to monitor. Right now I'm using this data to generate email reports of hosts that are offline. The way I envision this working in Django is building classes in models.py for the various components (our paying clients, routers, access point controllers, access points, switches, etc). These classes will build the database tables and their relationships. From there I planned on running cron jobs with scripts that would manually update these databases with psycopg2. I'd be doing things like adding new entries, deleting old entries, and updating existing ones. This would happen completely separate from the tools that Django provides for database management. Now to the questions: Is there anything outlined above that would not work the way I envision it working? Is there a better way to accomplish what I'm trying to accomplish? I want to have a lot of control regarding … -
Django Heroku, This site can’t be reached, Took too long to respond
I created a Django website around 1 month ago, it was working perfectly fine, but on 8-11-2020 it stopped working (It won't load). I tried things that I could find on the internet but nothing worked as there isn't much about my problem. I tried restarting all dynos and redeploying my website but it didn't work. Can someone tell me how to fix this? -
django models save two auto calculated field
I have this logic in my models, i just want that the result will automatic save in the database class Product(models.Model): unitquantity = models.FloatField(null=True, blank=True) price = models.FloatField(null=True, blank=True, verbose_name="Unit Price") discount_percentage = models.FloatField(max_length=500, null=True, blank=True) discount_price = models.FloatField(null=True, blank=True) Other_discount_percentage = models.FloatField(null=True, blank=True) Other_discount_price = models.FloatField(null=True, blank=True, default=0.0) discount_price_formula = models.FloatField(null=True, blank=True) other_discount_price_formula = models.FloatField(null=True, blank=True) def save(self, *args, **kwargs): self.discount_price_formula = self.price - (self.price * self.discount_percentage) self.other_discount_price_formula = self.discount_price_formula * self.Other_discount_percentage return super(Product, self).save(*args, **kwargs) -
How to access django request using graphene mutation info
I get this error 'WSGIRequest' object has no attribute 'request' PS: snippet is a truncated. Error is coming from info.context.request class Arguments: input = ForgotPasswordInput() ok = graphene.Boolean() message = graphene.String() @staticmethod def mutate(root, info, input=None): try: user = User.objects.get(email=input.get('email')) current_site = get_current_site(info.context.request)``` -
Double forward slash in Django URL causes 404 error
Can someone please advise why I keep getting a forward double slash in my Django URL? Please see the error message below. Please note the forward double slash after polls that causes the page to throw errors Page not found (404) Request Method: GET Request URL: http://157.230.7.149:8000/polls/owner/owner Using the URLconf defined in tutorial2.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ owner [name='owner'] polls/ <int:pk>/ [name='detail'] polls/ <int:pk>/results/ [name='results'] polls/ <int:question_id>/vote/ [name='vote'] admin/ The current path, polls/owner/owner, didn't match any of these. Please see the urlpattern in the urls.py file as well as the function in the views.py file urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('owner', views.owner, name='owner'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] views.py def owner(request): return HttpResponse("Hello, world. 80e4c546 is the polls owner.") Would greatly appreciate any assistance. Thank you -
Flask cannot redirect after receiving post request from Ajax in templates
I want to create a chatroom, in which, if people enter "!exit", then they will get out of the chatroom. The way I implement this idea is that whenever people send "!exit" message, Ajax will send a post request back to the view function. After receiving the request, the view function redirects the user to the homepage. However, right now, I think I can send a post request, since the console prints "success", but the code still does not redirect. This is my code: In chat.html: <head> <title> Chat room </title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function() { var socket = io.connect('http://127.0.0.1:5000'); socket.on('message', function(msg) { if (msg=="!exit") { $.ajax({ type : "POST", url : "http://127.0.0.1:5000/chat", data: {data: "Unmatched"}, contentType: 'application/json;charset=UTF-8', success: function() { window.location.href = '/chat' } }); } else { $("#message-display").append('<div>'+ "person: " + msg+'</div>'); } }); $('#sendbutt').on('click', function() { socket.send($('#message-input').val()); $('#message-input').val(''); }); }); </script> <div> Welcome to the chat room. You are chatting with a user. </div> <div> Type "!exit" if you want to stop chatting and return to the homepage. </div> <l id="message-display"> </l> <input type="text" id="message-input"> <button id="sendbutt"> Send </button> </body> </html> In main.py: socketio=SocketIO(app) @app.route('/', methods = ["GET", "POST"]) def homepage(): … -
Django template language query database
I have a list of cities,In the city list, I also need to query the hotels in each city,this's my code,use ‘city.hote_set.all’,But the list is all hotels,How to use filter query? For example:city.hotel_set.filter This's my code {% for city in city_list %} <a>{{ city.name }}</a> {% for hotel in city.hote_set.all %} <a>{{hote.name}}</a> {% endfor %} {% endfor %} -
Connect to a Django postgres database remotely
I am using Postgres for a production system, and I would like to be able to connect to this database remotely to integrate the information with other systems. My configuration looks classic like follows : ALLOWED_HOSTS = ['myipgoeshere', 'mydomainnamegoeshere'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': 'localhost' } } Now, if I want to connect to this database from another machine what should I use as hostname on that machine ? I need to provide information about Host Database Port User Password In my config, host is localhost, but I cannot use this as remote hostname, should we use the IP address instead ? Also will the port be the default postgres one ? Any hint would be much appreciated -
Adding Parameters to Existing Django Model Fields
I was trying to create a custom Django model field, where the new field will essentially be the same as a CharField but has an additional boolean attribute -- for now, just call it "public." I have looked up this article on adding custom attributes, but I don't like the method described as it required me to construct a brand-new model from scratch. It is a hassle considering the number of functions I must implement just to add a parameter, which is all listed in the docs. To clarify my objectives, I will like to declare this field as such: somefield = BoolCharField(public=True, max_length=100, blank=True) # Note that public is NOT a default CharField attribute The documentation stated that I am allowed to extend new fields from existing fields, but the section isn't elaborated. Can anyone please provide me with an example of how I should implement my field? Thank you very much. -
how to import django admin inlines to CreateView?
this is my CreateView class PizzaCreateView(PermissionRequiredMixin,SuccessMessageMixin,CreateView,): model = Pizza fields = ['name','price','pizza_description','toppings','Admin.PizzaImageInline'] action = 'Add pizza' success_url = reverse_lazy('pages:home') permission_required = 'pizzas.add_pizza' success_message = '"%(name)s" was created successfully' this is my admin.py class PizzaImageInline(admin.TabularInline): model = PizzaImage extra = 3 class PizzaAdmin(admin.ModelAdmin): inlines = [ PizzaImageInline, ] admin.site.register(Pizza, PizzaAdmin) how do i can transfer PizzaAdmin to my view form -
Creating a Pizzeria program in python and postgresql
I am new to python and would like to create a Pizzeria Program using python and PostgreSQL that looks something like this. Output: Welcome to Jeff's Pizzeria Here's our Pizza menu: Pizza Types(cost per sale): A) Pizza A (has Topping A, B, and C): $ 30.50 B) Pizza B (has Topping A only): $ 24.50 C) Pizza C (has Topping B and C only): $ 28.50 Toppings Type(cost per pizza): Topping A: $ 5.99 Topping B: $ 11.99 Topping C: $ 8.99 Please input a letter and number and press enter to select a pizza item. Input 'add' to finish your order. Input 'another' to add another pizza order. Input 'report' to view all of the pizza orders made today. A You selected Pizza A. That would cost $30.50. 1 You selected Topping B! That would cost $11.59. Add Your pizza order is added and your total bill is $42.09. Do you want to order pizza again? Y/N N Thank you for buying Jeff's Pizzeria Press 'another' to order pizza again or type 'report' to view all of the pizza orders made today report Pizzas sold today: 5 Pizzas per type sold: 5 Total of money spent: $204.85 Money earned … -
Django - Static file, image, wont appear
I'm learning django. It was working in the beginning of my project, but now imgs from static just dont appear. I've try to run collecstatic and work with STATIC_ROOT. Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') Home.html {% load static %} <img scr="{% static 'img/cart-icon.png' %}"> Files dir