Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multi language
I want my Django site to be available in both English and Azerbaijani languages. This is how I wrote the codes for it. However, I do not know what is true. Is there an alternative? Does this method affect the speed of the site? in my view : def change_Lang(request): referer = request.META.get('HTTP_REFERER') lang = request.GET.get("pylang", "en") pylang = request.session.get("pylang", None) if lang != "az" and lang != "en": lang = "en" if pylang == None: request.session["pylang"] = lang if pylang != lang: request.session["pylang"] = lang if referer: return HttpResponseRedirect(referer) return redirect("home") in my templatetag: @register.simple_tag def pylang(value, en, az): if value == "en": return en elif value == "az": return az else: return en in my template : {% load pylang %} {% pylang request.session.pylang "About - PyTerminator.com" "Haqqımızda - PyTerminator.com" %} I want to know if this method has a negative effect on the speed of the site? What is the alternative? Suggest better options. Thanks in advance) -
Django renaming log level to 3 character format
In python, using logging module, the log level format can be changed with: logging.addLevelName(logging.DEBUG, 'DBG') How can I do it in Django? My (working) logging configuration in settings.py: LOGGING: dict[Any, Any] = { 'version': 1, 'formatters': { 'app_log_format': { 'format': '%(asctime)s [%(levelname)s] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': current_log_path, 'formatter': 'app_log_format', }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } Thanks -
How To Order Alphanumeric CharFields in Django
i have a model for menu items that has a CharField for the numbers as some of them have sub variants that have a letter suffix fx. 25, 26, 27, 27a, 28... how do i order the objects after the menu number with the suffix taken into account after? so this list [1g, 14, 2g, 27a, 27, 33, 33b] would be [1g, 2g, 14, 27, 27a, 33, 33b] when just using order_by it defaults to the first number so [27, 4 0, 27a] comes out as [0, (2)7, (2)7a, 4] -
Django exception, NoReverseMatch
I'm learning django on a small project called BlogPost from a python's book. This is a very simple project on its own - user can add a post with title and text. I'm trying to add functionality of editting existed entries via views.py function called "edit_entry" and i receive exception which i can't overcome: NoReverseMatch at /edit_entry/6/ Request URL: http://127.0.0.1:8000/edit_entry/6/ Raised during: blogs.views.edit_entry Reverse for 'edit_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_entry/(?P<object_id>[0-9]+)/\Z'] Does anybody know what could be a proble? Here is my code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): """Create data model""" topic = models.CharField(max_length=100) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_added'] def __str__(self): return self.topic forms.py from django.forms import ModelForm from .models import BlogPost class NewEntryForm(ModelForm): class Meta(): model = BlogPost fields = ['topic','text'] labels = {'topic':'Topic', 'text': 'Text'} urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('', views.index, name='index'), path('entries/', views.entries, name='entries'), path('new_entry/', views.new_entry, name='new_entry'), path('edit_entry/<int:object_id>/', views.edit_entry, name='edit_entry')] views.py from django.shortcuts import render, redirect from django.http import request from .models import BlogPost from .forms import NewEntryForm # Create your views here. def index(request): … -
Navigating through apps in django
After spending one full day trying to fix this problem, I finally ask here. Sorry if this is obvious to the Django purists! I have this project with (currently) 2 apps, called intro and rules. The intro app contains a button that should redirect to rules. Currently, for some reason that I cannot understand, clicking the button redirects to the intro page itself. Does someone see the mistake here? Following are the relevant code parts: HTML template for the button: <div class="button-container" action="{% url 'rules:index' %}"> <form class = "Demo_questionnaire""> {% csrf_token %} <button type="submit">New game</button> </form> </div> Project settings: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'intro', 'rules', ] URL configuration for the project: urlpatterns = [ path("admin/", admin.site.urls), path("intro/", include("intro.urls", namespace="intro")), path("rules/", include("rules.urls", namespace="rules")), ] URL configuration for intro: app_name = "intro" urlpatterns = [ path("", views.index, name="index"), ] URL configuration for rules: app_name = "rules" urlpatterns = [ path("", views.index, name="index"), ] Thank you in advance, and sorry if the answer is obvious :( -
Django: using two related fields / foreign keys at once
I have three models: class Team(models.Model): team_id = models.AutoField() team_name = models.CharField() class Game(models.Model): game_id = models.AutoField() home_team = models.ForeignKey(Team, on_delete=models.CASCADE) away_team = models.ForeignKey(Team, on_delete=models.CASCADE) class TeamBoxScore(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='game_boxscore') team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team_boxscore') # some stats here What I want to do is, for every Game instance, access the TeamBoxScore that matches both the Game instance and the Team instance referenced by home_team/away_team. Is there a way that I can have game.home_team.team_boxscore reference only the boxscore for that game_id? Or, conversely, can I specify which game.game_boxscore I want to return (the one that matches home_team or the one that matches away_team)? I want to minimize queries and avoid long iterative solutions. I've tried annotating the fields from each TeamBoxScore instance to every Game (referencing the game_boxscore related field), but that ends up doubling the size of the queryset and placing the values from the home boxscore and the away boxscore in separate instances. I've tried going through the team_boxscore related field, but that returns every boxscore for that team (game.home_team.team_boxscore). I've further tried to groupby these annotated values and just return the sum, but this is both inelegant and takes too long (and could be wrong!) … -
Django believes that there is a "SuspiciousFileOperation". This is not true
Django has a belief that there is a SuspiciousFileOperation error when this just is not the case. My fully reproducible setup is below. It continues to return this error despite the fact that: I have installed and set up Whitenoise correctly, as well as in the Middleware and InstalledApps, in the settings.py filw, as well as the following: INSTALLED_APPS = [ 'django.contrib.staticfiles', ] MIDDLEWARE = [ "whitenoise.middleware.WhiteNoiseMiddleware", ] STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_URL = 'static' STATICFILES_DIRS = [ BASE_DIR / "static" ] Despite the fact that I have correctly set up the static config in my root urls.py folder, as follows: from django.conf import settings from django.conf.urls.static import static from django.views.static import serve urlpatterns = [ ...... ] # Only for development. Do not use this in production. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My directory is as follows: <PROJECTNAME> <ROOTFOLDER> settings.py urls.py <APP NAME> static file.css static libraries css image-video-hero.css staticfiles libraries css image-video-hero.css Therefore, there is no reason as to why Django should have an issue with this, however, when I run the command of python manage.py collectstatic command, I still get the trace back of: File "<FILEPATH>\<PROJECTNAME>\.venv\Lib\site-packages\django\utils\_os.py", line 31, in safe_join raise … -
Django, exists subquery always returns False
I faced an issue, that my subquery returns False, even it should return True. from wagtail.models import WorkflowState, Page, Workflow import pytest def test_filter_pages(user): page = PageFactory.create( owner=user, live=False, latest_revision_created_at=timezone.now(), ) WorkflowState.objects.create( content_type=ContentType.objects.get_for_model(Article), base_content_type=ContentType.objects.get_for_model(Page), object_id=str(page.pk), workflow=Workflow.objects.get(name="Moderators approval"), status=WorkflowState.STATUS_IN_PROGRESS, requested_by=user, ) workflow_states = WorkflowState.objects.filter( status=WorkflowState.STATUS_IN_PROGRESS, object_id=str(OuterRef("pk")) ) queryset = ( Page.objects.select_related("owner", "latest_revision") .annotate(workflow_state_status=Exists(workflow_states)) .filter(owner=user) ) lists_ids = [ page.id for page in queryset if page.workflow_state_status ] assert lists_ids != 0 In this test there is only one page, which should have workflow state. But test fails with list_ids = 0. What is wrong here? Moreover, when I try to replace workflow_state_status with simple WorkflowState.objects.filter( object_id=self.pk, status=WorkflowState.STATUS_IN_PROGRESS, ).exists() everything works correct (except database queries) -
Django stopped updating static files
Django does not upload static files Hey guys, I am head to you because I have a problem I can’t fix. I am on localhost and Django does not apply modifications I have made on static files, although the file is changed. So to start here what I have done so far: clearing browsers caches rebooting the server step 1&2 of best answer: stackoverflow.com/questions/27911070/django-wont-refresh-staticfiles changing browser deleting pycache files Nothing seems to work, if you had an explanation on how to fix this but mostly WHY this happens, would be so nice ! 😊 -
DJANGO Compute number of hours the user spend per day
I have Clocking table in database. I wanted to count the users' time spend per day. For example 2024-03-21, user 1 spend 6.8 hours, the next day he spend n number of hours and so on (['6.8', 'n', ... 'n']) user date timein timeout 1 2024-03-21 10:42 AM 12:00 PM 1 2024-03-21 01:10 PM 06:00 PM 1 2024-03-22 01:00 PM 05:47 PM ... ... ... ... This is my models.py class EntryMonitoring(models.Model): user = models.ForeignKey('User', models.DO_NOTHING) timein = models.CharField(max_length=15, blank=True, null=True) timeout = models.CharField(max_length=15, blank=True, null=True) date = models.DateField(null=False) I wanted to get the list of hours spend per day, that would be really useful for me in plotting charts. Thank you in advance! -
How to restart gunicorn when used with config file
I am using gunicorn to server a django application. I am using a config file and starting gunicorn using the command gunicorn -c config/gunicorn/dev.py I want to know how to restart gunicorn. i am not able to use sudo systemctl restart gunicorn command which gives the below message: Failed to restart gunicorn.service: Unit gunicorn.service not found. I am very sure that gunicorn is running as i am able to use the application on the web. What is the way to restart gunicorn in this case. Below is the config file of gunicorn: # Django WSGI application path in pattern MODULE_NAME:VARIABLE_NAME wsgi_app = "someapp.wsgi:application" # The granularity of Error log outputs loglevel = "debug" # The number of worker processes for handling requests workers = 2 # The socket to bind bind = "0.0.0.0:8000" # Restart workers when code changes (development only!) reload = True # Write access and error info to /var/log accesslog = errorlog = "/var/log/gunicorn/dev.log" # Redirect stdout/stderr to log file capture_output = True # PID file so you can easily fetch process ID pidfile = "/var/run/gunicorn/dev.pid" # Daemonize the Gunicorn process (detach & enter background) daemon = True -
Python code to connect to FTP /convert my code in way that it uses FTP instead of SFTP
please help to write code to connect ftp using python download fresh files from specfic directory load those file in Mysql database ,mark them processed after downloading file from ftp ,after loading them into mysql database If any one can provide python script for this -
What are the key technologies and concepts involved in backend web development? [closed]
Key Technologies: Programming Languages: Backend development can be done using various languages, such as: Node.js: JavaScript runtime built on Chrome's V8 engine, popular for its non-blocking, event-driven architecture. Python: Known for its simplicity and readability, often used with frameworks like Django and Flask. Java: Offers platform independence and is commonly used in enterprise applications. Frameworks: Frameworks provide a structured way to build web applications. Some popular backend frameworks include: Express.js (Node.js): Minimalistic and flexible, ideal for building APIs and web apps. Django (Python): High-level framework for rapid development, follows the DRY (Don't Repeat Yourself) principle. Spring (Java): Comprehensive framework for Java, offering features like dependency injection and MVC architecture. Databases: Backend development involves interacting with databases to store and retrieve data. Common databases include: SQL Databases: Such as MySQL, PostgreSQL, and SQLite, used for structured data. NoSQL Databases: Such as MongoDB and Cassandra, used for unstructured or semi-structured data. Key Concepts: RESTful APIs: Representational State Transfer (REST) is a design pattern for creating scalable web services, commonly used in backend development. Authentication and Authorization: Implementing secure user authentication and authorization mechanisms to protect backend resources. Server-Side Rendering (SSR) vs. Client-Side Rendering (CSR): Understanding the difference between rendering techniques and when … -
Is it possible to add a "InputField" in ChoiceField in Django?
I'm in the process of developing a form that aligns with a database model. One of the fields in this form requires users to select from a range of options. Initially, I implemented this using Django's ChoiceField. However, I'm exploring the possibility of allowing users to input their own option if it's not available in the predefined choices. Is there a way to integrate this? -
Django htmx not targeting assigned element
I have a django-tables2 template that I've modified to assign a unique row id to each row. I'm trying to add a button that will allow a user to delete a given row on a click. I'm using htmx to initiate the deletion request. I also have an htmx enabled edit button that is working as intended regarding sever side modifications and updating the DOM. The delete button behaviour is as expected on the server side, but the swap appears to impact only the button, and not the tag. After clicking the delete button, the record is removed from the database, but only the button disappears on the DOM, not the <tr>. I won't include the views.py as it's fairly straightforward in that it retrieves the appropriate record, executes the delete, and returns an empty HTTPResponse. I've tried adding an hx-target with an hx-swap, but this deactivates any htmx call capability on the button. I've also tried putting a <div> wrapper around the <tr> and targeted that with my oob swap with no luck. Here is the table.tbody template with both the edit and the delete buttons: {% extends 'tablestyle.html' %} {% load humanize %} {% block table.tbody %} <tbody … -
django model save operation not creating on default database
I have two databases defined: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_offshore_bkup' }, 'onshore_db': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_onshore_bkup' } In the model: def save(self, *args, **kwargs): kwargs['using'] = 'default' super().save(*args, **kwargs) NoTice I've commented these #kwargs['using'] = 'onshore_db' #super().save(*args, **kwargs) In the viewset: with transaction.atomic(): self.serializer_class = self.create_serializer_class created_user = viewsets.ModelViewSet.create(self, request, *args, **kwargs) created_user_id = created_user.data['id'] The create() only saves the record in onshore_db immediately and doesn't consider the default db. Even after commenting the onshore_db configuration, when I run the app, I find that the new model objects are created in onshore_db only and no records in default db. What could be the reason? There's also a db-router defined: def get_db_name(): cache_data = {} db = 'default' request = get_current_request() try: user_id = request.session._session_cache['_auth_user_id'] cache_data = cache.get(user_id, {}) except Exception as e: return db if cache_data.get('CLIENT_DB_NAME', None): db = cache_data.get('CLIENT_DB_NAME') return db class MatrixDBRouter: # TODO encrypt db name where data from onshore def db_for_read(self, model, **hints): return get_db_name() def db_for_write(self, model, **hints): return get_db_name() def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True But this only returns the default … -
How do we update pip to it's latest version
A new release of pip is available: 23.2.1 -> 24.0 [notice] To update, run: python.exe -m pip install --upgrade pip By running provided command i am unable to update pip to it's latest version. it's showing the following error upon running the command " python.exe -m pip install --upgrade pip" ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Python311\Lib\site-packages\pip\init.py' Consider using the --user option or check the permissions. please help to solve the above mentioned problem -
The same uuid is generated for different objects in Django
When I run server on localhost I am able to add new objects in my postgre database through Django admin panel, but only one for every table. When I try to add second new object, it assigns the same uuid that has already been used. There is an example of model with uuid as primary key: models.py from django.db import models from authuser.models import User from django.utils import timezone import uuid class Thread(models.Model): idthread = models.UUIDField(default=uuid.uuid4(), primary_key=True, unique=True) date_created = models.DateTimeField(default=timezone.now) userid = models.ForeignKey(User, on_delete=models.DO_NOTHING) name = models.CharField() def __str__(self): return self.name Only after restarting the server it will assign new unique uuid to object that I would like to add. -
How to implement dual authentication (email and phone number) in Django Rest Framework?
I'm building a Django Rest Framework (DRF) application and I need to implement dual authentication, allowing users to sign in using either their email or mobile number. What is the best approach to implement this? I've already set up the authentication system using email, but now I need to extend it to support mobile number authentication as well. Should I create a custom authentication backend, or is there a DRF package that can help me achieve this more easily? I'd appreciate any advice or examples on how to implement dual authentication in DRF. Thank you! -
ModuleNotFoundError: No module named 'psycopg2' while makemigrations on postgres DB
I cloned a github project on Django and i was following the instructions to execute the program. I am new so, i went ahead and downloaded postgres and installed it. at the make migrations step, this error was logged along with bunch of paths :- ModuleNotFoundError: No module named 'psycopg2' i was following the steps given in the documentation file for this which are as follows : " Installing the Postgres and enabling it in the background We will go to telusko\settings.py in the project folder Around line 78, there's DATABASES dictionary, we will set the value for keys ('NAME', 'USER' & 'PASSWORD') to 'postgres' Then we'll execute python3 manage.py makemigrations & python3 manage.py migrate Finally, we will run the project by python3 manage.py runserver " i followed the steps, at the 3rd step, instead of 'postgre' as the password, i typed in the password asked at the installation process BUT at the 4th step when i run the python3 manage.py makemigrations this error is shown: ModuleNotFoundError: No module named 'psycopg2' i want this project somehow working till tomorrow so please help -
How to Submit Separate Actions from a Single Form Tag? (Django)
I have written the following code where a submit action with the value {{category.name}} unexpectedly triggers the "create" button in form_category, resulting in a "Please enter a name" message. This approach worked fine in a previous project using the same logic. I've confirmed that the urls.py is properly set up. What could be the issue? <form method="POST"> {% csrf_token %} category name: {{ form_category }} <input type="submit" value="create" formaction="{% url 'mk_category' %}"> <span> | </span> {% for category in categories %} <input type="submit" value="{{category.name}}" formaction="{% url 'index_with_category' category.id %}"> {% endfor %} </form> Thank you very much for your help! Wrapping each submit button in separate form tags resolves the issue. However, I plan to continue using multiple submit buttons within a single form in the future. I have checked urls.py multiple times and found no issues. Please help me with this. -
Django Python - How to Query this
I have this Consumer model class ConsumerModel(models.Model): GENDER_LIST = ( ('male','MALE'), ('female','FEMALE'), ("lgbt",'LGBT') ) REGISTER_AS = ( ('consumer','CONSUMER'), ('manager','MANAGER') ) uid = models.CharField(max_length=8) # remove the default value some time profile_id = models.UUIDField() user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=40) birthdate = models.DateField(null=True,blank=True) mobile_number = models.CharField(max_length=12, null=True, blank=True) gender = models.CharField(max_length=20,choices=GENDER_LIST,null=True,blank=True) profile_image = models.ImageField(null=True,blank=True,upload_to="images/") register_as = models.CharField(null=True, blank=False,choices=REGISTER_AS, max_length=12) def __str__(self): return self.user I have this view where I want to look/print for the Consumer with the following user but it returns and error: serializer = ConsumerLoginSerializer(data=request_data) if serializer.is_valid: try: user = User.objects.get(email=request_data["email"]) except: return Response(data={'status': wrong_input, 'message':wrong_body_vals_msg, 'errors':{"Email":"User not found"}}) print("PROFILE ID: " + ConsumerModel.objects.get(user=user)) return Response(data={"status": ok, 'message': "Success"}, status=ok) -
Embedded react component disable select text on other html elements
I am trying to include a react component in a django template which contains non-react content. My template contains the following code: {% load static %} <!DOCTYPE html> <html> <body> <h1>This text CAN NOT be selected</h1> <h2>React app</h2> <div id="react1"></div> <!-- this is the component that the react component will live in. --> <script src="{% static js %}" defer></script> <!-- js is a variable pointing to the main.XXXXX.js file. --> </body> </html> The variable js refers to the build/static/js/main.XXXXX.js-file build using npm run build and served using django. The index.js file (in react) simply add a component to the div: import React from 'react'; import { createRoot } from 'react-dom/client'; import App2 from './App2'; if(document.getElementById("react1") != null){ const root = createRoot(document.getElementById('react1')); root.render( <App2 /> ); } The component (App2.js) is a very simple hello-world example. The page renders correctly (the app is a simple counter app) as shown in the screenshot so all files are up-to-date. As can be seen I can select/interact with the application, but I cannot select the text defined in the tag (and more importantly, events such as button clicks outside of react are not triggered etc.). The React counter-app works as expected. I have googled … -
Cannot index models from Django to Elasticsearch
I have a Django project where we're going to use Elasticsearch for a full-text search. I have a task to connect it with the existing Django project. The first thing I found django-elasticsearch-dsl package. I did everything like in tutorial and all worked fine, but the idea was in using elasticsearch-dsl. I don't understand how to create indexes right now. If in django-elasticsearch-dsl the only thing I need is to run python3 manage.py search_index --rebuild inside Django container, but here I have no idea. I store all code in documents.py. documents.py from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Document, Text connections.create_connection(hosts=['http://elasticsearch:9200']) class FilmWorkDocument(Document): title = Text() description = Text() class Index: name = 'film' FilmWorkDocument.init() first = FilmWorkDocument(title='Example1', description='Example description') first.meta.id = 47 first.save() docker-compose.yml elasticsearch: image: elasticsearch:8.13.0 container_name: elasticsearch environment: - "ES_JAVA_OPTS=-Xms200m -Xmx200m" - discovery.type=single-node - xpack.security.enabled=false ports: - 9200:9200 Sending a request http://localhost:9200 shows that everything is ok. { "name" : "eeb958274241", "cluster_name" : "docker-cluster", "cluster_uuid" : "wUQjIKoLTNGKtFH7A1tzSw", "version" : { "number" : "8.13.0", "build_flavor" : "default", "build_type" : "docker", "build_hash" : "09df99393193b2c53d92899662a8b8b3c55b45cd", "build_date" : "2024-03-22T03:35:46.757803203Z", "build_snapshot" : false, "lucene_version" : "9.10.0", "minimum_wire_compatibility_version" : "7.17.0", "minimum_index_compatibility_version" : "7.0.0" }, "tagline" : "You Know, for Search" } But after … -
Django works perfectly on a local machine, but doesn't work in production
Django works perfectly on a local machine, but has errors with Postgres in production (I am using the same postgres DB in prod and locally). Django server hosted on Railway gives me this: Settings (WORKS PERFECTLY ON A LOCAL MACHINE WITH THIS IN-PROD DATABASE AND SAVES DATA): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } DATABASE_URL = os.getenv('DATABASE_URL') .env: DATABASE_PRIVATE_URL={{DATABASE_PRIVATE_URL}} DATABASE_URL={{DATABASE_URL}} DB_HOST=viaduct.proxy.rlwy.net DB_NAME=railway DB_PASSWORD={{DB_PASSWORD}} DB_PORT=19232 DB_USER=postgres SECRET_KEY={{SECRET_KEY}} Proof for local server working: Postgres server logs (local machine):