Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting Django environment variables for specific Pycharm project
I have multiple Django Pycharm projects, each with a different DATABASE_URL and DJANGO_SECRET_KEY Windows environment variable. Is there a way to set these variables specifically for individual projects so I can switch back and forth with ease? Also: in a way that makes them available in the terminal? I've read suggestions for setting them in the project's virtual environment or with the Run/Debug Configurations panel in Pycharm, but in neither case have I been able to get things to work. -
Django Rest Framework: one project, multiple apps, one server per app?
I've one project with 3 apps, using Django Rest Framework and would like to serve each app on a dedicated server, like so: api.app1.tld api.app2.tld api.app3.tld Reason: the apps are having a lot in common (models, ...), but are for different customers. I was thinking about passing an argument (not sure if possible), like so: python manage.py runserver --app=app1 python manage.py runserver --app=app2 python manage.py runserver --app=app3 Any idea? Thanks in advance! -
Update counter with max value from table with one query
I have certification_counter field that is 0 by default. I need to increment it by getting previous max value in table, but minimum value must be MIN_CERTIFICATION_COUNTER. I wrote query like that: last_value_qs = Project.objects.order_by("-certification_counter") Project.objects.filter(id=project.id).annotate( last_counter=Subquery( last_value_qs.values("certification_counter")[:1], output_field=IntegerField() ), max_counter=Greatest( F("last_counter"), MIN_CERTIFICATION_COUNTER ), ).update(certification_counter=F("max_counter") + 1) And I'm getting: django.db.utils.OperationalError: (1093, "You can't specify target table 'project' for update in FROM clause") I want to implement this as one transaction, to avoid race condition that's why I didn't use two queries like: max_value = Project.objects.order_by("-certification_counter").last().certification_counter Project.objects.filter(id=project.id).update(certification_counter=max(max_value, MIN_CERTIFICATION_COUNTER) + 1 ) -
When generating PDF from HTML in Django using PyQT5 the server crashes in a few times. Why?
When generating PDF from HTML in Django using PyQT5 the application manages to generate the file only a few times and after a while the server crashes. Why? I want to create a simple endpoint that recieves some parameters from front and from then, generate an PDF file. I've tried using pdfkit, weasyprint and PyPDF2, but i'm looking for something wihout extern dependencies like wkhtmltopdf. Here's my code: At first and second API call, the file returns from server as expected, but after that the django aplication simply exit. Can anyone say something about it? -
How to call variable from one method in another in Django?
I am trying to use only one View Class in Django with two methods post() and get(). Post is being used to get user session Token that I want to make available in "get()", so that I can identify the current user and send user details using the same view via Serializer. I want to use that token to get the name by user = Tokens.objects.get(key=token) to get the username and then filter User.objects.get(username=user) to post user data in the front end. How could I make "token" available inside def get() so I can work with it? Thank you! This is my View.py: class UserDetails(APIView): def post(self, request, *args): serializer = UserAccountTokenSendSerializer(data=request.data) if serializer.is_valid(): global token token = serializer.validated_data['token'] self.get(token) # user = Token.objects.get(key=token).user # global current_user # current_user = User.objects.get(username=user) # email = User.objects.get(email=user) # print(current_user, email) return Response(serializer.data) def get(self, request, *tokens): username = Token.objects.get(key=token).user email = User.objects.get(username=username).email serializer = UserAccount(username, email, many=True) return Response(serializer.data) These are my 2 serializers to post and get data: class UserAccountTokenSendSerializer(serializers.ModelSerializer): class Meta: model = UserAccountTokenSend fields = ( 'token', ) class UserAccount(serializers.ModelSerializer): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'username', ) This is my urls.py: path('get-user-tokens/', views.UserDetails.as_view()), … -
How to get data from database mongodb without models in django?
my problem is that my database is too large and I don't want to create any models since it's legacy one, and I will have to call different tables dynamically, so I just want to pull data from it. Is that possible in Django? -
How to deploy a django project github repo on GoDaddy cPanel?
I have a Django Project that I want to deploy on GoDaddy cPanel. and I have Github Repository of Project but I haven't deployed any dynamic website project on cPanel yet. can you please help and guide me to how can I upload and connect my github repo to cPanel and, Do I need to install python and django first on panel so can you please guide me for how can I run the django project on server. Thank You! -
Django: Sending data from backend to frontend without page refresh
I am developing a Website with django. Now, let's say I have a database where values can change at any time. Every time the DB changes, I want to execute a function (no problem with that) and update some data I passed to a template without a page refresh. At first, I thought about AJAX, but as it seems an AJAX-Request must be started from the frontend, right? Long story short: What I want specifically is to update some CSS depending on some data changes in the backend without any page refresh. Hope someone can help me 😁 -
Django How to check if Boolean out of ModelField is True
So I have this code in my views.py @login_required(login_url='home:login') def profile_view(request): packetfree = Account.objects.get(packet_free=request.user) packetpremium = Account.objects.get(packet_premium=request.user) packetbusiness = Account.objects.get(packet_business=request.user) if packetfree is True: abo = "Free" elif packetpremium is True: abo = "Premium" elif packetbusiness is True: abo = "Business" context= { 'person': request.user, 'abo': abo } return render(request, 'home/profile.html') And I want to check if the Value of the boolean from the model is true so I can find out which of the 3 booleans is true and know which subscription the user has as a Char to use it in my html template. -
Which is most expensive query in django among these?
I have 5 models which needs to be populated using a key from 6th model: I have two options, please suggest the most effective Option1: I can fetch all the five one by one and send via context to template and then show the each via html tabs Option2: Have seprate page for each model and fetch when ever user goes to that page, like if user goes to page1 then i fetch data from model1 and so on Which is good and effective ? Like querying only needed or just query all and show up in a html tabs ? -
Attempt to write a readonly database Django/Apache2/OperationalError
I am working on a Django app and have deployed it to a Ubuntu Server via AWS. Everything that doesn't require a database insert works fine. But when I try to log in (everytime if someone logs in I am saving the 'last login') an OperationalError appears: Attempt to write a readonly. I already changed the owner of the database and tried also with chmod 666 and chmod 777 but it still doesn't work. Did someone had the same issue and has solved it? Kind regards -
Django commit database changes later on command
I am building an eCommerce website that uses some form of verification as soon as a user upload/edits a product, once the product is updated the database property of the Product model isApproved is set to False, and if it's set to false the product won't show on the site because I set only approved products to be viewed. so how can I make it that when a user edits a product I can see the changes before committing it to the database? so that the previous version of the product is still live? -
deploy django app to heroku -push failed! , App not compatible with buildpack
$ git push heroku master Enumerating objects: 220, done. Counting objects: 100% (220/220), done. Delta compression using up to 4 threads Compressing objects: 100% (217/217), done. Writing objects: 100% (220/220), 1.20 MiB | 270.00 KiB/s, done. Total 220 (delta 62), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack- registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shivay-ksk. remote: To https://git.heroku.com/shivay-ksk.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/shivay-ksk.git' -
pipenv creating Pipfile & Pipfile.lock in one-up directory
I am trying to install Django using pipenv. The command used is pipenv install django~=3.1.0 The command is issued in django folder. The command creates files PipFile and Pipfile.lock in Desktop folder instead of Desktop/django folder. How to create PipFile and Pipfile.lock in django folder instead of Desktop folder? Operating system is Windows 10 and python in 3.7. -
Trying to deploy django app to AWS EC2 instance using Gunicorn and Nginx
I'm trying to deploy a django app on AWS EC2 and also using gunicorn and Nginx in the process, I followed this tutorial link. I'm not sure what is going wrong, this is the first time I've used AWS EC2, when I try to launch the IP address of the instance it comes back as: "can't open page because safari can't establish secure connection to the server" in my aws console the EC2 'instance state' shows it's running it has been setup in ubuntu 18.04 , I've also set up security groups in my EC2 instance with http, https, 443, 80, 8000, 5432 and 22 all allowed from any ip address except the 22 which only has my ip address as access. Also in my django app settings 'ALLOWED_HOSTS' , i've added the instance ip address and also '*'. this is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=djangoadmin Group=www-data WorkingDirectory=/home/ubuntu/djangoapp1 / ExecStart=/home/djangoadmin/pyapps/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ djangoapp1.wsgi:application [Install] WantedBy=multi-user.target ngnix conf file : server { listen 80; listen 443; server_name **.***.***.*; location = /favicon.ico { access_log off; log_not_found off; … -
How to properly configure the url for a django/ajax call
This is a vastly simplified version of my app. I am having problems with the url of the ajax call when the home page is reloaded after selecting a colour: the url becomes pages/use-selection/pages/print-time/ instead of pages/print-time/ Can someone please point out the solution? home.html {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <h1>{% block title %}Home{% endblock title %}</h1> You have selected: {{ colour }} <p><a href="{% url 'select' %}">Select colour</a></p> <script> document.addEventListener("DOMContentLoaded", (event) => { var colourButtons = document.getElementsByName('colour'); colourButtons.forEach((radioButton) => { radioButton.addEventListener('click', () => { useSelectedUrl(radioButton.value) }); }) $.ajax( { type: "GET", url: "pages/print-time/", cache: false, success: function (context) { } } ); }); function useSelectedUrl(colour) { var href = '/use-selection/colour_text'.replace('colour_text', colour); var return_link = document.getElementById('select'); return_link.href = href; } </script> {% endblock content %} select.html {% block content %} <h1>{% block title %}Select colour{% endblock title %}</h1> <p><input type="radio" name="colour" value="red" checked/>Red</p> <p><input type="radio" name="colour" value="blue" checked/>Blue</p> <p><a id="select" href="{% url 'use-selection' colour='blue' %}">Use selection<a></a></p> <script> document.addEventListener("DOMContentLoaded", (event) => { var colourButtons = document.getElementsByName('colour'); colourButtons.forEach((radioButton) => { radioButton.addEventListener('click', () => { useSelectedUrl(radioButton.value) }); }) }); function useSelectedUrl(colour) { var href = '/use-selection/colour_text'.replace('colour_text', colour); var return_link = document.getElementById('select'); return_link.href = href; } </script> {% endblock content %} urls.py # … -
How to create a function to send emails formatting html message with a variable list?
I am trying to create a function in django to send my HTML email templates with certain variables. Here's what I have so far: from django.core.mail import send_mail from django.template.loader import render_to_string from django.core.mail import get_connection from django.utils.html import strip_tags from otr import settings def send_email(subject, email_template, recipient, username, password, variable_list): html_message = render_to_string(email_template, {'context': 'values'}) for variable in variable_list: html_message.format(variable) plain_message = strip_tags(html_message) recipient = recipient with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=username, password=password, use_tls=True ) as connection: send_mail(subject, plain_message, 'Me', [recipient], fail_silently=False, html_message=html_message, connection=connection) Then I want to call this function to be used in different django views like: subject = "My subject" email_template = "emails/followup_email.html" recipient = queryset.customer_email username = username_variable password = password_variable customer_name = "Bob" dear_user = "my_name" phone_number = "1111111111" sincerely_user = "my_name" variable_list = [customer_name, dear_user, phone_number, sincerely_user] send_email(subject, email_template, recipient, username, password, variable_list) I keep getting "Replacement index 1 out of range for positional args tuple", so I am guessing I can't do a for loop in this way to format the HTML email with a list of variables. Does anyone know how to accomplish this a different way? -
django appuser give duplicate key error while creating new superuser
im getting this error while creating new superuser Heres the error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_auth_appuser_phone_key" DETAIL: Key (phone)=() already exists. I know it is checking for unique phone number while also considering empty phone value and hence giving this error. my question is how to resolve this Models.py: class AppUser(AbstractUser): user_type = models.PositiveSmallIntegerField(default=1) class Gender(models.IntegerChoices): Male = 1, 'MALE' Female = 2, 'FEMALE' Other = 3, 'OTHER' email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=15, unique=True) gender = models.PositiveSmallIntegerField(choices=Gender.choices, null=True, blank=True) dob = models.DateField(null=True, blank=True) doa = models.DateField(null=True, blank=True) @property def info(self): from user_auth.serializers import UserSerializer return UserSerializer(self).data @property def token(self): return RefreshToken.for_user(self) -
Django error on connecting to Postgres, unsupported startup parameter: options
On migrate step I get such error django.db.utils.OperationalError: ERROR: unsupported startup parameter: options settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=public' }, 'NAME': env.str('DB_NAME'), 'USER': env.str('DB_USER'), 'PASSWORD': env.str('DB_PASS'), 'HOST': env.str('DB_HOST'), 'PORT': env.str('DB_PORT'), 'DISABLE_SERVER_SIDE_CURSORS': True, } } (in options parameter I tried to set default schema to public) -
How to sum variable in a django model
In this example i have the following model in django: class Test(models.Model): name = models.models.ForeignKey('auth.user') amount = models.IntegerField() in this example i have 4 instances: test1 = Test("John",10) test2 = Test("John",20) test3 = Test("Eric, 30) test4 = Test("Eric, 40) what i want is to get a list of tuple, with the user and the total sum of amount. testlist = (("john", 30), ("Eric", 70)) i tried the aggregate method but then i get the total amount of all the instances -
is there an open source to manage workflow of a company with data and userss
Is there an open source platform based on Django to manage data, workflow and users. if there is please mention their name or github link. -
how to send values from nodeMCU to django website
I'm working on nodeMCU with soil moisture sensor and want to show on my django website. I'm very close to it but when i send data from nodeMCU to django server i see http 200 request from both side (from nodeMCU side and dajngo side). But main problem is i can't show real time values to my dajngo webpage. Anyone have knowledge about this, kinldy please share, maybe it will be very helpful for me. Project urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('SIS_APP.urls')), #1.nodeMCU hit data on this url path('update', include('SIS_APP.urls')), ] App urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), #2.nodeMCU hit data on this url path('update', views.update, name='update'), ] views.py from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. def index(request): return render (request, 'index.html') #this function call when nodeMCU hit this url @csrf_exempt def update(request): value = request.POST.get("httpResponseCode") #this value show "None" on webpage return HttpResponse (value) Nodemcu.ino #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> const char* ssid = "****"; const char* password = "*****"; // Domain Name … -
I want to integrate the payment gateway of paytm in a small modal iframe in my project
I'm in a planning phase so i just wanted to see if all the thing that I was thinking can be achieved or not it's just theoretical question and just want your advice on it The thing that I want is that a person should click on a link and a small modal on right side should pop up as shown in the below image Once that is done now i want it to have the payment gateway appear only inside that modal and not in the full view I'm going to start building this project for learning so any help or guidance will be great If possible please add the references as well on how this can be achieved -
ModuleNotFoundError only occurs when starting app in Docker
I am currently experimenting with cookiecutters. I'm creating a template for Django, which is working. The next step is to add a docker container for it. For some reason i get following error when I run docker-compose up (or just start the django app manually from within the container): app_1 | Exception in thread django-main-thread: app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner app_1 | self.run() app_1 | File "/usr/local/lib/python3.8/threading.py", line 870, in run app_1 | self._target(*self._args, **self._kwargs) app_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper app_1 | fn(*args, **kwargs) app_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run app_1 | autoreload.raise_last_exception() app_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception app_1 | raise _exception[1] app_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute app_1 | autoreload.check_errors(django.setup)() app_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper app_1 | fn(*args, **kwargs) app_1 | File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup app_1 | apps.populate(settings.INSTALLED_APPS) app_1 | File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_1 | app_config = AppConfig.create(entry) app_1 | File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 90, in create app_1 | module = import_module(entry) app_1 | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module app_1 | return _bootstrap._gcd_import(name[level:], package, level) app_1 | File "<frozen importlib._bootstrap>", line … -
Django displays incorrect template
I'm working on an website where user (if logged in) can perform a calculation and see all of his calculations listed. My website has two groups: Clients and Administrators where Clients are not allowed to see any other members' calculations except their own while Administrators are. Authentication is based on Django's built in User class and for each group I created separate views and templates. Templates have similar behavior but different displaying messages. When Clients want to see their calculations, correct information is displayed but the template rendered is for Administrators rather than for Clients. views.py #Administrators' view function class CalculationListView(generic.ListView): model = Calculation paginate_by = 10 #Users' view function class CalculationsByUserListView(LoginRequiredMixin, generic.ListView): model = Calculation paginate_by = 10 def get_queryset(self): return Calculation.objects.filter(userid=self.request.user) urls.py urlpatterns = [ path('', views.index, name='index'), path('calculations/', views.CalculationListView.as_view(), name='calculations'), path('calculation/<int:pk>', views.CalculationDetailView.as_view(), name='calculation-detail'), ] urlpatterns += [ path('mycalculation/', views.CalculationsByUserListView.as_view(), name='mycalcs'), ] Template names Administrators: calculation_list.html Clients: calculations_user.html test.py def test_calculations_in_list(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('mycalcs')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Check that initially we don't have any calculations in list self.assertTrue('calculation_list' in response.context) self.assertEqual(len(response.context['calculation_list']), 0) # Now assign some calculations …