Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
404 On Using Azure Storage In Django Application
I am trying to deploy a Django application on Microsoft Azure. I am using nginx + gunicorn on a Azure Virtual Machine. For serving static and media files, I have decided to use Azure Blobs available in Azure Storage. I am using the following library to integrate a Markdown + MathJax editor in my application - django-mdeditor. Now, this library comes with its own JS and CSS files. I am having no problem on using this library in the following scenarios - Local Development. Deployment on Heroku (production). Deployment on Azure Virtual Machine using nginx + gunicorn (production). In this case, I am serving the static files using nginx as mentioned in various tutorials, such as this one. However, as soon as I shift to Azure Storage as my storage back-end. I am getting the following errors - Failed to load resource: the server responded with a status of 404 (The specified blob does not exist.) codemirror.min.js:1 Failed to load resource: the server responded with a status of 404 (The specified blob does not exist.) codemirror.min.css:1 Failed to load resource: the server responded with a status of 404 (The specified blob does not exist.) dialog.css:1 Failed to load resource: the … -
Seaching dishes from nearest restaurant and one dish from a chain
my django model relationship is like below. class Chain(DatesModel): name = models.CharField(max_length=300, db_index=True) class RestaurantModel(models.model): name = models.CharField(max_length=300, db_index=True) address = models.TextField(null=True, blank=True) latitude = models.DecimalField(max_digits=10, decimal_places=7, default=40.7128) longitude = models.DecimalField(max_digits=10, decimal_places=7, default=74.0060) location = GisModels.PointField(geography=True, srid=4326, default=Point(-73.935242, 40.7306)) chain = models.ForeignKey(Chain, related_name="restaurant_chain", on_delete=models.DO_NOTHING, null=True, blank=True) class DishModel(models.model): dish_name = models.CharField(max_length=100, help_text="Dish Name") restaurant = models.ManyToManyField(RestaurantModel, null=True, blank=True) chain = models.ForeignKey(Chain, related_name="restaurant_chain", on_delete=models.DO_NOTHING, null=True, blank=True) chain is like McDonald's, Burger King, KFC. Now problem is searching a nearest dish with restaurant and there will be on dish from a chain. how this relationship can be managed in Elasticsearch or alternate solution. -
Django project in docker container unable to run manage.py runserver
I'm new to docker, and struggle a bit to wrap my head around container/image/service concept. I am unable to start container with django image. Here is my Docker file: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /django-ex COPY /django-ex /django-ex WORKDIR /django-ex RUN pip install -r requirements.txt 'Build' works fine no errors. But 'up' fails with error: web_1 | python: can't open file '/django-ex/manage.py': [Errno 2] No such file or directory maria-ra-staff_web_1 exited with code 2 Here is my docker-compose.yml: version: '3.6' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/django-ex ports: - "8000:8000" depends_on: - db I don't understand why 'up' doesn't have my project files. Did I miss something in the process? -
psycopg2.IntegrityError: duplicate key value violates unique constraint "engine_attackimage_pkey" DETAIL: Key (id)=(19) already exists
I am not manually setting the primary key. How could this be happening? I've been usign Django for 5 years and never encountered anything like this. Can someone help? -
Sending email via Django causes Server Error (500)
I'm trying to send email from admin to users who fill form and as result getting Server Error (500). How can I fix this error ? Here are my codes: (btw everything works very well when I'm running my application on my local server, but on IP it results with an error) views.py: from django.shortcuts import render from .models import Question, Message from django.core.mail import send_mail from django.conf import settings def index(request): context = { 'questions': Question.objects.all() } if request.method == "POST": if request.POST.get('message_text'): Message.objects.create( sender_name = request.POST.get('sender_name'), sender_email = request.POST.get('sender_email'), message_text = request.POST.get('message_text')) if request.method == 'POST': sender_email = request.POST.get('sender_email') sender_name = request.POST.get('sender_name') subject = 'Welcome !' message = 'Dear ' + str(sender_name) + '! \n We will back to you.' from_email = settings.EMAIL_HOST_USER recipient_list = [sender_email] send_mail(subject, message, from_email, recipient_list) return render(request, 'index.html', context) settings.py: EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 SERVER_EMAIL = 'hi@mail.com' EMAIL_HOST_USER = 'hi@mail.com' EMAIL_HOST_PASSWORD = '******' -
How to group result by query in orm
Can i group results on the basic of field in User model. models.py class User(AbstractUser): USERTYPE = (('1','type_1'),('2','type_2'),....) user_type = models.CharField(max_length=2,choices=USERTYPE) ..... views.py User.object.all().values('first_name','last_name') How can i get all users data with groupby there type in below format by using django ORM query only.. { "type_1":[ { "first_name":"abc", "last_name":"xzy" }, { "first_name":"abcd", "last_name":"wxzy" } ], "type_2":[ { "first_name":"abcdd", "last_name":"xzddy" }, { "first_name":"absdcd", "last_name":"wxsdzy" } ] } -
Kill a django process that was initiated using python
I had used python to initiate the django server. After it started, I worked upon my project and finally decided to stop the server. It could be done by using the the task manager. But it requires administrative privileges to stop it. I wish to use CLI to stop the server and that to without giving it special administrative privileges. (Favorably by changing the code of the python file below). #Python code below from subprocess import Popen Popen("workon Test & cd C:/Users/HP/Desktop/Keshav/PureTest/trial & python manage.py runserver", shell = True) Thanks in advance and sorry for my poor english. -
Error while deploying Django app on cpanel(shared hosting)
I m new to django. I created a web with dajngo,and successfully deployed it in the server The python app has been successfully setup and virtual environment has been setup. but while running the web it gives me "Server Error (500)" I don't know whats the problem. I think error is in "wsgi.py" file but i'm unable to idenify it. My wsgi file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'karan_web.settings') application = get_wsgi_application() can someone help me with it; -
Can't combine different query sets and render them in django
So i have to render a table on html template which combines columns from 2 different base models. But the table doent seem to render well. Entries from other table are shown in different rows. here is the screenshot of the table that has rendered -I used the chain method from ittertools for this purpose. Not sure where I messed up. Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) image = models.ImageField(upload_to='profile_pics') dob = models.DateField() email = models.EmailField(max_length=50, unique=True) class Placement(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(max_length=40) position = models.CharField(max_length=40) city = models.CharField( max_length=40) bond = models.CharField( max_length=40) ctc = models.CharField( max_length=40) my Views.py: def mentorintern(request): table = Placement.objects.all() name_student = Profile.objects.all() in_table = list(chain(table, name_student)) return render(request, 'mentorinternship.html', {'in_table': in_table }) HTML template used to render the table: <table class="table align-items-center table-flush table-hover" id="dataTableHover"> <thead class="thead-light"> <tr> <th>Name of Student</th> <th>Company</th> <th>Position</th> <th>City</th> <th>CTC</th> <th>Bond</th> </tr> </thead> <tbody> {% for std in in_table %} <tr> <td>{{std.first_name}}</td> <td>{{std.company}}</td> <td>{{std.position}}</td> <td>{{std.city}}</td> <td>{{std.ctc}}</td> <td>{{std.bond}}</td> </tr> {% endfor %} </tbody> </table> -
DB connection stopped working in docker-compose file
This docker-compose file was working fine six months ago. But recently I tried to use it to test my app and received this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db-test" to address: Name or service not known I read through some other stack overflow answers and tried adding 'restart: always' to the web service. I also tried adding a local network to the compose file, and nothing has worked. Any ideas what I am doing wrong? Here is my compose file: version: '3' services: # postgres database db-test: image: postgres:10.9 environment: - POSTGRES_PASSWORD=example volumes: - pg-test-data:/var/lib/postgresql/data # main redis instance, used to store available years for each organization redis-test: image: redis:5.0.4 volumes: - redis-test-data:/data # redis cache used for caching agency pages like /agencies/salaries/ redis_cache-test: image: redis:5.0.4 # search engine elasticsearch-test: image: elasticsearch:5.6.10 volumes: - elasticsearch-test-data:/usr/share/elasticsearch/data # web app web-test: build: . environment: - DATABASE_URL=postgresql://postgres:example@db-test/postgres - ENVIRONMENT=development - REDIS_URL=redis://redis-test:6379 - REDIS_CACHE_URL=redis://redis_cache-test:6379 - ELASTIC_ENDPOINT=elasticsearch-test:9200 env_file: docker.env depends_on: - db-test - redis-test - redis_cache-test - elasticsearch-test volumes: - .:/code # worker instance for processing large files in background worker-test: build: . command: python run-worker.py environment: - DATABASE_URL=postgresql://postgres:example@db-test/postgres - ENVIRONMENT=development - REDIS_URL=redis://redis-test:6379 - REDIS_CACHE_URL=redis://redis_cache-test:6379 - ELASTIC_ENDPOINT=elasticsearch-test:9200 env_file: … -
How do I change my CELERY_BROKER_URL in an already daemonized Celery process?
I'm daemonizing my Celery worker using Supervisord. The issue is I had a typo in my CELERY_BROKER_URL and the worker is not properly connecting to RabbitMQ. When I run celery -A mysite report it shows the old environment variable. My /etc/supervisor/conf.d/celery.conf file does not include the environment variables: [program:celery] command=/webapps/mysite/scripts/celery/celery_start autostart=true autorestart=true user=myuser stdout_logfile=/webapps/mysite/logs/celery.log redirect_stderr = true The environment variables are picked up via my virtual environment in the celery_start script: #!/bin/sh DJANGODIR=/webapps/mysite/mysite # Activate the virtual environment. cd $DJANGODIR . /webapps/mysite/bin/activate . /webapps/mysite/bin/postactivate # Programs meant to be run under supervisor should not daemonize themselves # (do not use --daemon). exec celery -A mysite worker -E -l info --concurrency=2 When I check the CELERY_BROKER_URL environment variable after activating the environment it is correct. I've tried supervisorctl restart celery which doesn't pick up the new environment variable (celery -A mysite report shows the old CELERY_BROKER_URL). I've tried supervisorctl shutdown and then supervisord which also won't pick up the new environment variable. When I run ps aux | grep 'celery worker' I don't see anything, presumably because Celery is daemonized by Supervisor, so I'm not sure of a way to completely destroy the current Celery process. No matter what, it feels … -
Django ORM Query multple keywords and retrun multiple list of of objects with single query
These are my model: class Topic(models.Model): name = models.CharField( max_length=50 ) class Question(models.Model): title = models.CharField( max_length=100 ) topic = models.ForeignKey( Topic, on_delete=models.CASCADE ) For example, I have many questions with the topic from many topics, I am trying to query english, biology topic-related question. and this my current query: question = Question.objects.filter( topic__name__in=["english", "biology"] ).values('title', 'id', 'topic') It returns all the biology and english related question. I dont want exactly like this. I want, it will return all the question that english and biology related questions but should be with group, like, all the English related objects should be in a separate lists and all the biology-related objects should be another separate list. there can be many topics, and all the query should be retrun in a list and in that list, there should be multiple list of objects based on the topic. the output look like this: [ { 'english': [here will be all the biology related objecs in list], 'biology': [here will be all the biology related objects in list] } ] I hope you got problem. Can anyone help me in this case? -
Restricted group user to use a specific apps on Django
I have three apps in my Django's Portal. I like to allow the specific group users to use a specific apps. For Example: app1 --> group user 1 app2 --> group user 2 app3 --> all users So, group user 1 can use app1, but they can't use app2, and so on. How can I do this? Thanks! -
Accounts activation with Djoser and Django Rest Framework
Am using Djoser for authentication in my project. Have been struggling to add email activation for over 4 days now but seems have failed to grab it fine as the documentation is a little hard for me to understand. This is my code settings.py #change auth model to custom model AUTH_USER_MODEL = 'userauth.User' #setting up email server EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'okumujustine01@gmail.com' EMAIL_HOST_PASSWORD = 'codemanuzmaster' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'okumujustine01@gmail.com' #djoser login settings DJOSER = { 'DOMAIN': 'localhost:8000', 'SITE_NAME': 'net', 'LOGIN_FIELD':'email', 'USER_CREATE_PASSWORD_RETYPE':True, 'ACTIVATION_URL': '#/users/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS':{ 'user_create':'userauth.serializers.UserCreateSerializer', 'user':'userauth.serializers.UserCreateSerializer', 'activation': 'djoser.email.ActivationEmail', } } here is the email i receive after creating user http://example.com/auth/users/activate/MQ/5c9-26bcab9e85e8a967731d It shows example.com but i want it to change the web url to localhost:8000 instead You're receiving this email because you need to finish activation process on example.com. Please go to the following page to activate account: http://example.com/auth/users/activate/MQ/5c9-26bcab9e85e8a967731d And if i change the web url manually to http://127.0.0.1:8000/users/activate/MQ/5c9-26bcab9e85e8a967731d it keeps returning { "detail": "Authentication credentials were not provided." } I really request you people to help me. -
How can I add a button to download a file in django?
I'm making a file management website in django. I made some templates, and the ability to upload files to the django admin. Easy stuff. In one of my templates I want to add a button to download one of my uploaded files... I've tried many different stackoverflow questions, but nothing worked for me. This is my django admin page from where I want to download my file... This is my template: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static 'css/pages/fthpage.css' %}"> <title></title> </head> <body> <h1>FTH Page</h1> <button class="dwnldbtn"> <h1>FTH</h1> <p>Download<br>excel file</p> </button> </a> </body> </html> Any sort of suggestion is very muh appreciated!! Thanks in advance! -
Listing items by the category they belong to
I'm a complete Newb so please bear with me. I've never used OOP or a framework before. I'm creating a book keeping system where I want the ledgers to be displayed by the category they belong to. Here's my model and it seems to work: class COAGroup(models.Model): Name = models.CharField(max_length=200) def __str__(self): return self.Name class Ledger(models.Model): Name = models.CharField(max_length=200) COAGroup = models.ForeignKey(COAGroup, on_delete=models.CASCADE) def __str__(self): return self.Name I'm working on my first view which should list all the ledgers by the category they belong to. Eg <h2>Some COAGroup Name</h2> <ul> <li>A ledger that belongs to this group</li> <li>Another ledger that belonds to the group</li> <li>And another</li> </ul> <h2>Another COAGroup</h2> <ul> <li>A ledger that belongs to this second group</li> <li>Another ledger</li> </ul> I've written the following view in views.py: def showledgers(request): COAGroups = COAGroup.objects.all() Ledgers = Ledger.objects.all() context = { "COAGroups":COAGroups, "Ledgers":Ledgers, } return render(request,"ListLedgers.html",context) I've managed to get the ledgers to show in ListLedgers.html but I can't figure out how to get them to list by COA Group as per my example. Thank you! -
VS Code: ModuleNotFoundError when using debug
I develop a Django project I ma newbie in Django and VS Code so I "debug" using print() and console.log() which is not efficient... so I really need to be able to debug my code and follow variable value during execution but when I try to run debug I read the VS Code doc about django so I have set the launch.json like that: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python : Fichier actuel", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" } { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload" ], "django": true }, ] } I select Python: Django in the debug configuration list and run my project and have ModuleNotFoundError: No module named 'simple_history' and other... I don't understand because my project works so tierce app are correctly installed in my env It wonder if it could be link to another problem I have since I start using python/VS Code and was not able to fix (I already post on this problem: python can't load on … -
Wagtail: How to Use Directly Video Section and Add Custom fields
{% video self.header_video autoplay controls width=256 %} Through This We Get the Video in Our Page. if we have header_video field in Our Model. But What I want According To the Requirement of Project. I Don't Want To make the VideoChooserPanel Field in My Home Model and use that to upload videos from the Home Fields and Showed into the Page. Because this is not my project requirement. What I Want the Videos section which is available in the Wagtail SidePanel that Uploaded Videos Directly I Want To Access through the Page . I want to use that Directly in my Home Page and In Other Pages Also and a One or More Custom fields I want to add also on that . How Can I Do That . Any Help Will Be Appreciated -
Best practice to share data continuously for specific time period using websockets?
I'm using Django-channels, to send data to the frontend using a while-loop. Code: # This code only executes, after running the newly create command "python manage.py auto_update" While True: if <condition>: break async_to_sync(channel_layer.group_send)( group_name, { 'type': 'auto_update', # this is the name of my consumer method } This is working fine. I want to know, using a while loop to send data is a best practice or not? If not, please suggest the best practice for this scenario to deploy on production. Fetching data from pickle files(size: in KB's). -
.htaccess configuration for Django and Apache on a shared hosting server
I find quite difficult to set up Django on a shared LAMP hosting server. I've been trying to find .htaccess configuration but everything I've found is not clear and didn't work for me. I have manage.py in the root of the domain and then the main project folder with some .py files. I have no access to shell, no access to apache configuration. I have only .htaccess and ftp on my disposal. I know from the hosting provider that Python is available but they don't provide any information about specific configuration for Django. I would have thought that a few lines of code in .htaccess would make it possible. Or is it more complicated than this? Can somebody more experienced help? Thanks. -
How to edit migration file to be fake and not from command line in django
Now at my live DB, there's a table created by another service and will be updated from service_1 while service_2 is retrieving data from it only, I want on service_2 to implement the model representing this db_table but when not responsible for creating it on migration file I know there is /path/to/python manage.py migrate --fake and /path/to/python manage.py migrate --initial-fake but I want the fake migration occurs on the file itself, as per the documentation there's no option to make this at migrations.Migration My first solution was using raw sql which is not bad to me but I found it not readable for other developers, so I was thinking about this solution, Any ideas? -
How to connect Heroku app to my client network?
I have a Heroku app using Django (my first project). There is a button in the website which when clicked will try to send a GET request to a URL which exists within my Client network. I can't access that Client URL outside their Network, like I cannot access from my home Wifi (hope this is because of Firewall). So how do I establish this connection from outside my Client network? I would really appreciate a detailed answer! -
Can't send post request from JavaScript when CSRF_COOKIE_SECURE is enabled
API Endpoint: /api/items/ has authentication_classes = (SessionAuthentication, ) In my Vue.js code I have: getCookie: function (name) { match = document.cookie.match(new RegExp(name + '=([^;]+)')); if (match) return match[1]; return }, ... saveApiCall: function (data) { this.$http.post("/api/items/", data, { headers: { 'X-CSRFToken': this.getCookie('csrftoken') } }).then(function (response) { this.close(); }).catch(function (response) { this.form_errors = response.body; }); }, but it doesn't work when I set these settings: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True How to send this $http.post request when csrftoken is secure? -
django to serve same static file from different urls
I have a situation where a minified js script tries to include another js file with a hard coded relative path. More precisely : I'm rendering an html page with url pattern path('room/<int:room_id>/', room, name='room'), This page includes the first js lib with <script src="{% static 'js/firstlib.min.js' %}"></script> I have js/firstlib.min.js in my static files dir, thus Django serve http://localhost:8000/static/js/firstlib.min.js correctly. The problem is that firstlib.min.js tries to include tanks/lib/otherlib.js using hardcoded relative path, using http://localhost:8000/room/139/tanks/lib/otherlib.js A dirty hack would be to replace tank/* with /static/tank/* everywhere in firstlib.min.js. But I'wondering if there is a better way to solve this issue, for example by dynamically rewriting url : /room/<int:room_id>/<path>/somescript.js becoming /static/<path>/somescript.js (actually, the first script tries to include several other scripts the same way :-s) -
About converting custom functions in models into annotations in custom managers/querysets
Being new to Django, I'm starting to care a bit about performance of my web application. I'm trying to transform many of my custom functions / properties which were originally in my models to querysets within custom managers. in my model I have: class Shape(models.Model): @property def nb_color(self): return 1 if self.colors=='' else int(1+sum(self.colors.upper().count(x) for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) def __str__(self): return self.name + "-" + self.constraints @property def image_url(self): return format_html(f'{settings.SVG_DIR}/{self}.svg') @property def image_src(self): return format_html('<img src="{url}"|urlencode />'.format(url = self.image_url)) def image_display(self): return format_html(f'<a href="/static/SVG_shapes/{self}">{self.image_src}"</a>') But I'm not clear on a few points: 1/ is there any pros or cons declaring with the propriety decorator in a django model? 2/ what is the cost of calling a function/property in term of database calls and therefore, is there an added value to use custom managers / querysets and define annotations to simulate my functions at that level? 3/ how would you suggest me to transform my image & nb_color functions into annotations Thanks in advance