Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build database for an e-commerce website in development and how to deploy it in production mode? [closed]
I want to built an E-commerce website using HTML, CSS, Bootstrap, Javascript, Python and Django. How to make databases for an e-commerce website, what is virtual environment in development mode, in production, how to configure it in production mode? I have tried using Django and Sqlite3 default database. But won't have any knowledge regarding databases -
Docker (Postgres image): authentication problem
I am running a Django project at the moment and I have an error when I try to use the command python manage.py migrate. I have a docker image called explore_hub. When I run python manage.py migrate I have the followin error: System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'D:\2xProjects\Python\ExploreHub\explore_hub\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection self.connect() File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "suadmin" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 22, in <module> main() File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 458, in execute output … -
Unusual Occurrence in Django's Main Thread
I am encountering errors when attempting to execute my Django project using the command python manage.py runserver Kindly assist me in resolving these errors. Error Error Error Please help, its an emergency, its my tesis -
My django app automatically add a /static/ to any url not specified with the {% url %} tag
As stated in the title of my question my app is going on production and i configured all the static parameters, everything works fine except one thing and i can't seem to find the problem. When i make an <a href="#Description"> to get to an anchor for exemple, the link that is served is: www.example.com/static/#Description instead of www.example.com/mypage/#Description Thank you for your help ! This is my settings.py configuration: PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Ajout d'un dossier static non lié a une app en particulier STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] I've tried changing the configuration but i don't seem to find the problem. -
single positional indexer is out-of-bounds in django
views.py file def rpa_save(request): if request.method == 'POST': test_kodu = request.POST.get('test_kodu') test_kodu = str(test_kodu) OlcumSonucLOG, dfLimit, urun_kodu = Providers.getir(test_kodu=test_kodu,is_emri=is_emri) my providers.py file @staticmethod def getir(test_kodu,is_emri): _, cur = Connection.connect_to_btr() sfTestler = RawDataProvider.get_sftestler_db(cur, is_emri) # Buradan is emri bilgisi ile yapılan testlerin order_no larını alıyoruz # sfTestler = pd.DataFrame({'ORDERNO': [223030204106, 223030204106, 223030204106,223030204106,223030204106,223030204106,223030204106]}) #test için konuldu, silinecek firstOrder = min(sfTestler['ORDERNO'].values,default=None) lastOrder = max(sfTestler['ORDERNO'].values,default=None) df = RawDataProvider.get_pklsonuclar_db(cur, firstOrder, lastOrder) # Bu order_no'na ait bütün testler dfSpecific = df[df['TESTKODU']==str(test_kodu)] dfSpecific.loc[:, ["BATCHNO", "TESTNO"]] = dfSpecific.loc[:, ["BATCHNO", "TESTNO"]].astype('int') dfSpecific = dfSpecific.sort_values(['BATCHNO', 'TESTNO'], ascending=[True, True]) urun_kodu = dfSpecific['URUNKODU'].iloc[0].split("-")[0] when i try send test_kodu and is_emri variables to providers.py i get single positional indexer is out-of-bounds from this line urun_kodu = dfSpecific['URUNKODU'].iloc[0].split("-")[0] how can i fix it ? -
Django-Python:The user image is not displayed on the user page when logged in with user details
When a user logs in, I want to see their profile picture if they have one; if not, the default profile picture should be displayed. Here is my view.py def header(request): if request.session.has_key('id'): user_id = request.session['id'] user = registertb.objects.get(id=user_id) return render(request, 'headerfooter.html', {'user_image': user}) else: return render(request, 'headerfooter.html')` ``` HTML CODE ``` <li> <p style="width:30px; height:30px; margin-left: 200px; margin-top: 10px;color: black;">{{ i.User_name }}</p> {% if user.user_image %} <img src="{{ i.user_image.url }}" style="height: 50px; width: 50px;" alt="Default Image"> {% else %} <img src="/media/image/New folder/default-avatar-profile.jpg" style="height: 50px; width: 50px;" alt="Default Image"> {% endif %} </li>` ``` models.py ``` class registertb(models.Model): User_name=models.CharField(max_length=300) User_email=models.CharField(max_length=300) user_image=models.ImageField(upload_to='image/') password=models.CharField(max_length=400) conf_password=models.CharField(max_length=300) ` ``` -
Websocket not receiving messages from Django Channels server websocket
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages. my asgi.py is import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) my consumer.py is import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(_name_) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing is from django.urls import re_path from … -
Error While Deploying a Django App on Railway.app
#10 33.61 return hook(config_settings) #10 33.61 ^^^^^^^^^^^^^^^^^^^^^ #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 355, in get_requires_for_build_wheel #10 33.61 return self._get_build_requires(config_settings, requirements=['wheel']) #10 33.61 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 325, in _get_build_requires #10 33.61 self.run_setup() #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 507, in run_setup #10 33.61 super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script) #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in run_setup #10 33.61 exec(code, locals()) #10 33.61 File "", line 7, in #10 33.61 File "/root/.nix-profile/lib/python3.11/tkinter/init.py", line 38, in #10 33.61 import _tkinter # If this fails your Python may not be configured for Tk #10 33.61 ^^^^^^^^^^^^^^^ #10 33.61 ModuleNotFoundError: No module named '_tkinter' #10 33.61 [end of output] #10 33.61 #10 33.61 note: This error originates from a subprocess, and is likely not a problem with pip. #10 33.61 error: subprocess-exited-with-error #10 33.61 #10 33.61 × Getting requirements to build wheel did not run successfully. #10 33.61 │ exit code: 1 #10 33.61 ╰─> See above for output. #10 33.61 #10 33.61 note: This error originates from a subprocess, and is likely not a problem with pip. #10 33.63 #10 33.63 [notice] A new release of pip is available: 23.1.2 -> 23.3.1 #10 33.63 [notice] To update, run: pip install --upgrade pip #10 ERROR: process … -
Creating a table to display rows from a database
I'm trying to create a table that will display the rows of a database called patients and I have created this using Django as the back-end and react as the Front-End. When I try to implement the code I have created thus far the only thing I'm seeing on the webpage is my table header. It should be noted that I have checked sqlite studio and there is data stored in the table. I've checked on PostMan and my Get, POST,PUT, and DELETE methods are all working fine and do what I intend them to do. I'm using Firefox as my browser and I've checked the network tab under inspection, but nothing is being sent to the back-end. I will attach my initial attempt at the front-end webpage import React, {Component} from 'react' export class ViewPatients extends Component{ constructor(props){ super(props); this.state = { patient: [], }; } fetchPatients = () => { fetch('http://127.0.0.1:8000/patient') .then(response => response.json()) .then(data=> { this.setState({patient:data}); }) .catch(error => { console.error("Error Fetching Patients") }); }; componentDidMounted(){ this.fetchPatients(); // this.refreshList(); } render(){ const { patient } = this.state; return( <div> <table> <thead> <tr> <th>ssn</th> <th>address</th> <th>age</th> <th>gender</th> <th>race</th> <th> medical history </th> <th>occupation</th> <th>phone number</th> <th>username</th> </tr> </thead> … -
How to update Django url (to include data/param) after POST
I have a search form (place names) on my home page with an auto-complete dropdown on the search input field. When the user presses enter after selecting an item in the search box the form does a post. When the results return I still have the same url (https://mywebsite.com). How do I get the selected search entry (a location name) to appear in the url so users can book mark it for later use? eg https://mywebsite.com/mylocation I have got the GET code working to get the location in the url - just don't know how to update the url to add the location string after the search form post. I am new to Django so really winging it. Have searched but found no discussion on this even in the Django docs. -
Removing user tags in django
I have been using taggit feature in django for hobbies . Each user can add his hobbies in his profile and tags will be created like tennis or watching movies. I have created a cloud to show him the tags that he has already added : <div class="rounded-tag-container"> {% tag_edit person_id=person.id %} </div> this is also html for this cloud: {% for tag in tags %} <span class="rounded-tag"> <a href="#" style="color:blue;"> {{ tag.name }} </a> <span class="close-button" onclick="removeTag(this, '{{ tag.name }}')"> <strong>×</strong></span> </span> {% endfor %} <script> function removeTag(element, tag_name) { element.parentNode.remove(); $.ajax({ type: 'POST', url: '/hobbies/' + person_id + '/', data: { tag_name: tag_name, csrfmiddlewaretoken: csrftoken }, success: function(response) { console.log(response); }, error: function(error) { console.error('Error deleting tag:', error); } }); } also In my hobbies view I defined tag_name: tag_name = request.POST.get('tag_name') if tag_name : try: person.tags.remove( tag_name) messages.success(request, 'Tag deleted successfully') except Tag.DoesNotExist: messages.error(request, 'Tag not found') else: messages.error(request, 'Tag name not provided') when the user clicks on the close button of each tags,it will be removed from the client side and then clicks on submit,it must remove the tag in post request from db, but it does not remove it from database! -
Django webapp creating 2 profiles when a user signs up
I am building a django webapp after creating a view for the signup page, if i go ahead and signup two profiles are created instead of one. i have tried redirecting to different pages but the problem still persists. this is the view i created def signup(request): if request.method == "POST": print("Signup view called") username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] password2 = request.POST["password2"] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, "Email Taken") return redirect("signup") elif User.objects.filter(username=username).exists(): messages.info(request, "Username Taken") return redirect("signup") else: user = User.objects.create_user(username=username, email=email, password=password) user.save() #log user in and redirect to settings page #create Profile object for the new user user_model = User.objects.get(username=username) new_profile = Profile.objects.create(user=user_model) new_profile.save() return redirect("signup") else: messages.info(request, "Password Not Matching") return redirect("signup") else: return render(request, "signup.html") -
Apache error Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state:'
Have been trying to get an apache server running for a project but have hit this roadblock Getting a 403 forbidden error Ive tried tutorials and other stack overflow questions but can't seem to figure it out, apache should have permission to access this all and the paths should be correct. Completely stumped. apache error log: is in build tree = 0 stdlib dir = '/home/unitpi/mysite/venv/lib/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/unitpi/mysite/venv' sys.base_exec_prefix = '/home/unitpi/mysite/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/unitpi/mysite/venv' sys.exec_prefix = '/home/unitpi/mysite/venv' sys.path = [ '/home/unitpi/mysite/venv/lib/python311.zip', '/home/unitpi/mysite/venv/lib/python3.11', '/home/unitpi/mysite/venv/lib/python3.11/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x0000007faa743040 (most recent call first): <no Python frame> [Fri Nov 17 06:52:02.803390 2023] [wsgi:warn] [pid 38411:tid 548320587840] (13)Permission denied: mod_wsgi (pid=38411): Unable to stat Python home /home/unitpi/mysite/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/unitpi/mysite/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 … -
no html element seems to stretch the whole height of my page
i want to apply a background colour but the html, body and my containers dont seem to stretch the whole height of the page. this image demonstrates my problem demonstration why doesnt any element seem to stretch over my whole page? how can i apply a background colour with a gradient over the whole page without it repeating? #################################### below is my html if that helps this is a django site made of 2 html elements, i cant tell if the problem is due too the fact my body is declared in 1 html page, but contains things from another.... repeated_stuff.html <!DOCTYPE html> {% load static %} <html lang="en" style="height: 100%"> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" type="text/javascript"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body style="background: linear-gradient(135deg, #ff9a75, #e8f9fd, #59ce8f); height: 100%; margin: 0;"> <div class="container text-center" id="main_container"> {% block content %} {% endblock %} </div> </body> </html> and heres my main content {% extends "repeated_stuff.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'carousel.css' %}"> <link rel="stylesheet" href="{% static 'quick_skills.css' %}"> <link rel="stylesheet" href="{% static 'layout_helper.css' %}"> <div class="row"> <div class="col" > <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="false" style="height :70vh; margin-left:15%; … -
Manager isn't accessible
**** view in the model***** class detail(DetailView): model = Requisicao context_object_name = 'requisicao' template_name = 'detail.html' pk_url_kwarg = 'pk' class itemManager(models.Manager): def get_queryset(self): return super(itemManager, self).get_queryset() First of all, thank you for your time and help. I'm trying to bring the items from this queryset but it's showing this error in my browser. I would like to know how to solve it. -
How to use the User built in model as a default value of another form?
I am working on a project that is dealing with the built-in User model. I have a class that showed me how to use the User model...Registering, Login/Logout, Dashboard, Being able to update the profile of a user, and Deleting an account. But I can't get it to click on using the logged in User in other ways. Such as a value in another form and Sorting based on user. The goal of the app is to A logged in user is able to 'create' a deck and the 'User' field is auto set to the logged in user A logged in user is able to only see the decks they have The user can edit/delete a deck owned by them views.py def my_decks(request): # this is me trying to get all decks owned by logged in user but doesn't work deck_list = Deck.objects.get(user=request.user) # Currently this creates a deck object but leaves the user field null if request.method == "POST": deck = DeckForm(request.POST, instance=request.user) if deck.is_valid(): deck.save() return HttpResponseRedirect('/my-decks') else: deck = DeckForm() context = {'deck': deck, 'deck_list': deck_list} return render(request, 'gametracker_app/my-decks.html', context=context) def update_deck(request): if request.method == 'POST': deck = UpdateDeckForm(request.POST) if deck.is_valid(): deck.save() return redirect('my-decks') else: deck … -
Celery redis reduce freqeuncy of BRPOP messages
I'm running my worker with the following arguments --without-gossip --without-mingle --without-heartbeat with Redis as my celery broker I can see my redis instance is frequently receiving messages (once a second) that look as follows: 1700056088.098427 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056089.104080 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056090.109984 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056091.115298 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056092.122189 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056093.126348 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" This amount of traffic means I can't use certain free-tiers in cloud providers. Realistically I only need to run a single periodic task every hour (like a cronjob). Is there a way to reduce the frequency / interval of these messages? -
Websocket not receiving messages from Django Channels server
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages. my asgi.py is import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) my consumer.py is import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(_name_) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing is from django.urls import re_path from … -
TemplateDoesNotExist error in Django Webapp
I am getting this error when i try to use the default django login page: TemplateDoesNotExist at /login/ registration/login.html this is my urls file: from django.urls import path from django.urls import path, include from . import views urlpatterns = [ path("", views.home, name="home"), path("main-page/", views.main_page, name="main-page"), path("kick-page/", views.kick_page, name="kick-page"), path('', include("django.contrib.auth.urls")), # add django auth pages for login ] this is my views file: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import login, authenticate from .forms import * #import all the forms from forms.py def home (response): form = SignIn() return render(response, "main/home.html", {"form": form}) #need a page to select site/microtik, and add/remove microtiks def main_page (response): return render(response, "main/main_page.html", {}) #Need a page that shows the selected mictotik and a form to enter MAC of device to kick def kick_page (response): return render(response, "main/kick_page.html", {}) and this is my directory structure: C:. └───microsite │ db.sqlite3 │ manage.py │ ├───main │ │ admin.py │ │ apps.py │ │ forms.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ __init__.cpython-311.pyc │ │ │ ├───templates │ │ … -
Django "request.user" always returns "AnonymousUser" even though sessionid gets added and is valid
So I made a discord oauth2 login without using a User model like AbstractUser or AbstractBaseModel, when I first made it a month ago, it worked fine and the login worked flawlessly! (Profile loaded, username shown, etc.) I don't know what I changed a week ago, but it no longer works. The custom authentication works and authenticate() returns a new DiscordUser model, then it gets passed to login() with the custom backend argument. The sessionid gets saved in the cookie storage when I check it. When I also check the DB, the sessionid is there and therefore a valid sessionid. Yet when I print out the request.user or request.user.is_authenticated I always get AnonymousUser and False. I don't understand. I followed this video: https://www.youtube.com/watch?v=KKJyU7JGuVk&list=PLwu1p7jK5YEUhRNJpzLYa8nhWRnJdPR6p auth.py: from django.contrib.auth.backends import BaseBackend from .models import DiscordUser class DiscordAuthenticationBackend(BaseBackend): def authenticate(self, request, user) -> DiscordUser: try: user = DiscordUser.objects.get(pk=user["id"]) return user except DiscordUser.DoesNotExist: new_user = DiscordUser.objects.create_discord_user(user) new_user.save() return new_user managers.py from django.contrib.auth import models from datetime import datetime from utils.cipher import XChaCha20Manager from base64 import b64encode class DiscordUserOAuth2Manager(models.UserManager): def create_discord_user(self, user): # encrypt tokens with the same nonce encrypted_access_token, nonce = XChaCha20Manager().encrypt(user["access_token"].encode()) encrypted_refresh_token, _ = XChaCha20Manager(nonce=nonce).encrypt(user["refresh_token"].encode()) new_user = self.create( user_id=user["id"], username = f"{user["username"]}", avatar = … -
Sending the output of two filters in one querystring to filter a django model
I have two filters. I have used pokemon as the example: Filter A: filters the pokemon trading card sets e.g. Base set, Fossil, Jungle Filter B: Filters the pokemon stats, e.g. pokemon types, name of pokemon. Those two filters have two submit buttons, I want them to work together. If I hit the submit for filter B it sends: ?name=Bulbasaur&type= If I hit the submit for filter A it sends: ?sets=Jungle What I want is: ?name=Venusaur&type=&sets=Fossil I'm using the module django-filters, I construct a FilterSet class for each filter that I initiate in the view. pokemon_sets = PokemonSets.objects.all() pokemon_filter = PokemonSetsFilter(request.GET, queryset=pokemon_sets) sets = pokemon_filter.qs.values_list('key_id', flat=True) pokemon = PokemonDatabase.objects.filter(sets__in=sets) pokemon_filter = PokemonFilter(request.GET, queryset=listings) Any insight will help greatly! I tried filtering the pokemondatabase model to the output of the filter to chain the filters to filter the model, but only one filter works at a time. -
How to dynamically set the access token expiration in Django Rest Framework Simple JWT?
I am working on a restful web application using Django Rest Framework and need to implement a mechanism to check every 15 minutes if the user has been active in order to extend their token expiration. If the user has not been active, their access token should become invalid. I am using Djoser in conjunction with Simple JWT as the authentication backend. Can someone provide guidance on how to achieve this? Thank you. I have tried creating a custom middleware to track the user's activity for the last 15 minutes but do not know how to effectively manage the user's jwt access token based on the user activity. -
Run Tests with Coverage "TypeError: Parameters to Generic[...] must all be type variables"
When running tests with coverage using PyCharm on django (python) project, im having the following error: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2023.1.2\plugins\python\helpers\pycharm\django_test_manage.py", line 6, in <module> from django.core.management import ManagementUtility File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\core\management\__init__.py", line 13, in <module> from django.apps import apps File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\apps\__init__.py", line 1, in <module> from .config import AppConfig File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\apps\config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\utils\deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\asgiref\sync.py", line 130, in <module> class AsyncToSync(Generic[_P, _R]): File "C:\Program Files\Python39\lib\typing.py", line 277, in inner return func(*args, **kwds) File "C:\Program Files\Python39\lib\typing.py", line 997, in __class_getitem__ raise TypeError( TypeError: Parameters to Generic[...] must all be type variables class SimpleTest(TestCase): def test_basic_addition(self): self.assertEqual(1 + 1, 2) According to what i have read, its probably a version conflict between typing and asgiref. Here are the versions I'm using: typing_extensions 4.8.0 asgiref 3.7.2 Python 3.9.13 Django 3.2.20 Whats weirder is that running the the same test with coverage (using lib coverage.py) from terminal, everything works. coverage run ./manage.py test -v 3 According to Jetbrains, the PyCharm IDE uses the exact same library for coverage...What could be the solution? -
Django 4.2 , GenericIPAddress and CIDR
Im updating a project from: Python 3.9 + Postgres 13 + Django 4.0.6 + psycopg2 TO Python 3.11 + Postgresql 15 + Django 4.2 + psycopg3 I have a big problem with GenericIPFields. It seems that it doesn't support cidr anymore. When I try to save an ORM with a cidr, I get: ValueError: '10.255.96.48/28' does not appear to be an IPv4 or IPv6 address I need that INET FIELD on DB with cidr to make queryes like: Subnet.objects.filter().extra(where = [ "cidr::inet >>= inet '"+self.ip_address+"'" ]) and other cidr related queries. -
How can I define multiple URL patterns in Django?
Could anyone tell me how to define multiple URL patterns in Django? On YouTube, I watched a few videos, but they didn't help me and I found a lot fo mistakes in it. Thank you for helping to define multiple URL patterns in Django.