Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Create a watch list feature
The user can add that product to the watch list by clicking on the add button, and then the add button will change to Rimo. And this time by clicking this button, the product will be removed from the list. There should be a link on the main page that by clicking on it, all the products in the watch list will be displayed, and by clicking on the detail button, you can see the details of the product, and by clicking on the remove button, you can remove them from the list. models.py class User(AbstractUser): pass class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default = True) views.py: def product_detail(request, product_id): product = get_object_or_404(List, pk=product_id) comments = Comment.objects.filter(product=product) if request.method == 'POST': # comment if 'comment' in request.POST: user = request.user if user.is_authenticated: content = request.POST.get('content') comment = Comment(product=product, user=user, content=content) comment.save() context = { 'product': product, 'comments': comments, } return render(request, 'auctions/product_detail.html', context) from .forms import AddWatchlist def … -
Retrieving files using django rest Framework and postman
I am making a secure file storage system In this for the decryption process user is giving the file_id and key as an input. The program finds the file, reads it's data and decrypts it using the key and rewrites the file data of the file with the new encrypted data and return the file. I'm using django rest framework for this. The code for the view is given below: class Decryption(APIView): def post(self, request, *args, **kwargs): file_id = request.data.get('file_id') key = request.data.get('key') try: if not key: return Response({"error": "Key is required"}, status= status.HTTP_400_BAD_REQUEST) try: encrypted_file = EncryptedFile.objects.get(id = file_id) except EncryptedFile.DoesNotExist: return Response({'detail': "The requested File doesn't exist"}, status= status.HTTP_404_NOT_FOUND) encrypted_data = encrypted_file.file.read() cipher = Fernet(key) decrypted_data = cipher.decrypt(encrypted_data) encrypted_file.file.seek(0) #encrypted_file.file.write(decrypted_data) response = Response() response['Content-Disposition'] = f'attachment: filename = {encrypted_file.file_name}' response.write(decrypted_data) return response except Exception as e: return Response({'details': e}, status= status.HTTP_400_BAD_REQUEST) I was expecting a file as a result. But I got a blank screen when I made an API call using postman -
Failed authentication for Google Sheet and Django running in Apache server
I'm implementing a Django application that uses a Google Sheet as database, and is hosted with Apache in a Rocky Linux server. To test the integration between Django and Google Sheet, I have followed Tom Dekan Tutorial. And to configure the Django application to run with Apache, I have followed the official Django Tutorial. However, when I try to access the page, I receive an Internal Server Error. Checking the error logs, I receive the following message: [Thu Nov 16 11:44:34.203173 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] mod_wsgi (pid=150297): Failed to exec Python script file '/opt/dashbea/TesteGSheet/core/core/wsgi.py'. [Thu Nov 16 11:44:34.203297 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] mod_wsgi (pid=150297): Exception occurred processing WSGI script '/opt/dashbea/TesteGSheet/core/core/wsgi.py'. [Thu Nov 16 11:44:34.203791 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] Traceback (most recent call last): [Thu Nov 16 11:44:34.203866 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] File "/opt/dashbea/TesteGSheet/core/core/wsgi.py", line 22, in <module> [Thu Nov 16 11:44:34.203876 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] application = get_wsgi_application() [Thu Nov 16 11:44:34.203885 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] File "/opt/dashbea/TesteGSheet/my_env/lib64/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Thu Nov 16 11:44:34.203893 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] django.setup(set_prefix=False) [Thu Nov 16 11:44:34.203902 2023] [wsgi:error] [pid 150297:tid … -
Pytest and Selenium in Docker : wrong database used for the test suite?
I'm struggling to setup my test runner for a new Django project. I want to use these libraries : Django 4.2 pytest-django 4.6.0 pytest-splinter 3.3.2 And I want it to work with Docker. I got a head start with that answer : https://stackoverflow.com/a/58447497/3219759 but I can't make it work. Here is my docker-compose.yml : version: '3.3' services: web: build: jam restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - USE_DOCKER=True env_file: - .env ports: - "127.0.0.1:8000:8000" volumes: - .:/code links: - db depends_on: - db - selenium db: image: postgres environment: - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xxx - POSTGRES_DB=xxx ports: - "127.0.0.1:5432:5432" volumes: - pg_data:/var/lib/postgresql/data selenium: image: selenium/standalone-firefox:4.9.1 ports: - "4444:4444" # Selenium - "5900:5900" # VNC volumes: pg_data: And to finish the setup, I have these fixtures in the conftest.py file : @pytest.fixture(scope='session') def test_server() -> LiveServer: addr = socket.gethostbyname(socket.gethostname()) server = LiveServer(addr) yield server server.stop() @pytest.fixture(scope='session') def splinter_webdriver(): return 'remote' @pytest.fixture(scope='session') def splinter_remote_url(): return 'http://selenium:4444/wd/hub' and this in settings.py: if env('USE_DOCKER') == 'yes': import socket ALLOWED_HOSTS = [socket.gethostbyname(socket.gethostname())] I have a basic view that list all the profiles, and a template to match. This feature is working on my local server. The corresponding test: @pytest.mark.django_db class TestIndexPage: def test_profile_list(self, browser, … -
Email simulation with Django
This project should be able to simulate email. The program runs successfully and I can write the email, but the email is not sent and it gives this error. what is the problem؟ in terminal: [16/Nov/2023 17:35:46] "GET /emails/inbox HTTP/1.1" 200 2 in console: MLFormElement. (inbox.js:10:7) code: document.addEventListener( "DOMContentLoaded",function () { const form = document.querySelector("#compose-form"); const msg = document.querySelector("#message"); form.addEventListener("submit", (event) => { event.preventDefault(); to = document.querySelector("#compose-recipients"); subject = document.querySelector("#compose-subject"); body = document.querySelector("#compose-body"); if (from.length == 0 && to.length == 1000) return; fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: to.value, subject: subject.value, body: body.value, }), }) .then((response) => response.json()) .then((result) => { console.log(result.status); if (result.status == 201) { load_mailbox("sent"); } else { msg.innerHTML = `<div class="alert alert-danger" role="alert"> ${result.error} </div>`; } }); }); }, false ); -
How do I change the default buttons in django?
In django admin, models have default buttons, how can I change the name of these buttons? enter image description here