Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render a list of foreign key in template
Models class Head_of_department(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=30) def __str__(self): return self.first_name + ' -- ' + str(self.school) class Employee(models.Model): first_name = models.CharField(max_length=200, unique=True) last_name = models.CharField(max_length=200, unique=True) head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) email = models.EmailField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Attendance(models.Model): head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) employee = models.ForeignKey('Employee', on_delete=models.CASCADE, ) attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True) Views class Attendancecreate(CreateView): model = Attendance fields = ['employee'] success_url = '/dashboard/' def get_context_data(self,** kwargs): context = super(Attendancecreate, self).get_context_data(**kwargs) email = self.request.user.email hod = Head_of_department.objects.get(email=email) context["objects"] = self.model.objects.filter(employee__head_of_department =hod) print (context["objects"]) return context def form_valid(self, form): self.object = form.save(commit=False) self.object.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email) self.object.save() return super().form_valid(form) Template <div class="form-group"> {% for item in objects %} {{ item.student }} {% endfor %} </div> The webapp has a login feature. The headofdepartment can mark the attendance . I want to render a list of employees under the respective logged in HOD and mark attendance . I want to do this in the same view -
Django Datetime not getting saved
I am trying to create an object of the following model and save it through using code as below. chk_list_for_batch = ChkListForBatch(batch, chk_point, False, datetime.datetime.now()) chk_list_for_batch.save() But, I get the following error django.core.exceptions.ValidationError: ["'2019-05-25 11:20:23.240094' value must be either True or False."] I searched but couldn't find any direction. Kindly suggest. -
How to add an index to my slug when this slug already exists in database?
When i create new post i need to do next: 1. Generate slug from self.title with slugify and self.id 2. Check if this slug does not exists we save post with self.slug 3. If this slug already exists we save post with self.slug + '-' + self.id I found solution here but it doesn't work for me, it creates post with empty slug and crashes on trying to list it. #models.py from django.db import models from django.shortcuts import reverse from django.utils.text import slugify class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, blank=True, unique=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug': self.slug}) def save(self): super(Post, self).save() if not self.slug: slug = slugify(self.title) try: post_obj = Post.objects.get(slug=slug) slug += "-" + str(self.id) except Post.DoesNotExist: pass self.slug = slug self.save() -
Oscar offer app override Benefits functions conflicts error
I use Oscar 1.6.4 version. I want to override PercentageDiscountBenefit in oscar.app.offer.benefits.py. But conflict error happens. How can I override this functions? from oscar.core.loading import get_classes CorePercentageDiscountBenefit, CoreAbsoluteDiscountBenefit = get_classes('offer.benefits', ['PercentageDiscountBenefit', 'AbsoluteDiscountBenefit']) class PercentageDiscountBenefit(CorePercentageDiscountBenefit): def apply(self, basket, condition, offer, discount_amount=None, max_total_discount=None): print( "\n\n\n\n", "PRINT SOMETHING", "\n\n\n\n", ) return super().apply(basket, condition, offer, discount_amount, max_total_discount) class AbsoluteDiscountBenefit(CoreAbsoluteDiscountBenefit): def apply(self, basket, condition, offer, discount_amount=None, max_total_discount=None): print( "\n\n\n\n", "PRINT SOMETHING", "\n\n\n\n", ) return super().apply(basket, condition, offer, discount_amount, max_total_discount) Error screenshot -
Django - passing a dict to form constructor and having it available globally in the class
I'm making a big mess trying to access the object that I passed from the view to the form. class PrenotaForm(forms.ModelForm): ORARI_CHOICES = () def __init__(self, *args, **kwargs): DICT_ORARI_CHOICES = kwargs.pop('ORARI_CHOICES_NEW', {}) ORARI_CHOICES_NEW = [] for key, value in DICT_ORARI_CHOICES.items(): temp = [key,value] ORARI_CHOICES_NEW.append(temp) super(PrenotaForm, self).__init__(*args, **kwargs) self.ORARI_CHOICES = ORARI_CHOICES_NEW print("EEEEEEEEEEEEEEE" + str(self.ORARI_CHOICES)) print(ORARI_CHOICES) I don't understand why inside the init the ORARI_CHOICES is populated as shown in console output: EEEEEEEEEEEEEEE[['è uguale', 'Indifferente'], ['845', '08:45'], ['900', '09:00'], ['915', {'label': '09:15', 'disabled': 'disabled'}], ['930', {'label': '09:30', 'disabled': 'disabled'}], ['945', '09:45'], ['1000', '10:00'], ['1015', '10:15'], ['1030', '10:30'], ['1045', '10:45'], ['1100', '11:00'], ['1115', '11:15'], ['1130', '11:30'], ['1145', '11:45']] but outside the init the ORARI_CHOICE is still empty: print(ORARI_CHOICES) since the print does not output nothing. How can I override the ORARI_CHOICES = () and make it avalable globally in the class after every GET request performed in the view? if request.method == 'GET': size_gruppi = 30 print("gruppi size is : " + str(size_gruppi)) ORARI_CHOICES = ( ('è uguale', "Indifferente"), ('845', "08:45"), ('900', "09:00"), ('915', "09:15"), ('930', "09:30"), ('945', "09:45"), ('1000', "10:00"), ('1015', "10:15"), ('1030', "10:30"), ('1045', "10:45"), ('1100', "11:00"), ('1115', "11:15"), ('1130', "11:30"), ('1145', "11:45"), ) orari_map = map(list,ORARI_CHOICES) orari_dict = dict(ORARI_CHOICES) print(orari_dict) … -
How to insert default value in database table when user account is crrated in Django?
I am using postgre database have 10 channel in my database. This is my models with channelId and userId as foreign key: class Count(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE) rate = models.PositiveIntegerField(default=0) def __str__(self): return self.channelId.name class Meta: ordering = ["-id"] I want when a user account is created then 3 row inserted in the table for all 3 channelId and rate value set to 0. suppsose a user sign up and get userIid 99 then 3 rows inserted in the table as userId channelId rate 99 1 0 99 2 0 99 3 0 What could be the possible solution. -
Set field form value from view
How to add field value manually from view? model.py class Connect(models.Model): username = models.CharField(max_length=255) password = models.CharField(max_length=255,null=True, blank=True) conft = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return unicode(self.username) form.py class NacmForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput,required = False) conft = forms.Textarea() class Meta: model = Connect fields = ['username', 'password','conft'] labels = {'conft':_('Config'),} view.py class config_static(View): def post(self, request, *args, **kwargs): formm = NacmForm(request.POST or None) ipform = IpFormset(request.POST) userValue = formm['username'].value() passValue = formm['password'].value() if ipform.is_valid() and formm.is_valid(): simpanForm = formm.save() for form in ipform: ipaddr = form.cleaned_data.get('ipaddr') vendor = form.cleaned_data.get('vendor') ....... //some code// ....... simpanIp = form.save(commit=False) simpanIp.connect_id = simpanForm simpanIp.save() simpanForm.save() ......... //some code// i want to set "conft" value manually, maybe like configuration = "some config" conft = configuration i already tried configuration = "some config" NacmForm(initial={'conft': configuration }) or formm.fields['conft'].initial = configuration or formm = NacmForm(request.POST, initial={"conft": configuration }) when i use that code above, the value isnt save to database, then i tried this Connect.objects.create(conft=configuration) its save to database but not in same row -
How to search post in django
i'm new to django and i'm trying to create a search form in my index.html to search from my post and show the results in my search.html file in django but i keep getting this search error. http://dpaste.com/03KAGY1. please can you help me and show me a code snippet of how to fix this problem my django version is 1.11.6 This is my views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Article def search(request): template = 'articles/search.html' query = request.GET.get('q') results = Article.objects.filter(Q(title__icontains=query) | Q(movie_name__icontains=query)) context = {'results': results} return render(request, template, context) and this is my urls.py url(r'^results/$', views.search, name="search"), and this is my form <form action="{% url 'search' %}" method="GET"> <input name="q" value="{{request.GET.q}}" type="text" placeholder="Search..."> <button type="submit" class="btn-success btn">submit</button> </form> -
Comparison of the string with the data in the database
I would like to compare a sentence which I input to my code with any value in database. There is my function which apply data into database from my page: def create_author(request): form_author = AuthorForm() context = {'form_author': form_author} if request.method == 'POST': form_author = AuthorForm(request.POST) if form_author.is_valid(): name = request.POST.get('name',) surname = request.POST.get('surname') if name == Author.name and surname == Author.surname: print("We have this author in database") # There should be stop. else: author_object = Author(name=name, surname=surname) author_object.save() return render(request, 'authors/create_author.html', context) and it works but it only adds - doesn't check if any author exist in db. Any ideas for fixing it? Thanks in advice. -
Redirect doesn`t working with ajax form in django
I have a form, which works with ajax. When I do redirect or something else (Httpresponse, HttpResponseRedirect ...) it doesnt work, but form is saved to db and I dont receive errors. Problem only with return redirect('index'). How can I fix this? my views.py def add_new(request): """ Function which upload new file to UploadModel. """ form_upload = UploadForm(request.POST, request.FILES, prefix='upload_form') if form_upload.is_valid() and request.is_ajax(): new_file = form_upload.save(commit=False) if request.user.is_authenticated: new_file.author = request.user new_file.created_date = date.today() new_file.is_worked = True if new_file.ended_date <= date.today(): new_file.is_worked = False new_file.delete() else: new_file.is_worked = True new_file.save() return redirect('index') form_upload = UploadForm() return render(request, 'sharing/index.html', {'form_upload': form_upload}) html file <form method="POST" enctype="multipart/form-data" id="file-upload-form" data-url="/"> {% csrf_token %} <div class="form-group"> <label>Title</label> {{ form_upload.title }} </div> <div class="form-group"> <label>Ended date</label> {{ form_upload.ended_date }} </div> <script> $('#datepicker').datepicker({ format:'yyyy-mm-dd' }); </script> <br> <div class="form-group"> {{ form_upload.file}} </div> <input type="submit" value="Save" class="btn btn-primary"> </form> and js file function upload(event) { event.preventDefault(); var data = new FormData($('form').get(0)); $.ajax({ url: $(this).attr('data-url'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: handleSuccess(), }); return false; } function handleSuccess(){ $("form")[0].reset(); alert('Success uploading!'); } $(function() { $('form').submit(upload); }); -
how to fix 404 in django, problem with urls
Working on simple api. All seemed fine, but after pressing the button, script is suppose to send the data to model. By now it shos me the error 404 and previously append_slash but I set it to false and still not working. I'm fresh in this framework. Appreciate for advice. views.py def index(request): url = 'http://www.omdbapi.com/?t={}&apikey=My key is here' if request.method == 'POST': form = MovieForm(data=request.POST) form.save() else: form = MovieForm() movies = Movie.objects.all() #// fetch all objects movies_data = [] #//// array for movies and their details for movie in movies: r = requests.get(url.format(movie)).json() #// gets details from api movies_main = { 'title': movie.title, 'director': r['Director'], 'rate': r['imdbRating'], } movies_data.append(movies_main) context = { 'form': form, 'movies_data': movies_data, } return render(request, 'movies/movies.html', context) main urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('movies.urls')) ] app urls urlpatterns = [ path('', views.index), ] -
how to send a model id while using javascript in django
I'm trying to delete a model instance when clicked on a button but before that i want to show a confirm box using JS, if the confirm box results true then i want to head over to the view to delete the instance also passing the instance id. Here Django is showing an Error NoReverseMatch at /profile/myprojects Reverse for 'project_delete' with arguments '('',)' not found. This is my button <button onclick="delFunction()" class="btn btn-danger btn-sm">Delete Project</button> This is the JS code function delFunction() { var txt; if (confirm("Are you sure you want to delete the project?")) { window.location.href = "{% url 'project_delete' project.id %}"; } } -
I can't multiply two fields. Error: invalid literal for int() with base 10:
I try to multiply price and quantity. but somethings went wrong. 'quantity' and 'price' both is IntegerField() class BillListSum(generics.GenericAPIView): def get(self, request): bill = Bill.objects.all() serializer = BillSerializer(bill) all_sum = Bill.objects.all().aggregate(Sum(int('cart__drink__price')*'cart__quantity' ))['cart__drink__price__sum'] return Response({'sum': all_sum if all_sum else 0 , 'objects': serializer.data}) Error: invalid literal for int() with base 10: 'cart__drink__price' Please help me! Thank you so much. -
Please recommend me the logic / tutorial / sample code to implement comment system in Django v 2 or higher
I am new to Django, I am building a standard blog application in Django version 2.2.1 where users can register, login,CRUD in post. is there any inbuild library with Django to implement this ? I searched web for answer but most tutorials supports older version of Django. Thank you. I have seen some libraries like django-comments but I think new version does not support it. -
Get ForeignKey object fields in the template
I have a select list which shows ForeignKey in the template Django. When user select a object in the field related values should appear. For example I have a contact list here and for this I am using generic views class SendContactView(CreateView): model = SendContact template_name = 'contact.html' fields = ['customer'] def get_context_data(self, **kwargs): context = super(Sales, self).get_context_data(**kwargs) context['form'].fields['customer'].queryset = Contact.objects.filter(author=self.request.user) return context in the template everything fine <label class="mt-1">Items*</label> <select class="browser-default custom-select" ng-value={{ form.customer }} and this shows ForeignKey as customer Contact. The problem is if I select any of them (in the select list customers name is visible only) how can I get their email, phone number and other stuff in the other form field? any help world be appreciated! Thank you! -
Django - Easiest way to set initial value for form fields to the current database value, for custom UserChangeForm?
Essentially I have a custom UserChangeForm that uses my user model 'Writer' and I want to set the default for all the fields as the current value from the database(or the value from the request user). What would be the best way to go about this? I tried to set the defaults in the form however the request object isn't accessable in forms.py the form... class writerChangeForm(UserChangeForm): class Meta: model = Writer fields = ('username', 'email', 'first_name', 'last_name', 'country') country = CountryField().formfield() widgets = {'country': CountrySelectWidget()} The view... class ProfileView(generic.CreateView): form_class = writerChangeForm template_name = 'diary/profile.html' Thanks for any input! -
whenever i click submit button i get unboundLocalError and local variable 'c' referenced before assignment
i have created a form for product table. I included values from multiple table in dropdown box. whenever i finish filling form and clicking submit, it throws me a error of UnboundLocalError. and it also says local variable 'c' referenced before assignment.i didn't understand what mistake i did and I'm new to django environment. model.py class Products(models.Model): pname=models.CharField(max_length=120) pcode=models.CharField(max_length=120) category=models.CharField(max_length=120) brand=models.CharField(max_length=120) supplier=models.CharField(max_length=120) description=models.CharField(max_length=120) class Meta: db_table="products" forms.py: class ProductForm(forms.ModelForm): pname=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) pcode=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) category=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) brand=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) supplier=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) description=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model=Products fields="__all__" views.py: def addproduct(request): if request.method == "POST": form = ProductForm(request.POST) if form.is_valid(): try: form.save() return redirect(show_products) except Exception as e: raise e else: form = ProductForm() c=Category.objects.all() b=Brand.objects.all() return render(request,'addproduct.html',{'form':form,'c':c,'b':b}) addproduct.html: <form method="POST" action="addproduct"> {% csrf_token %} <div class="form-group"> <label>Product Code:</label> {{form.pcode}} </div> <div class="form-group"> <label>Category:</label> <select class="form-control" name='category' required='' id='id_category' > {% for cat in c %} <option value='{{cat.id}}'> {{cat.cname}}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Brand:</label> <select class="form-control" name='brand' required='' id='id_brand' > {% for bra in b %} <option value='{{bra.id}}'> {{bra.bname}}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Supplier:</label> {{form.supplier}} </div> <div class="form-group"> <label>Product Name:</label> {{form.supplier}} </div> <center> <button class="btn btn-outline-success" type="submit">Submit</button></center> </form> -
Aggregate hourly count based on "HOUR" in datetime field in Django
I am using Django 2.2 along with MySQL. I have the following query: store_count_events = TrackCount.objects.filter( recorded_at__date=start_date.date(), recorded_at__hour__range=(8, 23), store__store_owner__id=self.kwargs['account_id']).order_by( 'recorded_at' ).extra( select={ 'hour': 'hour(recorded_at)' } ).values( 'hour' ).annotate( TotalPeople=Sum('people_count_in') ) But when I check my records I get the output as following : [ { "hour": 17, "TotalPeople": 22 }, { "hour": 17, "TotalPeople": 19 }, { "hour": 17, "TotalPeople": 30 }, { "hour": 18, "TotalPeople": 33 }, { "hour": 18, "TotalPeople": 31 }, { "hour": 18, "TotalPeople": 32 }, { "hour": 19, "TotalPeople": 32 }, { "hour": 19, "TotalPeople": 21 }] But I would like the output something like this : [{ "hour": 18, "TotalPeople": 96}....] that is the record for same hour should be SUM-ed up together. Hope my point is clear. TIA -
Wagtail Blog example results in no attribute '_default_manager'
I'm working through the wagtail tutorial. Using Python 3.6.7, Wagtail 2.5.1, Django 2.2.1. Everything works until I get to adding the categories near the end of the page ... class ArticlePage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=ArticlePageTag, blank=True) categories = ParentalManyToManyField('article.ArticleCategory', blank=True) # ... (Keep the main_image method and search_fields definition) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Article information"), FieldPanel('intro'), FieldPanel('body'), InlinePanel('gallery_images', label="Gallery images"), ] The FieldPanel "categories" produces an error. Here is the Traceback when running makemigrations : (env) simon@ckweb$ ./manage.py makemigrations │Watching for file changes with StatReloader Traceback (most recent call last): │Exception in thread django-main-thread: File "./manage.py", line 10, in │Traceback (most recent call last): execute_from_command_line(sys.argv) │ File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line │ self.run() utility.execute() │ File "/usr/lib/python3.6/threading.py", line 864, in run File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute │ self._target(*self._args, **self._kwargs) self.fetch_command(subcommand).run_from_argv(self.argv) │ File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv │ fn(*args, **kwargs) self.execute(*args, **cmd_options) │ File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute │ autoreload.raise_last_exception() self.check() │ File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in … -
Why do I need web api to link between django and other js framworks
It's my first question in this forum :D so my question is why do i need a web api to link between django and other js frameworks for example django with angular? And is it necessary to build a web api like (rest api) to link between back end and front end? Thanks a lot. What I have tried: It's my first question in this forum :D so my question is why do i need a web api to link between django and other js frameworks for example django with angular? And is it necessary to build a web api like (rest api) to link between back end and front end? Thanks a lot. -
django-rest: TypeError: unhashable type: 'list'
I am trying to restify my backend using django-rest-gis, in such a way that POST request adds data to database and GET request lists down the data. However, I am getting following error:- TypeError: unhashable type: 'list' [25/May/2019 04:48:29] "GET /api/ HTTP/1.1" 500 147185 I have followed many answers on stackoverflow but could only get that it comes when you have a mutable type as key in dictionary models.py from django.contrib.gis.db import models # Create your models here. class test1(models.Model): date = models.DateTimeField(auto_now_add=True, null=True, blank=True) location = models.PointField(blank=False) plg = models.PolygonField(srid=4326, geography=True, null=True, blank=True) city = models.CharField(max_length=50, blank=False) state = models.CharField(max_length=50, blank=False) def __str__(self): return "%s" % (self.state) serializers.py from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import test1 class test1Serializer(GeoFeatureModelSerializer): class Meta: model = test1 geo_field = ['location','plg'] auto_bbox = True id_field = False fields = ('city','state') views.py from .models import test1 from .serializers import test1Serializer from rest_framework.generics import ListCreateAPIView class test1SerializerCreate(ListCreateAPIView): serializer_class = test1Serializer queryset = test1.objects.all() -
How to get the last 3 created objects from the database?
I want to display the last 3 created objects onto my website. I have no clue what to do. I just need to know how to order the model according to created date. And, access the 1st, 2nd and 3rd item of the ordered set. I'm pretty sure this doesn't work. This is from views.py latest = Upcoming_Events.objects.all().order_by('date')[:3] event1 = latest.get(pk=1) event2 = latest.get(pk=2) event3 = latest.get(pk=3) I keep getting 'Cannot filter a query once a slice has been taken' -
How to create multi-page forms in django 2.2.1
I am using Django 2.2.1 and I want multi-page form where any one can navigate back and forth step by step. Submit Button is at last page of forms. -
Reaching a form via POST without submitting
I have a multi-part user login. User fills out Form A, is then directed on submit via POST to Form B. I've sent up some form validation so the outlines of the input boxes turn red when the form is invalid. However, since Form A on submit goes to Form B, Form B is getting automatically submitted since it is being reached via POST. So I'd like to reach Form B on submit of Form A without submitting Form B. On submit of Form A, user is redirected via return formB(request) to Form B def formB(request): form = MyForm() if request.method == "POST": if form.is_valid(): data = form.save(commit=False) data.save() return redirect('/') return render(request, "formb.html", {'form': form}) How can I set this up so it just loads Form B normally without validating? Is there another way I should be reaching Form B? -
Django Static Files 404 even when findstatic found the files
I'm setting up a web using django, and whenever i moved to another machine I always get 404 error on my static files. I tried using findstatic command and it says it found my static files, but it still won't load on my site python manage.py findstatic css/base.css Found 'css/base.css' here: /home/aoki/Project/Menulis/code/static/css/base.css I've also tried using collect static and STATIC_ROOT setting, it just won't work Here is my settings.py SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static/'), ) STATIC_URL = 'static/' LOGIN_REDIRECT_URL= '/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') MEDIA_URL = '/media/' here is the log [25/May/2019 03:17:51] "GET / HTTP/1.1" 200 6373 [25/May/2019 03:17:51] "GET /static/js/main.js HTTP/1.1" 404 1037 [25/May/2019 03:17:51] "GET /static/css/base.css HTTP/1.1" 404 1037 [25/May/2019 03:17:51] "GET /static/images/graphics/dev.svg HTTP/1.1" 404 1037 [25/May/2019 03:17:51] "GET /static/css/base.css HTTP/1.1" 404 1037 [25/May/2019 03:17:51] "GET /static/images/graphics/dev.svg HTTP/1.1" 404 1037 [25/May/2019 03:17:51] "GET /static/js/main.js HTTP/1.1" 404 1037 [25/May/2019 03:17:51] "GET /static/js/sw.js HTTP/1.1" 404 1037 Thanks