Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ckeditor is not good for django anymore
before ckeditor worked for django but now it is not working and expired. django by itself suggest non-free ckeditor 4 LTS or ckeditor 5 but I don't know how to use it please if there is give me another editor for django or guide me for this ckeditor. -
django-dbbackup: server and pg_dump version mismatch
I faced on this error. who can help me? command: python manage.py dbbackup error: Traceback (most recent call last): File "/passchain/manage.py", line 22, in <module> main() File "/passchain/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/dbbackup/utils.py", line 120, in wrapper func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/dbbackup/management/commands/dbbackup.py", line 93, in handle self._save_new_backup(database) File "/usr/local/lib/python3.10/site-packages/dbbackup/management/commands/dbbackup.py", line 106, in _save_new_backup outputfile = self.connector.create_dump() File "/usr/local/lib/python3.10/site-packages/dbbackup/db/base.py", line 92, in create_dump return self._create_dump() File "/usr/local/lib/python3.10/site-packages/dbbackup/db/postgresql.py", line 112, in _create_dump stdout, stderr = self.run_command(cmd, env=self.dump_env) File "/usr/local/lib/python3.10/site-packages/dbbackup/db/base.py", line 171, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump --dbname=postgresql://root:%251fiY%263%40%21%4073%2A6%25ZJ6dT%40%40%253703%2A%5E%2A3%26%254oW046%264%25%250%24%40fexO%2AY%40CRhFy8%2A%240%5E05%2105%407%23@db:5432/db --format=custom pg_dump: error: aborting because of server version mismatch pg_dump: detail: server version: 16.0; pg_dump version: 15.6 (Debian 15.6-0+deb12u1) i have installed postgress-client and therre is not exist any pg_dump package newer version 15 -
How to sort a queryset by a attributes's choices
I have a model with a selectable month and year, like so: class Item(models.Model): MONTHS_CHOICES = [ ('JANUARY', 'January'), ('FEBRUARY', 'February'), ('MARCH', 'March'), ('APRIL', 'April'), ('MAY', 'May'), ('JUNE', 'June'), ('JULY', 'July'), ('AUGUST', 'August'), ('SEPTEMBER', 'September'), ('OCTOBER', 'October'), ('NOVEMBER', 'November'), ('DECEMBER', 'December') ] month = models.CharField(max_length=9, choices=MONTHS_CHOICES, default="JANUARY", db_index=True) year = models.IntegerField(default=0) (...) If I try to order the items by month and year Item.objects.all().order_by("-year", "month"). Logically the months will be be ordered alphabetically. What can I do to get the items ordered by the same order I have the months on MONTHS_CHOICES? Option B is just redo the models to include a DateField with only year and month, like this question here and order it by that field I also tried the solutions on this page but nothing worked to me. -
TypeError at /api/register-application/
I was trying to deploy my system, as everything was working easily on localhost:8000 but when i deploy same code on the server then with the domainname api i cannot post any data with same function worked in localhost:8000. the error is TypeError at /api/register-application/ unhashable type: 'set' Request Method: POST enter image description here I want a solution to fix this issue. -
How to refactor a couple of fields from one model to another with FK relation
I currently have a model class Car(models.Model): name = models.CharField(max_length=20) manufacturer_name = models.CharField(max_length=20) manufacturer_url = models.URLField() Now I would like to extract the manufacturer information into its own model, so that I can get rid of redundant data. Like so: class Manufacturer(models.Model): name = models.CharField(max_length=20) url = models.URLField() class Car(models.Model): name = models.CharField(max_length=20) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) Doing this however the Django migration tool just detects this as "delete fields" and "add fields". Can Django somehow do this migration automatically? Or will I have to write those migrations myself. It seems like a common use case, so I figured maybe Django has something in store for ootb. -
Django Bootstrap form-select...how do I find the selected value?
I have a Django application using Bootstrap form-select. This is filled up from a table like this: <div class="div-1 rounded bg-light text-dark "> {% trans "Active restaurant: " %} <select class="form-select-sm bg-light text-dark" aria-label={% trans "Select a restaurant" %} id="Selected_Restarurant"> <option selected>{% trans "Select a restaurant" %}</option> {% for restaurant in restaurants %} <option value="restaurant.name">{{ restaurant.name }}</option> {% endfor %} </select> </div> I have no idea how to address the value selected by the user in the form-select above. I need to run a filter on employee and update an employee table in the home.html template below to only show the employees of the selected restaurant. I know it has to do with the model and filters, that is also well documented, but how do I find the selected value and update the table below based on the selection?: <table class="table table-sm table-hover"> <thead class="table-success"> <tr> <!--th scope="col">{% trans "Employees" %}</th--> <th scope="col">{% trans "Restaurant" %}</th> <th scope="col">{% trans "First name" %}</th> <th scope="col">{% trans "Last name" %}</th> <th scope="col">{% trans "Username" %}</th> </tr> </thead> <tbody class="table-group-divider"> {% for employee in employees %} {% if employee.restaurant.name == "McDonalds in the bush" %} <tr> <!--td>{{ employee.user.first_name }}</td--> <td>{{ employee.restaurant.name }}</td> <td>{{ … -
I am having issues with the user signup, authentication and views in django
I have a django app and i have created a function to login a user but it shows error this is the view def loginpage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: return HttpResponse("Username or Password is incorrect!!!") return render(request, 'login.html') def LogoutPage(request): logout(request) return redirect('login') this is the html code {% load static %} <!DOCTYPE html> <html lang="us"> <head> <meta charset="UTF-8"> <title>Login</title> <link rel="stylesheet" href="{% static 'css/login.css' %}"> </head> <body> <div class="login-form"> <form method="post"> {% csrf_token %} <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <button type="submit">Login</button> </form> <p>Don't have an account? <a href="{% url 'signup' %}">Sign up here</a></p> </div> </body> </html> this is the url path('login/', userview.loginpage, name='loginpage'), this is the error shown TypeError at /login/ login() missing 1 required positional argument: 'user' Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 4.2.11 Exception Type: TypeError Exception Value: login() missing 1 required positional argument: 'user' Exception Location: C:\Users\kakarot\PycharmProjects\TradingApp.venv\Lib\site-packages\django\core\handlers\base.py, line 197, in _get_response Raised during: django.contrib.auth.login Python Executable: C:\Users\kakarot\PycharmProjects\TradingApp.venv\Scripts\python.exe Python Version: 3.11.7 Python Path: ['C:\Users\kakarot\PycharmProjects\TradingApp', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311', 'C:\Users\kakarot\PycharmProjects\TradingApp\.venv', 'C:\Users\kakarot\PycharmProjects\TradingApp\.venv\Lib\site-packages'] Server time: Tue, 16 Apr … -
Django ManifestStaticFilesStorage throwing Value Error
I am attempting to ensure that the cache is refreshed whenever I spin up a new instance in Django. I have implemented the following custom storage class to disable the strict handling of manifest files: from django.contrib.staticfiles.storage import ManifestStaticFilesStorage class NonStrictManifestStaticFilesStorage(ManifestStaticFilesStorage): manifest_strict = False This is used in conjunction with the setting: STATICFILES_STORAGE = "myapp.custom_storages.NonStrictManifestStaticFilesStorage" While everything appears to function correctly, I encounter a ValueError when a file does not exist, despite having set manifest_strict = False. This error was not expected under these circumstances. Could someone assist me in debugging this issue? As a temporary solution, deleting the problematic file resolves the error, but this is prone to future errors. For instance, if someone inadvertently removes a CSS file while cleaning up the code, it could disrupt the backend server, which must be avoided. -
Django: how to disable the HTTP_HOST check on a specific endpoint?
I defined a super simple healthcheck endpoint in my Django app (urls.py) to be used in a docker compose environment, like: services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile depends_on: db: condition: service_healthy env_file: - ./.envs/.production/.django command: /start healthcheck: test: ["CMD", "curl", "-f", "http://localhost:5000/healthcheck/"] start_period: 20s interval: 15s timeout: 10s retries: 5 start.sh #!/bin/bash set -o errexit set -o pipefail set -o nounset python /app/manage.py collectstatic --noinput exec /usr/local/bin/gunicorn config.asgi --bind 0.0.0.0:5000 --chdir=/app -k uvicorn.workers.UvicornWorker # ... various imports def healthcheck(): return HttpResponse() urlpatterns = [ # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path("accounts/", include("allauth.urls")), # Hijack path("hijack/", include("hijack.urls")), # Healthcheck path("healthcheck/", healthcheck, name="healthcheck"), # Media files *static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), ] if settings.DEBUG: # Static file serving when using Gunicorn + Uvicorn for local web socket development urlpatterns += staticfiles_urlpatterns() In a local environment there are no issues since localhost is inside the ALLOWED_HOSTS configuration variable. But if I'm in a production environment this is not allowed of course. Indeed I get: ... django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'localhost:5000'. You may need to add 'localhost' to ALLOWED_HOSTS. ... Since the healthcheck endpoint is only used internally is there a way to resolve this? On the top of … -
Why I get an "name 'os' is not defined" error (with import os done)
Good day! I write simplest code #!/usr/bin/python3 import os import os.path dirname = os.path.dirname(__file__) or '.' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") from django.template.loader import render_to_string rendered = render_to_string('Login.html', {'foo': 'bar'}) And got an error BASE_PATH = os.path.dirname(__file__) ^^ NameError: name 'os' is not defined. Did you forget to import 'os'? Clearly I don't forgot "import os". Any way to deal with this error? I try different code parts from any advice find on web, but no luck at all. -
Django Prefetch object with generic relation
As stated in the documentation: class Prefetch(lookup, queryset=None, to_attr=None) The Prefetch() object can be used to control the operation of prefetch_related(). The queryset argument supplies a base QuerySet for the given lookup For example, it can be used to specify the columns from the related object to SELECT, by using only(): Author.objects.prefetch_related(Prefetch("hometown", City.objects.only(["name"])) However, when prefetching the objects related through a generic relation, what model should be passed to the queryset param of Prefetch? I can't see any references to that on the docs nor SO. Something like: Prefetch("foo", GenericRelation.objects.only(["title"])) -
What's wrong with this Django view fucntion editpage func, EditForm class and editpage.html?
I am trying to just display page contents in console after the form is submitted. Also how to change editpage.html file's 'name' variable in such a way that instead of hardcoding 'ewew' variable name can be passed with name of each different pages.debug display on browser debug display on browserserver console view file of django: from django.shortcuts import render from . import util from django.http import HttpResponseRedirect from django.urls import reverse from django import forms from string import Template import markdown2 import re def writetofile(name,entryBody): file1 = open(f"encyclopedia/templates/wiki/{name}.html","w") file1.write('{% extends "encyclopedia/layout.html" %}\n') file1.write('{% block body %}\n') file1.write(entryBody) #editLink=f"<a href=\"{% url 'encyclopedia:editPage',{"name":{name}} %}\">Edit Page</a>" #editLink=f"<a href=\"{% url 'encyclopedia:editPage' name=name %}\">Edit Page</a>" #editLink=f"<a href=\"{% url 'encyclopedia:editPage' name='{name}' %}\">Edit Page</a>" #editLink="<a href=\"{% url 'encyclopedia:editPage' name='{}' %}\">Edit Page</a>".format(name) #editLink="<a href=\"{\% url 'encyclopedia:editPage',{'name': %s} \%}\">Edit Page</a>".format(name) #editLink = Template("<a href=\"{% url 'encyclopedia:editPage' , {name:'$name' }} %}\">Edit Page</a>") editLink = Template("<a href=\"{% url 'encyclopedia:editPage' name='$name' %}\">Edit Page</a>") editLink=editLink.substitute(name=name) print(editLink) file1.write(editLink) file1.write('\n{% endblock %}') file1.close() def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def newPageError(request): return render(request, "encyclopedia/newpageerror.html") #def content(request): def wiki(request,name): #name=request.GET.get('name') entryBody=util.get_entry(name) if entryBody: entryBody= markdown2.markdown(entryBody) writetofile(name,entryBody) #file1 = open(f"encyclopedia/templates/wiki/{name}.html","w") #file1.write('{% extends "encyclopedia/layout.html" %}\n') #file1.write('{% block body %}\n') #file1.write(entryBody) #file1.write('\n{% endblock %}') #file1.close() return … -
Trying to ban user as a super user (banned user can't create posts)
i give permission to my superuser to ban all the other types of users, this my views.py file: @login_required(login_url='login') def Home(request): posts = Post.objects.all() if request.method == "POST": #taking the id i passed in value attribute post_id = request.POST.get("post_id") user_id = request.POST.get("user_id") if post_id: post = Post.objects.filter(id=post_id).first() if post and (post.auther == request.user or request.user.has_perm('main.delete_post')): post.delete() elif user_id: user = User.objects.filter(id=user_id).first() if user and request.user.is_staff: try: group = Group.objects.get(name="default") group.user_set.remove(user) print("removed successfully") except: print("something went wrong") pass try: group = Group.objects.get(name="mode") group.user_set.remove(user) print("removed successfully") except: print("something went wrong") pass return render(request,"main/home.html", {"posts":posts}) my html file: {% if user.is_staff %} <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-warning" value={{post.id}} name="user_id">Ban User</button> </form> {% endif %} i tried to print messages if the user is removed and it printing removed successfully, and then i logged as that banned user i can still create post,did i miss something in views.py? -
Get values from 2 database statements with radio buttons
I am trying to connect two database statements via two radio buttons. As soon as I change the radio button value, these have to be retrieved again directly via the database. I am currently trying to do this via HTML, JavaScript and Python. However, only one of the two statements is currently displayed. js: $("#id_base-0-show_null").change(function () { var show_null_value = document.querySelector('input[name=base-0-show_null]:checked').value; var checked_0 = document.getElementById('id_base-0-show_null_0').checked; var checked_1 = document.getElementById('id_base-0-show_null_1').checked; console.log(show_null_value, checked_0, checked_1); **currently doesn't do anything** }); exporter.py: def get_last_values_of_target(self, target_type, target_name): ... def get_zero_values_of_target(self, target_type, target_name): ... manual_input.py: def get_last_values_of_target(request): if is_ajax(request): target_type = int(request.POST['target_type']) target_name = request.POST['target_name'] exporter = Exporter() exporter.station = target_type values = exporter.get_last_values_of_target(target_type, target_name) **here is the current single exporter where i'm trying to add a second one (get_zero_values_of_target)** return HttpResponse(simplejson.dumps({'values': values}), 'application/javascript') else: return HttpResponseBadRequest("Not allowed") template: {% block content %} <form action="" method="post" id="manual_input_form" name="manual_input_form"> {% csrf_token %} <div class="timeDiffer"> {% for base_form in base_formset %} *** <div class="{% if base_form.non_field_errors %}error {% else %}showDiff{% endif %}"> <div>{{ base_form.show_differences.label_tag }}{{ base_form.show_differences }}</div> </div> {% if base_form.show_differences %} <div class="{% if base_form.non_field_errors %}error {% else %}showNull{% endif %}"> <div class="flex">{% trans base_form.show_null.label_tag %}{{ base_form.show_null }}</div> </div> {% endif %} {% endfor %} <input type='hidden' … -
python makemigration creating tables error
Traceback (most recent call last): File "C:\python\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\python\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\Asus\Documents\projects\valeohr\backend\app\apps.py", line 9, in ready from .jobs import updater File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\updater.py", line 3, in <module> from app.jobs.jobs import Syncing File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\jobs.py", line 8, in <module> class Syncing: File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\jobs.py", line 13, in Syncing db = DB.get_db('geco1') File "C:\Users\Asus\Documents\projects\valeohr\backend\app\models\base.py", line 14, in get_db dbo = cls.objects.filter(code=db).first() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 1047, in first for obj in (self if self.ordered else self.order_by("pk"))[:1]: File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 394, in __iter__ self._fetch_all() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 1867, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 87, in __iter__ results = compiler.execute_sql( File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1398, in execute_sql cursor.execute(sql, params) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return … -
CSS on the site is not visible
I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the HTML. Would you like me to share the code? I try to change something on setting.py -
How can I troubleshoot an authentication issue?
When making a request to http://127.0.0.1:8000/auth/users/reset_password/. The endpoint works only if i include ""rest_framework_simplejwt.authentication.JWTAuthentication" at(DEFAULT_AUTHENTICATION_CLASSES) but not when using my Custom authentication "passportBackend.custom_auth.JWTOrOAuth2Authentication".I think the documentation of rest_framework_simplejwt it returns None when permission is not required. from rest_framework.authentication import BaseAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication from oauth2_provider.contrib.rest_framework import OAuth2Authentication from rest_framework.exceptions import AuthenticationFailed class JWTOrOAuth2Authentication(BaseAuthentication): def authenticate(self, request): # Try authentication additional_info = request.META.get("HTTP_X_ADDITIONAL_INFO") # # DRF OAuth2 # print(additional_info) if additional_info == "OAuth2": oauth2_authentication = OAuth2Authentication() oauth2_user, oauth2_auth = oauth2_authentication.authenticate(request) if oauth2_user is not None: return oauth2_user, oauth2_auth # # Simple JWT # elif additional_info == "jwt": jwt_authentication = JWTAuthentication() jwt_user, jwt_token = jwt_authentication.authenticate(request) if jwt_user is not None: return jwt_user, jwt_token return None def authenticate_header(self, request): # Override this method if needed pass "DEFAULT_AUTHENTICATION_CLASSES": ( "passportBackend.custom_auth.JWTOrOAuth2Authentication", ), How can I troubleshoot an authentication issue with my custom JWTOrOAuth2Authentication class ? -
How to connect to the existing database through NGINX?
I have a project what I need to start with Docker. I've successfully created images and containers of Django, NGINX and postgreSQL, so the project starts correctly. I noticed that when I try to login to the admin panel, Django raises OperationalError at /admin/login/ connection to server at "database" (192.168.144.2), port 5432 failed: fe_sendauth: no password supplied. Everything worked fine without nginx, but now I cannot access to the database. As I understand the problem, I need to change nginx.config, but I tried almost everything and still cannot figure this out. Seems like postgreSQL doesn't see my user maybe. My code snippet below. uwsgi.ini [uwsgi] wsgi-file = config/wsgi.py strict = true socket = :8000 protocol = http master = true no-orphans = true die-on-term = true lazy-apps = true processes = 4 threads = 8 enable-threads = true max-requests = 500 reload-on-rss = 1024 worker-reload-mercy = 60 harakiri = 60 harakiri-verbose = true vacuum = true post-buffering = 1048576 buffer-size = 65535 nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; include /etc/nginx/uwsgi_params; server { listen 80; server_name localhost; location / { proxy_pass http://django:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header … -
Can't make Telegram WebApp Validation work using python
I am unable to validate data that Telegram sent to my WebApp.. import hashlib import hmac import json import typing from urllib.parse import unquote def parse_init_data(init_data: str) -> typing.Dict: return dict(param.split("=") for param in init_data.split("&")) def parse_user_data(user_data: str) -> dict: return json.loads(unquote(user_data)) def _extract_hash_value(init_data: str) -> str: return parse_init_data(init_data)["hash"] def generate_secret_key(telegram_bot_token: str, c_str: str = "WebAppData") -> str: c_str_enc = c_str.encode() token_enc = telegram_bot_token.encode() return hmac.new(token_enc, c_str_enc, digestmod=hashlib.sha256).hexdigest() def validate(init_data: str, secret_key: str) -> bool: hash_ = _extract_hash_value(init_data) unquote_init_data = unquote(init_data) sorted_init_data = sorted( [chunk.split("=") for chunk in unquote_init_data.split("&") if chunk[: len("hash=")] != "hash="], key=lambda x: x[0], ) sorted_init_data_str = "\n".join([f"{key}={val}" for key, val in sorted_init_data]) init_data_enc = sorted_init_data_str.encode() secret_key_enc = secret_key.encode() data_check = hmac.new(init_data_enc, secret_key_enc, digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(hash_, data_check) this code is from github. It is intended to validate data coming from Telegram to my WebApp.. I have passed all necessary things.. extracting user data from Telegram Sent data is working. But validating that data is from Telegram failing. This is initData I got query_id=AAHkHFkqAAAAAOQcWSqv8eyu&user=%7B%22id%22%3A710483172%2C%22first_name%22%3A%22Ro%27zmat%22%2C%22last_name%22%3A%22Otajonov%22%2C%22username%22%3A%22OtajonovR%22%2C%22language_code%22%3A%22en%22%2C%22is_premium%22%3Atrue%2C%22allows_write_to_pm%22%3Atrue%7D&auth_date=1713215281&hash=c7907965154661f6f322d02e4a97086568e033980818396b623649ba3a062685 and this code is my django view that trying to validate using above functions: from django.shortcuts import render from .webapp_auth import parse_init_data, parse_user_data, validate, generate_secret_key from django.contrib.auth import get_user_model User = get_user_model() def business_settings_view(request): … -
Most Efficient Way To Add Email Field of Auth User Model From A ManyToMany Field When Sending Email
In the code below I would like to add the email of the user's email field directly into the recipient's variable below in the notification function. How would one achieve this? class Pass(models.Model): guest_name = models.CharField(max_length=128,blank=False,verbose_name="Guest") date = models.DateField(blank=False,null=False,verbose_name='Date') area = models.CharField(max_length=128,blank=False,verbose_name='Area(s)') member_name = models.CharField(max_length=128,blank=False,verbose_name="Member") member_number = models.IntegerField(blank=False) phone = models.CharField(max_length=14,blank=False,null=False) email = models.EmailField(max_length=128,blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='pass_users', blank=True, null=True, ) managers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='passes', blank=True, limit_choices_to = {'is_active': True}) def __str__(self): return '%s' % (self.guest_name) def get_absolute_url(self): return reverse('guestpass:pass_detail', kwargs={'pk':self.pk}) @receiver(post_save, sender=Pass) def notification(sender, instance, **kwargs): if kwargs['created']: subject = 'New Guest Pass' message = '%s guest pass has been created.' %(instance.guest_name) sender = 'noreply@email.com' recipients = [?] send_mail( subject, message, sender, recipients, fail_silently=False, ) -
Should model fields be tested in Django?
class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) MDN says: You don't need to explicitly test that first_name and last_name have been stored properly as CharField in the database because that is something defined by Django ... However you should check the text used for the labels (First name, Last name, Date of birth, Died), and the size of the field allocated for the text (100 chars), because these are part of your design and something that could be broken/changed in future. If I wanted to follow that advice, I would not write a test that tests that the field only accepts 100 characters, since that would mean testing Django's behavior. Instead, I would write a test that tests that max_length indeed equals 100. This test could look something like this: def test_max_length(self): self.assertEqual(models.Author._meta.get_field('first_name').max_length, 100) My feeling is that this test would basically be the same as testing that I wrote what I wrote. Of course, if a wrong max_length breaks some other piece of code, that should be tested, but it should be tested in that other piece of code. What are the best practices for testing Django model fields? … -
Django Python - What does _ do after a variable name
Sorry for my poor explanation but I'm reviewing my professor's code like this: user, _ = User.objects.get_or_create( name = serializer.data['name'], email = serializer.data['email'], password = make_password(serializer.data['password'])) when I remove the ", _" from that I can't access the objects (eg: name) of it. I was doing "user.name" but I cant without the ", _" can someone explain why that is. It's my first time here in in SO hehe I wanna access the name field through the user where I assigned the object I created -
Django HttpReponse: can't change file name (XMLHttpRequest)
I am trying to implement a file download feature via an XMLHttlpRequest. The response is formed as follows: response = HttpResponse(entries, content_type='application/text charset=utf-8') response['Content-Disposition'] = f'attachment; filename={self.title}.docx' So, the title should be something like 'Book.docx'. Instead, on every download I get a UUID-like title that is different, wrong, and has no extension, e.g. 'b691dac0-9498-414f-9c5b-a96223998b76'. Encoding the title with urlquote or .encode() doesn't help. -
Django - Need guidance on filtering data by keywords
In my web-app project, I have a page for advanced search. Initially, all the items from db should be displayed on front-end. From admin interface, for each item I have added keywords separated by comma. What I want to do is to filter the items on FE based on those keywords. Example: the wine has keywords like: red, dry . When I click on one of those options on front-end, the corresponding wines should be shown. I have created the template, added views and some javascript but now I'm stuck and I don't understand where the logic lacks. Here is the template piece: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false"> Filter </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="filterOptions"> <li><a class="dropdown-item" href="#" data-keyword="red">Red</a></li> <li><a class="dropdown-item" href="#" data-keyword="sparkling">Sparkling</a></li> <li><a class="dropdown-item" href="#" data-keyword="white">White</a></li> <li><a class="dropdown-item" href="#" data-keyword="sweet">Sweet</a></li> <li><a class="dropdown-item" href="#" data-keyword="dry">Dry</a></li> <li><a class="dropdown-item" href="#" data-keyword="citrus">Citrus</a></li> </ul> </div> <section class="products section-padding"> <div class="container"> <div class="row"> {% for wine in page_obj %} <div class="col-lg-4 col-12 mb-3"> <div class="product-thumb"> <a href="product-detail.html"> <img src="{{ MEDIA_URL }}{{ wine.image.url }}" class="img-fluid product-image" alt=""> </a> <div class="product-info d-flex"> <div> <h5 class="product-title mb-0"> <a href="product-detail.html" class="product-title-link">{{ wine.name }}</a> </h5> <p class="product-p">{{ wine.description }}</p> </div> </div> </div> </div> {% endfor %} … -
Django. 'GroupDetailView' object has no attribute 'object'
I try create AddMembersForm to Group in my app. 'GroupDetailView' object has no attribute 'object' class GroupDetailView(DetailView): model = Group context_object_name = 'group' template_name = 'rooms/group_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AddGroupMemberForm(group_id=self.object.id) context['members'] = GroupMembers.objects.filter(group=self.object) #Download all members return context def post(self, request, *args, **kwargs): form = AddGroupMemberForm(request.POST, group_id=self.object.id) if form.is_valid(): new_member = form.save(commit=False) new_member.group = self.get_object() new_member.save() return redirect(self.get_object().get_absolute_url()) else: return self.render_to_response(self.get_context_data(form=form)) ----------------------------------------------------------------------------------- class Group(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='creator_group', on_delete=models.CASCADE) name = models.TextField(max_length=50) description = models.TextField(max_length=500) def __str__(self): return self.name def get_absolute_url(self): return reverse('group_detail', kwargs={'pk': self.pk}) class GroupMembers(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='membership') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='group_membership') role = models.TextField(max_length=30, default='Członek grupy') time_release = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} należy do {self.group.name}' I want to add users to my groups (the group founder will have this option).