Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serve MEDIA_URL a view in urlpatterns
I'm trying to make a view for MEDIA_URL and insert the url into urlpatterns. I have MEDIA_URL with link to amazon S3 resource. How to make urlpattern to invoke my view, where the url is external link, but is MEDIA_URL of my project? I've tried to insert just media/ url, but this doesn't get invoked: url(r'^media/', media_view), surely because it is not original website that I'm serving with django app. urlpatterns = [ url(r'^$', home_view), ] -
Saleor Django SQL errors on Win 10//eCommerce
i have this problem for a few days now, and i cant solve it. I have red all the docs and files and did everything as instructed. So basically, i've installed Django latest ver, installed Python 3.x also the latest ver, and wanted to implement Saleor and work on a new e commerce web app. Gone to Saleor Win installation Docs(official), installed all the required apps like SQL, git etc.. and got no errors. Ofc, i did all of that via vurtualenv which i placed in the separated folder. So i have>Project>ecommerce and myvenv folders inside. I placed saleor in ecommerce. The problem starts when i try to do python manage.py migrate > i get an SECRET_KEY error. And my question is, how to deffine a secret key on windows cmd?? And next question is about installing SQL. It seems that i just CANT deffine new db using cmd on windows. This just keeps giving me nightmares. Thank you for your time. -
Django - creating XML file from Template - MemoryError
I'm getting MemoryError when trying to create an XML file using Django templates. class Export(TimeStampedModel): xml_file = models.FileField(upload_to='exports/', null=True, blank=True) @classmethod def generate_and_save(cls): export = Export.objects.create() string = render_to_string('exporter/export.xml', {'object_list': Product.objects.active()}) now_string = now().strftime('%d%m%Y_%H%M%S') export.xml_file.save(f"export_{now_string}.xml", ContentFile(string)) The problem is obvious. There are hundreds of thousands of products and the whole rendered template is stored in memory until written to file. Is it possible to do it in chunks or stream? -
django-filter chained select
I'm using django-filters lib https://django-filter.readthedocs.io/en/master/index.html. I need to make chained select dropdown in my filters. I knew how to make it with simple django-forms like here https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html. When user pick region, i need to show cities in this region? Have someone idea or solution how to build filters like this? -
Revert emails fetched via django-mailbox, back to Gmail inbox
I am a Django newbie. I have setup a mailbox in Django admin using the django-mailbox package. The URI configuration was a Gmail IMAP email server. While retrieving mails into my Django mailbox, they got deleted from the inbox and got created as db records. Is there a way to revert the emails back to the Gmail inbox, either using a Django API, gsuite's email recovery, or exporting data from db into Gmail inbox? Thanks in advance for your help. P.S. the mails are not present in the trash folder. -
How to perform model.objects.get(**kwargs) with case insensitive
I would like to get an instance of one of my Django models by using dictionary in an insensitive case way. For the moment I'm using: my_model.objects.get(**dictionary) But I don't get the instance if there is a difference of lower / upper case between what there is in my dictionary and the fields of the instance. Do you think there is a clean way to perform this operation ? -
Trying to display an SVG (vector) logo via static files in Django?
I have created a .SVG organisation logo using Sketch. I'm trying to display this logo/ vector file on a website but I cannot get it to show. I have put the .SVG inside my static images in Django. My other static images (.jpg) show fine on my browsers but nothing shows when I try to include the .svg file. Is there something wrong with the way that I am including it in my HMTL? Or have I missed something else? <img src="{% static 'images/company-logo.svg'%}" alt="" width="100px" height="100px"> -
How can i modify a db connection for a specific testmethod in a Django TestCase (and then restore upon completion)?
I have a special case where i need to run certain testmethods against one database and other testmethods against another while maintaining the same alias (within a given TestCase). I am not asking about multiple db connections, the issue is changing a db connection for a given alias within a testmethod, and then reverting it back to the default state after the test method executes. I have tried the following (this code is placed within my TestCase): from django.db import connections from django.db.backends.postgresql.base import DatabaseWrapper def testSwitchDBParamsForAlias(self): db_wrapper = DatabaseWrapper( 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST' : 'host', 'PORT' : '2342, 'NAME' : 'dbname', 'USER' : 'user', 'PASSWORD': 'password' ) connections.__setitem__('dbalias', db_wrapper) print(connections._databases) # This still has the old connection In the code above, 'dbAlias' already exists with different credentials and im trying to swap the credentials out using the setitem method. Another attempt using the context manager: def testSwitchDBParamsUsingCM(self): with self.settings(DATABASES = DATABASES): # call setup_databases here print(connections._databases) #old credentials printed here Neither works and I am left not understanding how this connection object works at all. Any ideas/suggestions? -
Nginx as reverse proxy django gunicorn returning 400 bad request
I'm trying to use nginx as a reverse proxy to receive incoming calls, then, depending on the server_name, redirect those calls to different computers (hosts), running nginx Django and Gunicorn. So far, I've tried different configurations for the conf file on the host, but none of them are working. Is there anything wrong with my conf files? This is the nginx.conf in 192.168.0.13 that will function as a reverse proxy: server { listen 80; server_name www.coding.test; location / { proxy_pass http://192.168.0.8:80; proxy_redirect off; # app1 reverse proxy follow proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } This is the nginx.conf in 192.168.0.8 that is intended to run the django app: upstream django { server unix:///home/pi/coding-in-dfw/mysocket.sock fail_timeout=0; } server { listen 80 default_server; server_name www.coding.test client_max_body_size 4G; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location /static/ { alias /home/pi/coding-in-dfw/static/; } location /media/ { alias /home/pi/coding-in-dfw/media/; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed } location /.well-known { alias /home/pi/coding-in-dfw/.well-known; } } Finally this is the way I'm running gunicorn: gunicorn --workers 5 --bind unix:///home/pi/coding-in-dfw/mysocket.sock codingindfw.wsgi:application && sudo service nginx restart Any help is appreciated. -
How do I preserve old data upon page reload in a pull down menu?
I am struggling with preserving old data in a form upon page reload (if you user didn't successfully fill out entire form or otherwise gets validation errors) when the field is a pull down. Here is my current code: <div class="form-group"> <select class="form-control" name="primary_instrument" id="primary_instrument" placeholder="Primary instrument"><option {% if old_data.primary_instrument %} selected {% endif %} disabled>Primary instrument</option> {% for instrument in instruments %} <option value='{{ instrument.id }}'>{{ instrument }}</option> {% endfor %} </select> <div class="error-message"> <p> {% if 'primary_instrument' in errors %} {{ errors.primary_instrument }} {% endif %} </p> </div> </div> Thank you! -
Django: Pass argument to Listview from FormView
I have a FormView that will be used to pass arguments to a ListView. I am not very confident about how to properly use these classes or how to correctly pass arguments... I want to pass these arguments by using kwargs such as follow: class NextPageView(ListView): template_name = 'pages/next.html' model = TimeSTimeE def get_queryset(self): dateEnd = self.request.GET.get('timeE', 'give-default-value') dateStart = self.request.GET.get('timeS', 'give-default-value') new_context = model.objects.filter(date__range=(dateStart, dateEnd)) return new_context class BacktestForm(FormView): template_name = 'pages/backtest.html' form_class = FormBacktest # success_url = 'pages/next.html' def form_valid(self, form): time1=form.cleaned_data['dateStart'].strftime('%Y-%m-%d %H:%M:%S') time2=form.cleaned_data['dateEnd'].strftime('%Y-%m-%d %H:%M:%S') return super().form_valid(form, kwargs={'timeS': time1, 'timeE': time2, }) In my urls: path('next/', views.NextPageView.as_view(), name='next'), path('backtest/', views.BacktestForm.as_view(), name='backtest'), However, form_valid doesn't let me pass kwargs. What is the best strategy? Thanks in advance, -
How to import or call PY code in HTML within django framework
I wrote a py file that uses two APIs to retrieve data about current crypto trends. I am trying to import or call the retrieved data in an HTML file do display in my web app. I have tried using {{% %}} to call the py file, but not sure if I am doing the right thing. import requests url_usd = 'https://api.coingecko.com/api/v3/coins/markets? vs_currency=usd&order=market_cap_desc&per_page=250&page=1' \ '&sparkline=false&price_change_percentage=24h' url_gbp = 'https://api.coingecko.com/api/v3/coins/markets? vs_currency=gbp&order=market_cap_desc&per_page=250&page=1' \ '&sparkline=false&price_change_percentage=24h ' requests1 = requests.get(url_usd) results1 = requests1.json() requests2 = requests.get(url_gbp) results2 = requests2.json() for i in range(0, 250): coin_id = results1[i]['id'] coin_name = results1[i]['name'] changes = results1[i]['price_change_percentage_24h'] usd = results1[i]['current_price'] gbp = results2[i]['current_price'] print("Coin ID: " + coin_id) print("Coin name: " + coin_name) print("Price per coin in USD: " + "$" + "{:.2f}".format(float(usd))) print("Price per coin in GBP: " + "£" + "{:.2f}".format(float(gbp))) print("Percentage price change: " + "{:.2f}".format(changes) + "%") print() Output: Coin ID: bitcoin Coin name: Bitcoin Price per coin in USD: $3461.54 Price per coin in GBP: £2645.04 Percentage price change: 0.82% Coin ID: ripple Coin name: XRP Price per coin in USD: $0.31 Price per coin in GBP: £0.23 Percentage price change: -0.60% and so on for the next 250 coins I want to now … -
How to contact firebase between android and django server?
My app contains two methods for signing in and signing up: Using the Django server which I made. Using Firebase service. I'm not familiar with Firebase and I don't know how a user information like email and user name and password stores to the server. Can I implement Firebase features into the server to contact between android and Firebase and server? Please explain how. -
How does Django's Rest Framework's ModelSerializer overriding works?
I am following case I can't figure out how the following code which uses rest_framework is working. I looked in the documentation but was not able to find much help there. ( This code comes from a django tutorial but no information was given there) Here is the model: class Tweet(models.Model): parent = models.ForeignKey("self",blank=True,null=True,on_delete=models.CASCADE) user = models.ForeignKey(Profile,on_delete=models.CASCADE) content = models.CharField(max_length=140,validators=[validate_content]) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) And the serializers: class TweetModelSerializer(serializers.ModelSerializer): user = UserDisplaySerializer(read_only=True) #write_only date_display = serializers.SerializerMethodField() timesince = serializers.SerializerMethodField() parent = ParentTweetModelSerializer() class Meta: model = Tweet fields = [ 'id', 'user', 'content', 'timestamp', 'date_display', 'timesince', 'parent' ] // other lines of code class ParentTweetModelSerializer(serializers.ModelSerializer): user = UserDisplaySerializer(read_only=True) #write_only date_display = serializers.SerializerMethodField() timesince = serializers.SerializerMethodField() So parent is a field in my original Tweet model but when I use a Serializer to override or replace the field "parent",how can the ParentTweetModelSerializer determine which parent tweet is related TweetModelSerializer's tweet with it without us passing any data to it ( as we didnt passed anything in ParentTweetModelSerializer() ? I was unable to find anything related with it in the rest_framework's documentation. -
Django - Admin page login also logged into user authentication
After I logged in to admin page, my site also logged in by superuser. And when I logged out from it also logged out from admin. Please help me. -
How do I limit matches with a vanilla javascript autocomplete?
I created a like/dislike functionality for my Django app. It uses jQuery/ajax and works fine, but it breaks my Devbridge autocomplete search (https://github.com/devbridge/jQuery-Autocomplete). I've decided to replace the Devbridge autocomplete with a vanilla JS autocomplete from here: https://www.w3schools.com/howto/howto_js_autocomplete.asp. The problem is I have over 10,000 items in my array, so when you type in the first few letters it produces 100s or thousands of matches. I'd like to limit the number of matches. Any help is much appreciated. I've included what I'm guessing is the most relevant code. For the complete code just check out the link. <script> function autocomplete(inp, arr) { /*the autocomplete function takes two arguments, the text field element and an array of possible autocompleted values:*/ var currentFocus; /*execute a function when someone writes in the text field:*/ inp.addEventListener("input", function(e) { var a, b, i, val = this.value; /*close any already open lists of autocompleted values*/ closeAllLists(); if (!val) { return false;} currentFocus = -1; /*create a DIV element that will contain the items (values):*/ a = document.createElement("DIV"); a.setAttribute("id", this.id + "autocomplete-list"); a.setAttribute("class", "autocomplete-items"); /*append the DIV element as a child of the autocomplete container:*/ this.parentNode.appendChild(a); /*for each item in the array...*/ for (i = 0; i … -
Django JSON field in Serializer validated_data is None
I have a Django Model which looks something like this: class Foo: data = JSONField(encoder=DjangoJSONEncoder, default=dict) And I have the corresponding serializer for it which is pretty basic: class FooSerializer(BaseSerializer): class Meta: model = models.Foo fields = '__all__' What I want to do is to have some validations for that JSON field in the serializer. I tried doing this via overriding the validate and create functions but in both cases the value for attrs.data or validated_data.data is None. The weird part is that if I create the same validations in the pre-save or post-save signals then the instance.data value is not None and actually has the value I'm passing in the request. I'm wondering if I'm doing something wrong or does DRF not support doing validations for JSON fields in the serializer and just expect you to do it in the signals. That seems kinda wrong. -
Creating a left join in Django with null values
I'm trying to create a Django equivalent of a SQL LEFT OUTER JOIN. However I'm having trouble with this. class Course(models.Model): name = models.CharField(max_length=255) class Grades(models.Model): grade = models.CharField(max_length=3) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) What my goal is, is to loop over all courses and when there is a value for the student (which I already have) then print out his/her grade. It seems really easy to me but I just cannot figure it out... -
Django url patterns: good practice?
I am wondering whether the following is considered "bad practice". I have multiple urls.py files per app in a Django project. So for example I have in a single app called locations I may the following files: # locations/urls/api.py # locations/urls/general.py Both of these are included in "main url file": # settings/urls.py from django.urls import include, path urlpatterns = [ # ... snip ... path('api/locations', include('locations.urls.api')), path('locations/', include('locations.urls.general')), # ... snip ... ] The reason I am considering this construction is because I want some "location urls" to be within the api/... routes combined with routes coming from other apps into the api/... routes and some I would like to be just within the locations/... routes. I hope my explaination is clear. Let me know what you think of this construction! Cheers! -
How to display an URL added by the user in Django template?
I have the following Dashboard and I have to add a section called Design where the users will be able to have an input file and add their own design link files. Right now this don't work, they are just html tags. What I want to achieve is that the user add their Figma or Sketch link, click on the Add Link button and then the link displays below the input. I added this to the model: design_file = models.URLField(max_length=250) and this is how my html file looks like: <div class="project-details__section scrollbar scrollactivity"> <h2 class="project-details__subhead">Design</h2> <input type="text"> <button>Add Link</button> </div> Any suggestions in how to achieve this? I saw several tutorials but I can't connect what I need with the given information. -
Get an error when trying to connect to neo4j database from Django
I am following this tutorial to start with Django and neo4j, but as the first import is reached, I get this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/core/management/base.py", line 329, in run_from_argv connections.close_all() File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/db/utils.py", line 220, in close_all for alias in self: File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/db/utils.py", line 214, in __iter__ return iter(self.databases) File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraph/AttractoraGraph/settings.py", line 14, in <module> from neomodel import config File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/neomodel/__init__.py", line 3, in <module> from .core import * File "/Users/hugovillalobos/Documents/Code/AttractoraGraphProject/AttractoraGraphVenv/lib/python3.6/site-packages/neomodel/core.py", line 9, in <module> from neomodel.util import Database, … -
DPI-1047 "libclntsh" cannot open shared object file: No such file or directory"
I have a django application hosted in centos os. Below is the configuration:- Python:- 3.7.2 Django:- 1.11.18 cx_Oracle:- 7 Oracle Instant Client:- 12.1 OS:- centos Oracle Version:- 11g WSGI Server:- Gunicorn Reverse Proxy Server:- Nginx When I import cx_Oracle from the python3 shell, it works. But when I start my application, on every redirect from within the application I get the same error. Not sure what to do about it. I dont know what code to post for this, so if any of you want to see some particular code snippet then let me know, I will edit and add that portion of the code. I have been working on it for two days without any progress, would really appreciate some help. -
error when ran "python manage.py runserver"
I did . virtualenv env skill --python=python3 cd skill source bin/activate pip install django==2.1 django-admin.py startproject start cd start -python manage.py runserver : giving error -link to the pic : here! -
DRF Read only field is still validated
I have a field that I want always to be the user. My serializer is like this: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' read_only_fields = ('user',) def perform_save(self, serializer): serializer.save(user=self.request.user) But it gives me the error NOT NULL constraint failed: app_my_model.user_id but the field is read_only... I don't get this. -
Controlling time-out of memcached when using it as a cache backend for Django's cached_db session setting
In a Django project when using cached_db type session caching: 1) How does one control the time-out of the cache backend? For instance, I want each session data object saved in memcached to have a ttl of 20 days. I moreover want this ttl to update on subsequent writes (if they happen). 2) Will memcached automatically scale to consume all RAM available in case there's a huge influx of session writes? Can I dictate the memory allocation? Moreover, are there any best-practices if there's a spike in data? When I see /etc/memcached.conf, there doesn't seem to be a lot of levers one can pull. Would be awesome to get an illustrative answer. Background: I've traditionally relied on DB-based session caching, and only now have mulled shifting over to cached_db. Thus I'm somewhat green on the subject. My current cache settings are as follows (set in settings.py): if ON_PROD_SERVER == '1': CACHES = { 'default': { 'BACKEND':'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION':'unix:usr/local/var/run/memcached/memcached.sock', } } else: CACHES = { 'default': { 'BACKEND':'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION':'unix:/var/run/memcached/memcached.sock', } }