Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handling single page application url and django url
I have a single page application created in Vue.js that utilizes the HTML5 History Mode for routing, and the html file is served with Django. The urls.py of django is like so: urlpatterns = [ url(r'^$', views.home), url(r'^admin/', admin.site.urls), url(r'^api-token-auth/', obtain_jwt_token), ] And views.home: def home(request): return render(request, 'index.html') Consider the following scenario: User visits the home page (i.e., /) Since, the home page responds with required index.html for the Single page Vuejs app, it works like its supposed to. From there the user navigates to the about page (i.e., /username/12). Its still working fine, as its navigating with the Vue router. Now, the user refreshes the page. Since there's no /username/12 in the urls.py patterns, it will show Page not found (404). Now, I could provide another pattern in urls.py to catch all pattern in the last order as this: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api-token-auth/', obtain_jwt_token), url(r'^.*$', views.home), ] But other urls like the media or static urls will also point to the same catch all pattern regex. How can I solve this problem? -
OAuth Request 400 Bad Request
Our app uses resources from a third party. The resources we request are supposed to be rendered in an iframe. The way it works based on the third party specs: The 3rd party app does not provide an access token url, the only url required is the resource url. With that said, We send a post request after create an OAuth object and signature as follows: import random import time from urlparse import parse_qsl, urlparse from urllib import quote, urlencode import urllib2 import binascii import hashlib import hmac import webbrowser import json import copy import requests from django.http import JsonResponse from myapp.users.models import User CONSUMER_KEY = 'CONSUMER_KEY' CONSUMER_SECRET = 'CONSUMER_SECRET' q = lambda x: quote(x, safe="~") get_timestamp = lambda: int(time.time()) get_nonce = lambda: str(str(random.getrandbits(64)) + str(get_timestamp())) def get_sign(params, url, http_method, oauth_token_secret=""): """returns HMAC-SHA1 sign""" params.sort() normalized_params = urlencode(params) base_string = "&".join((http_method, q(url), q(normalized_params))) sig = hmac.new("&".join([CONSUMER_SECRET, oauth_token_secret]), base_string, hashlib.sha1) return binascii.b2a_base64(sig.digest())[:-1] resource_url = 'https://example.com/cat_id/rsc_id' resource_id = 1001 user = User.objects.get(id=216) # get a user who should have access to the resource user_resource_data = [ ('oauth_consumer_key', CONSUMER_KEY), ('oauth_nonce', get_nonce()), ('oauth_signature_method', "HMAC-SHA1"), ('oauth_timestamp', get_timestamp()), ('oauth_callback', 'about:blank'), ('oauth_version', '1.0'), ('resource_link_id', '%s_%s' % (resource_id, user.id)), ('user_id', user.id), ('lis_person_name_full', user.username), ('lis_person_name_family', user.last_name), ('lis_person_name_given', user.first_name), ('lis_person_contact_email_primary', … -
django allauth not translating correctly
Im using django_allauth for user authentication and registration. My web app is being developed in spanish and all the libraries im using are being translated using this settings: TIME_ZONE = 'America/Hermosillo' # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = 'es' # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id SITE_ID = 1 # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n USE_I18N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n USE_L10N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz USE_TZ = True and all text inside my page is being translated except for some of the allauth messages, for example: all form text in this image is being translated by allauth templates. but when the user registers it shows translated text for some things but untranslated text for others, like the following paragraph: the most important part for me is the confirmation email which isnt being translated at all: I have looked inside the allauth files and I have found that there is already a translation for the email template and all that stuff but it is not handling it correctly I think, is there any way I cant correct that on settings or some way to override that email generation template and provide my own? -
Where is my templating error? Django seems to have trouble figuring it out
I have been working on a Django template and am getting an error that Django seems not to be able to diagnose. See http://dpaste.com/3FGVF5S for details on the error trace; what is being pegged as the culprit is {% if pet.shelter.website %}. Pet is a Model; shelter is a ForeignKey from Pet to Shelter; Shelter is a model with a website as a UrlField(null = True, blank = True). Where should I be looking if Django basically says "I don't know why this is wrong" and the identified line number seems to be correct? -
uWSGI - Fatal Python error: PyEval_RestoreThread: NULL tstate
I'm trying to use uWSGI with processes and threads together, but when I enabled threads I got this errors (daemonize log): Fatal Python error: PyEval_RestoreThread: NULL tstate [deadlock-detector] a process holding a robust mutex died. recovering... DAMN ! worker 1 (pid: 6617) died, killed by signal 6 :( trying respawn ... I'm using Python 3.4.2 and uWSGI 2.0.14 on Debian Jessie. uWSGI config file: [uwsgi] base = /home/test chdir = %(base) module = test.wsgi:application home = /home/user/.pyenv/test-3.4.2 master = true processes = 4 threads = 5 ;I enabled this line pidfile = %(base)/test.pid harakiri = 30 post-buffering = 8000 min-worker-lifetime = 60 die-on-term = true stats = %(base)/stats.sock thunder-lock = true socket = %(base)/test.sock chmod-socket = 777 vacuum = true max-requests = 5000 logto = /var/log/uwsgi/test.log daemonize = /var/log/uwsgi/daemonize.log -
Convert user.id to user.username in Django template
I am implementing the very cool third party package Django-Simple-History into a project. Per the documentation I'm using the middleware to store which user makes changes to an object. This makes it easy to iterate over in the template like: {% for x in object.history.all %} {{ x.history_date }}, {{ x.history_user_id }} <br /> {% endfor %} I am trying to use the available user.id to get the correlating user.username in the template. Any suggestions? (I'm still pretty new to Django/Python) Thanks! -
Django - How to Get current object in queryset?
Views.py class ProfileView(UserPassesTestMixin, DetailView): template_name = "profile/profile_view.html" queryset = User.objects.all() context_object_name = 'profile' def test_func(self): x = User.objects.get(full_name="") print (x) if x is None: raise Http404("Profile Inactive") else: return True Question - If the full_name of the user is empty i want to display Profile Inactive error but i am not able to print the current full_name where i can the print command prints irrelevant data(the username). how do i get the full_name of the object? -
Multiple models save in a POST request. (Invalid data. Expected a dictionary, but got list.)
I have two models. Preference and CustomerPreference. I want to save multiple customer_preferences at a time. Now I am getting the following errror. { "customer_preferences": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } } models.py class Preferences(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100, unique=True) class CustomerPreferences(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) preference = models.ForeignKey(Preferences, db_index=True, on_delete=models.CASCADE, related_name='customer_preferences') customer = models.ForeignKey(Customer, db_index=True, on_delete=models.SET_NULL, related_name='customer_customer_preferences', null=True) status = models.CharField(max_length=100, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, on_delete=models.CASCADE, related_name='customer_preference_creator') views.py class PreferencesViewSet(viewsets.ModelViewSet): serializer_class = PreferencesSerializer queryset = Preferences.objects.all() class CustomerPreferenceViewSet(viewsets.ModelViewSet): serializer_class = CustomerPreferencesSerializer queryset = CustomerPreferences.objects.all() model = CustomerPreferences def get_queryset(self): queryset = CustomerPreferences.objects.all() customer_id = self.request.query_params.get('customer_id', None) if customer_id is not None: queryset = queryset.filter(customer=customer_id) return queryset def get_serializer_class(self): if self.action == 'list' or self.action == 'retrieve': return CustomerPreferencesListSerializer return CustomerPreferenceSaveSerializer serialzers.py class PreferencesSerializer(serializers.ModelSerializer): model = Preferences class Meta: model = Preferences fields = '__all__' class CustomerPreferencesListSerializer(serializers.ModelSerializer): model = CustomerPreferences preference = PreferencesSerializer() class Meta: model = CustomerPreferences exclude = ('id','user',) class CustomerPreferencesSerializer(serializers.ModelSerializer): model = CustomerPreferences user = serializers.CharField(read_only=True) class Meta: model = CustomerPreferences fields = '__all__' class CustomerPreferenceSaveSerializer(serializers.ModelSerializer): customer_preferences = CustomerPreferencesSerializer() class Meta: model = Preferences fields = ( 'customer_preferences',) def create(self, validated_data): request = self.context.get('request') … -
Developing and deploying Vuejs app with django
I have built a fairly simple web app in Vuejs, which was running with its default npm run dev command with webpack. Vue app was utilizing the api from Django that I have built using django-rest-framework. And whenever there was a change in Vue app it will automatically hot reload, which is pretty awesome. Now I would like run the Vue app using django instead of webpack. What I mean is that Django will respond with an html template file, and Vuejs app will run on that html file for a single page application. What I am doing now is first run this command: npm run build Then I copy the dist/static/ folder files into the django static folder. And finally load it into the template: index.html {% load static %} <!DOCTYPE html> <html> <head> ... ... <link href="{% static "css/app.e446b60204fec1f9f5510c711523ffca.css" %}" rel=stylesheet> </head> <body> <div id="app"></div> <script src="{% static "js/manifest.88376ea5d07804f39ff7.js" %}"></script> <script src="{% static "js/vendor.e0e5105739e9947a23e7.js" %}"></script> <script src="{% static "js/app.571e9140518a5bae898c.js" %}"></script> </body> </html> Now later on, if I need to change the Vue app, I have to build it again, copy the files and load it inside the template, which seems pretty lengthy. So, I am hoping there is … -
unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute'
im getting an error "unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute'" models.py from django.db import models from django.forms import ModelForm class Calculator(models.Model): parents = models.IntegerField() jobs = models.IntegerField() grants_bursaries_scholarships = models.IntegerField() student_loan = models.IntegerField() other_income = models.IntegerField() rent = models.IntegerField() travel = models.IntegerField() bills = models.IntegerField() other_outcome = models.IntegerField() def total_income(parents, jobs, grants_bursaries_scholarships, student_loan, other_income): return parents + jobs + grants_bursaries_scholarships + student_loan + other_income def fixed_outcome(rent, travel, bills, other_outcome): return rent + travel + bills + other_outcome def variable_outcomes(total_income, fixed_outcome): return total_income(Calculator.parents, Calculator.jobs, Calculator.grants_bursaries_scholarships, Calculator.student_loan, Calculator.other_income) - fixed_outcome() I'm using the model for my forms.py to create a website but I'm unsure about how to change it and how to define my total_income, fixed_outcome and variable_outcomes -
Django - Set and use site-wide variables for use in templates
I'm looking for a way to set a number of site-wide (or app-wide) variables, such as website (or app) title for instance, that I would use in my templates (in my header for instance). I have something like WordPress' bloginfo() in mind. Ideally I'd like to be able to define any type of attribute at the level of a site or an app. For a given app, for instance, I'd have : app --attribute1 (e.g. title) --attribute2 (e.g. contact email) --Model1 ----AttributeX ----AttributeY ----... Meaning that "attribute1" would be unique to my app. I would then need a way to use the value of attribute1 in my templates. I hope my question is clear. -
How can I add a widget with working scroll bar to display error/warning messages?
I am working on a Django app (1.7). The specifics are not that important but basically I am pulling data from a different database and trying to see if they exists in mine: for product in product_list: try: item = MyProduct.objects.get(code=product.code) # more logic except ObjectDoesNotExist: messages.add_message(request, messages.WARNING, "{} doesn't exist".format(product.name)) pass When I submit my form, my view returns with many warning messages one after the other, causing me to have to scroll down a lot (if there are many missing items) before I am able to view the data that does exist. I am wondering if there is a way to add messages to some fixed height widget with separate scroll bar so that I would not have to scroll more if there are more warning messages. I would like to be able to scroll through my messages, but with a separate scroll bar within a widget at the top of my page after rendering the request. -
Django Break Loop in template
Im currently displaying a table with values, and in case those values doesn't exist im displaying a button to introduce such values. The problem is that i need a break in the for loop but Django doesn't support break in templates. The current state is this: And the html for the table is the following: <table style="width:100%"> <tr> <th>Num de aluno</th> {% for quest in questionlist <th> {{quest.question_id.q_discription}} </th> {% endfor %} </tr> {% for st in students %} <tr> <td> {{st.student_number}} </td> {% for qt in questionlist %} <td> {%for tst in studentexamitems %} {% if qt == tst.qitem_id and st == tst.student_id %} {{tst.qscore}} {% endif %} {% endfor %} <a href="{% url 'newTableEntry' qt.id st.id %}"> <button type="button" class="btn btn-success btn-xs"> <span class="glyphicon glyphicon-plus"></span>&nbsp; Grade </button> </a> </td> {% endfor %} </tr> {% endfor %} </table> So the question is how do i remove the button in case of a existing grade, and keep the button in case of not existing? -
Rewrite URL to exclude Django application name
on my live server, I am trying to remove/rewrite the need to include the application name in the URL, as without it I get a 404. For example: http://www.mywebsite.com/myapp/page.html to el to http://www.mywebsite.com/page.html This is especially tricky since i don't want this to affect the django admin URL which excludes the app name. This is on Apache Server on Ubuntu on a shared host (A2). -
Running Python Django as a service in CentOs7
This is really a beginner question. I managed it to run Django on my VM. The following command line is activation the server and runs in the foreground. python manage.py runserver 0.0.0.0:8000 Now i want to run this permanent, as a test as a service in CentOs7. The idea is now to create a service which could activated by systemctl. But I am sure I am missing an important part here. Because after [Unit] After=default.target [Service] Type=simple ExecStart=/usr/bin/python /root/djangotest/python manage.py runserver 0.0.0.0:8000 [Install] WantedBy=default.target What do i miss, is it possible to add those attributes behind the ExecStart? Should i write a script and how should it look like? Do you have suggestions? -
What is the most effective way to compare, find and return a large set of mobile numbers while identifying contacts?
Say I have data for 1000 users on my DB and someone new signs up. I want them to have an easy to way find contacts already registered - via their phone number. Something very similar to WhatsApp, Allo, Instagram, Twitter etc. do - they allow you to see what contacts are already using their services. The DB stores usernames and contact information - name, number etc. If X signs up with 200 contacts, do I compare each of the 200 with each of the 1000 existing? Surely, there's a better way than taking my New User's 200 contacts and comparing each one to the existing 1000 records. How do the other services manage this? Is there a specific sort of data structure I should be maintaining for searching? Will a tree or graph structure be a more efficient approach in this scenario? If so, how should I be implementing it? I'm using DRF for the back-end implementation. I've searched around, but I don't seem to find a good answer for this problem. -
newrelic + django + gunicorn: worker timeout logged as SystemExit, is there a better way?
I'm using newrelic with a Django application served by Gunicorn. When one of my endpoints performs badly and times out, the normal gunicorn behavior is to send SIGABRT to the worker process, which then dies raising SystemExit(1). This is normal. These get logged as exceptions by Newrelic. I don't really want them cluttering up my application exception logs. It seems to me it would be more useful to view these in Newrelic as performance problems, rather than application errors. Is there any way to 1) stop logging these as SystemExit exceptions, but 2) still see them as web transaction timeouts on the newrelic UI? -
Calling a function into an other function in Python (Django)
I'm trying to call a function into a function in django but I keep getting: The view app.views.function1 didn't return an HttpResponse object. It returned None instead. My views are: def function1(request): [some api calls] #Once this process is done I want to call my second function function2() and then I have def function2(request): How you call an other function in Django/Python easily p.s. These functions could just be one, I just want to divide them to have my code more readable and have one function do only one thing. -
Sending Django ManyToMany signals
Hi i am a Medical Doctor, and i have been working with Django for the past 3 months. I want to send a ManyToMany signal to save from one model to another. I have gone through all the examples on stackoverflow and the django documentation and i still cant get it to work. Here is my code; class GeneralConsulting(models.Model): id = models.AutoField(primary_key=True) patient_ID = models.ForeignKey(PatientProfile) temp = models.CharField(max_length=10, blank=True, editable=True) pulse = models.CharField(max_length=10, blank=True, editable=True) investigations_nhis = models.ManyToManyField(NHIS_labs, blank=True) class Lab_bill(models.Model): ID = models.AutoField(primary_key=True) patient_ID = models.ForeignKey(PatientProfile) type_of_insurance = models.CharField(max_length=50, blank=True) type_of_lab = models.ManyToManyField(NHIS_labs, blank=True) attendance_date = models.DateTimeField() @receiver(models.signals.m2m_changed, sender=GeneralConsulting.investigations_nhis.through) def change_labs(self, sender, instance, **kwargs): m2m_changed.connect(Lab_bill, sender=GeneralConsulting.investigations_nhis.through) bill2 = Lab_bill(type_of_lab=instance.investigations_nhis) bill2.save_m2m() But the above code saves all the other entries except the m2m field. Also when i use change_labs as my first argument in m2m_changed.connect I get an error that change_labs is not defined. Actually, i have tried several suggestions from all over the internet and i am even getting confused. Kindly help. -
Django: MultiChoiceField does not show saved choices added after creation
I am currently trying to create a dynamic product model that will allow admins to create add their own "option sets" to products. For example, Product A has flap valve with 400mm, 500mm and 600mm widths available. To facilitate this I have created 3 models. models.py # A container that can hold multiple ProductOptions class ProductOptionSet(models.Model): title = models.CharField(max_length=20) # A string containing the for the various options available. class ProductOption(models.Model): value = models.CharField(max_length=255) option_set = models.ForeignKey(ProductOptionSet) # The actual product type class HeadwallProduct(Product): dimension_a = models.IntegerField(null=True, blank=True) dimension_b = models.IntegerField(null=True, blank=True) # (...more variables...) flap_valve = models.CharField(blank=True, max_length=255, null=True) ...and a form... forms.py class HeadwallVariationForm(forms.ModelForm): flap_valve = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple) def __init__(self, *args, **kwargs): super(HeadwallVariationForm, self).__init__(*args, **kwargs) self.fields['flap_valve'].choices = [(t.id, t.value) for t in ProductOption.objects.filter(option_set=1)] def save(self, commit=True): instance = super(HeadwallVariationForm, self).save(commit=commit) return instance class Meta: fields = '__all__' model = HeadwallProduct This works fine for during the initial creation of a product. The list from the MultipleChoiceForm is populated with entries from the ProductOptionSet and the form can be saved. However, when the admin adds a 700mm flap valve as an option to the ProductOptionSet of Product A things fall apart. Any new options will show up in the … -
Reencode django request body with another encoding
We're using sendgrid's webhook parsing api. We receive a post request for every email. Sendgrid explains here that the field charsets contains information which charset/encoding the fields text and html have: [charsets] => {"to":"UTF-8","cc":"UTF-8","subject":"UTF-8","from":"UTF-8","text":"iso-8859-1"} Now in Django I'm doomed, because Django already applied utf-8 encoding on the hole request body, so i already lost data. Is it possible to reencode the body with another encoding and just get text out of it? Here is a simplified example: from django.views.generic import View from django.http import QueryDict import json class Webhook(View): def post(self, request): """ Explaining the problem if sendgrid sends the `text` content in a different charset then 'utf-8'. See sendgrid documentation here: https://sendgrid.com/docs/API_Reference/Webhooks/inbound_email.html#-Character-Sets-and-Header-Decoding """ charsets_info = request.POST.get('charsets') charsets = json.loads(charsets_info) charset = charsets.get('text') if charset.lower() not in ['utf-8', 'utf8']: # I know, this don't work, but how would something # like this be possible in Django? new_post = QueryDict(request.body, encoding=charset) text = new_post.get('text') else: text = request.POST.get('text') # go on and work with text... Thank you for your help! -
Django rest-framework APIClient post request with csrf check
I am writing django rest api unittest when I get this problem. The api is for user registration. For convenience I use the @csrf_exempt decorator in view.py to bypass csrf check. # url: '^register/$' @csrf_exempt def registration(request): ... I use the the APIClient in django rest-framework to fire the request. from rest_framework.test import APIClient client = APIClient() class RegisterTest(TestCase): def setUp(self): pass def test_create_user(self): data = { # basic info 'username': 'foo', 'password': '123456', 'email': 'foo@foo.com', # profile info 'company': 'foo', 'registration_code': 'foo', 'phone_number': 'foo', } response = client.post('/register/', data, format = 'json') # check successful registration self.assertEqual(response.status_code, 200) Then I tried to force the csrf validation in my view.py. Just simply take away the decorator and use post request will force a csrf check in my opinion. And according to this post, I specifically created a api for csrftoken retrieve view.py # url: '^register/$' def registration(request): ... # url: '^token/$' @ensure_csrf_cookie def token(request): For test.py I am following django-rest-framework documentation for the setup. The only difference is I used APIClient rather than RequestClient to do the test. test.py from rest_framework.test import APIClient # enforce csrf validation client = APIClient(enforce_csrf_checks = True) class RegisterTest(TestCase): def setUp(self): pass def test_create_user(self): data … -
convert a sql queries into the django
View def group_codes(self): final_shelves = self.final_shelf_info() stbrole_codeInfo = ResultsTestsCodes.objects.filter( results_test_id=self.kwargs['testID'], ).values('build').annotate( script_fail = Sum('script_fail'), script_total = Sum('script_total'), post_testing_fail = Sum('post_testing_fail'), post_testing_total = Sum('post_testing_total'), mr_fail = Count('stb_role'), gw_fail = Count('stb_role'), ).order_by( 'build', ) return stbrole_codeInfo Module from django.db import models class ResultsTestsCodes(models.Model): results_test_id = models.IntegerField(primary_key=True) build = models.CharField(max_length=401) tr_codes_id = models.IntegerField() pair_no = models.IntegerField() stb_names = models.CharField(max_length=1600) build = models.CharField(max_length=41) pre_testing_pass = models.IntegerField() pre_testing_fail = models.IntegerField() pre_testing_total = models.IntegerField() script_pass = models.IntegerField() script_fail = models.IntegerField() script_total = models.IntegerField() post_testing_pass = models.IntegerField() post_testing_fail = models.IntegerField() post_testing_total = models.IntegerField() stb_role = models.CharField(max_length=2) class Meta: managed = False db_table = 'results_tests_codes' Template Total failed details:<br /> <b>------------------------</b> <br /> {% for code in group_codes %} *_{{ code.build }}_*<br /> {% if test_info.test_type = 0 %} {{ code.pre_testing_fail }}/{{ code.pre_testing_total }} failed pre-test<br /> {% else %} {{ code.mr_fail }}/{{ code.script_total }} <span>MR</span> failed during script<br /> {{ code.gw_fail }}/{{ code.script_total }} <span>GW</span> failed during script<br /> {{ code.mr_fail }}/{{ code.post_testing_total }} MR failed during post-test<br/> {{ code.gw_fail }}/{{ code.post_testing_total }} GW failed during post-test<br/> <br/> <br/> {% endif %} {% endfor %} <br /><br /> I am trying to count failed mr and gw and write this results on my template. {{ code.mr_fail }} … -
unsupported operand type(s) for -=: 'str' and 'int'
I have this error, could you help me? You need to subtract the "quantity" value from the "Pedido" - "stock" model of the "Articulo" model, then save the stock result. in line: articulo.stock -= pedido.cantidad def Update_stock(request, id_pedido, cod_experto): if request.method == 'GET': pedido = Pedido.objects.get(id=id_pedido) articulo = Articulo.objects.get(pk=cod_experto) articulo.stock -= pedido.cantidad articulo.save() return render(request, 'admindata.html', {'pedido':pedido, 'articulo':articulo}) models.py: class Pedido(models.Model): articulo = models.ForeignKey('Articulo') fecha_pedido = models.DateTimeField(auto_now_add=True,null=True, blank=True) cantidad = models.IntegerField(blank=True) def __str__(self): return '{}'.format(self.especialidad, self.articulo, self.cantidad, self.estado) class Articulo(models.Model): cod_experto = models.CharField(max_length=999, primary_key=True, blank=True) nombre = models.CharField(max_length=999, blank=True) on_delete=models.CASCADE) stock = models.CharField(max_length=999, blank=True) -
[django]when debug=false,MEDIA_URL returns not found
when DEBUG=TRUE,media_url is working,but DEBUG = False ,returns not working. This is my setting file. setting.py DEBUG = False ... MEDIA_URL = "/pics/" MEDIA_ROOT = BASE_DIR urls.py urlpatterns = [ .... .... ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) home.html ... <img src="{{ post.image.url}}" ..> models.py class Post(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() image = models.ImageField(upload_to="media/") maybe,this setting is recommended debug-mode. What shuld I change this setting.