Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why i get None instead of the model id in django ImageField path
When attempting to add a new event through the Django admin panel, the image is incorrectly being stored at the path "media/events/None/poster/file.png" instead of the intended path "media/events/{instance.id}/poster/file.png." I have added a print(...) statement to the get_poster_image_path function for testing purposes. : def get_poster_image_path(instance, filename): print(f""" from get_poster_image_path ==================\n type :{type(instance)}\n instance :{instance}\n instance.id :{instance.id}\n instance.name :{instance.name} """) return f'events/{instance.id}/poster/{filename}' class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True) .... the result: from get_poster_image_path ============================= type :<class 'events.models.Event'> instance :myevent instance.id :None instance.name :myevent -
Custom Session backend for Django using firestore
We are tryng to create a custom backend session engine using firestore. The autentication methodology is FireBase Auth. We have created the following code for the custom session and while we are abl to create collections in Firestore , data with session_key and uid is not being written to docs in the collection. We are hoping to eliminate the use of SQLite or any other sql for production -
python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory
I made this command “python manage.py runserver” I got this error “ python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory” how can i fix this I tried to check if the file was there and I found the file was there -
get_absolute_url does not work in my django app
in my django app, i have used get_absolute_url in model. from django.db import models from django.urls import reverse class nm(models.Model): name = models.CharField(max_length=50) no = models.IntegerField() def __str__(self): return f"\n{self.name}|{self.no}\n" def get_absolute_url(self): return reverse("number-str-url", args=[self.name]) but in django template when i want to link that, it does not work {% extends "base.html" %} {% block title %}Numbers{% endblock title %} {% block content %} <ul> {% for number in numbers %} <li><a href="{{number.get_absolute_url}}">{{number|title}}</a></li> {% endfor %} </ul> {% endblock content %} i want to show list of numbers one, two, three, four and five. when user clicks on one of them, the link navigate user to dedicated page of the number. something like this: One Two Three Four Five -
Django Python+Ajax : how to update variable from frontend to back end? My ajax function isn't working
When the user submits this form I want to save the rgb color code as a variable to be stored on the back end (using django), so whenever the card is loaded (the colour picked on this page) will be loaded. I asked GPT, which suggested using ajax (I've never used it before). This is a snippet from my js : function updateSetColor(color) { console.log(color); $.ajax({ type: "POST", url: "/Flashcard/", beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken")); }, data: { color: color }, error: function(error) { console.log("Error updating color"); }, cache: false, }); } This is a snippet from my view that uses the color variable sent from the data : def flashcard(request): form = Flashcard_verif(request.POST) if request.method == "POST" and form.is_valid() and request.accepts('main/Flashcard.html'): print(request.POST) color = request.POST.get("color") # Get the color from the AJAX request print(color) As you can see I've got the console to output the color picked by the user and on the backend I've got the server to output the color that should've been recieved. The output from the console is correct but the output from the server is 'None'. I suspect its due to the ajax function. Any help would be appreciated or new ways of … -
Django Serializer with Many To Many fileld returns empty list, How to fix it?
I have two models Product and Lessons. I join them in one Product serializer. But I get empty list in lesson fileld. This is what I am getting now: { "id": 1, "name": "Python", "owner": 1, "lessons": [] # here should be lessons }, my modelds.py class Product(models.Model): name = models.CharField(max_length=250) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Lesson(models.Model): name = models.CharField(max_length=255) video_link = models.URLField() duration = models.PositiveIntegerField() products = models.ManyToManyField(Product, related_name='lessons') My serializers.py class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'name', 'video_link', 'duration') class ProductSerializer(serializers.ModelSerializer): lessons = LessonSerializer(read_only=True, many=True) class Meta: model = Product fields = ['id', 'name', 'owner', 'lessons'] And my view.py class LessonListView(ListAPIView): serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): lesson_view = Product.objects.all() return products_view I can see many topics in the internet about that but I it is not working for me at all. How can I resolve it and get my data that I have for lessons field ? -
Django: How to enable app usage for different societies
I have a django project that has many apps. There is a core app that has all the main models that other secondary apps will use. One model in the core app is called SocietyEntity: class SocietyEntity(models.Model): id = models.AutoField(primary_key=True) referenceName = models.CharField(max_length=200, verbose_name="Nombre") members = models.ManyToManyField(get_user_model()) administrator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name="Administrator") As shown, the societies can have one o more users as members. What I want to achieve is some kind of relation between societies and the other secondary apps of the project, that enable that society to make use of the app. Something like a manytomany kind of relation between SocietyEntity and app names? I'm not sure but I think I need some way to relate societies to apps, if that is even possible. If a society doesn't have permission to use an app, this shouldn't be listed in the admin interface for example. Any suggestion is well received! Thanks -
Django Table2 reverse ManyTomany
Here is my models : class Appellation(models.Model): name = models.CharField(db_index=True, max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) class Ranking(models.Model): name = models.CharField(db_index=True, max_length=200) initials = models.CharField(db_index=True, max_length=10, blank=True, null=True) appellation = models.ManyToManyField(Appellation) In the Ranking Table, i arrived to have a column with all the appellation of a ranking : appellation = tables.ManyToManyColumn(lambda obj: format_html('<span class="badge py-3 px-4 fs-7 badge-light-primary">{}</span>', str(obj)), separator=' ') It's OK. No, i would like to have in the Appellation Table, a column with all the rankings of the appellation. Thanks you for your help. Regards -
Csrf token verification failing for admin form after using AbstractUser class in Deployement?
I am using Abstract User class for authentication in Django. Works fine on Localhost but when deployed the admin route is redirecting and csrf verification is failing with 403 Error. https://rallys.azurewebsites.net/admin/login/?next=/admin/ ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['https://rallys.azurewebsites.net'] AUTH_USER_MODEL = 'home.User' I have looked at modifying the Authenticate_user_model but the error persists. I noticed that the passwords field is no longer hashed in the admin panel on local host except for the SuperUser I created using CLI. -
How can I see the values of a ManyToMany field based on a Foreign key value in Django Admin Panel?
I am making a Django app for multiple choice question-answer exam. I have created a Subject, Question and Exam model as below. class Subject(models.Model): subject_name = models.CharField(max_length=200, blank=False) subject_code = models.IntegerField(blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) question_name = models.CharField(max_length=200,null=True) class Exam(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) questions = models.ManyToManyField(Question) date_of_exam = models.DateField(blank=False) users = models.ManyToManyField(CustomUser) Here in Question I am connecting subject by Foreign Key relation. In Exam I have subject as Foreign key and questions as ManyToMany relation from Question model. I want to create exam from admin panel. I want that when I select a subject only the questions of that subject should be displayed in the manytomany field to select from (As questions have foreign key of subject I think it should be possible). (I want to do this from admin panel only and not from a template.) How can I achieve this? Any suggetion is very much appreciated. Thanks in advance for the suggestions!! :) -
What should I know before shifting from Django to Wagtail
I am python programmer ,I know how django works but I'm trying to move to Wagtail. I seem not to understand about how Wagtail works , it mixes Models with templates and I also find out that it doesn't use any views ,this goes against how django works. Can you please explain to me what is a Wagtail Page exactly. I know its sort of a model but I don't seem to understand how it works. I would also like to know how do I get to use Wagtail Pages to render different data depending on data in the database lets say images of Users in the database. Also ,do I have to create a Page for everything eg If I want to create a User Model or Profile Model ,does it have to be a Page also. Please Help. I tried to actually to use Wagtail docs to create a web app but I don't seem to be in control .Wagtail doesn't have an views so i don't know how i can handle the requests in my own way then send the response of my own ,lets say JSON data. -
FastAPI Endpoint List as parameter not working
I I want to create an endpoint that receives a list of strings, which will be called and used as assets in the endpoint function. The endpoint http://localhost:8000/api/v1/equipments works correctly. Debugging I have verified that enters in and executes perfectly the function. @equipments_router.get("/equipments", summary="Equipments data") def get_equipments(assets: List[str] = None, Authorization: str = Header(None)): However, I have seen that if I make a GET to http://localhost:8000/api/v1/equipments?assets=first&assets=second, the value of assets is None. I'm pretty sure that Authorization has no role to play in the problem. -
Sending Django Channels message from inside async_task
I am using Django-Q for some moderately long tasks and would like to send a message from within the task to an websocket connection that I have established with Django channels. I am able to send the message if the task is run synchronously, ie, by calling the function, or passing sync=True to async_task. I am relatively new to this, and was not able to find out why the message is never sent, when the task is being run asynchronously. Is this not possible to achieve, or what is it that I am missing? I am aware that I could use Celery for this, though I would prefer not to unless this cannot be done with Django-Q. Here is the setup: #views.py def testview(request, uuid): task_id = async_task(dummy_task, uuid) event_triger(uuid, task_id) # This message shows up. def event_triger(uuid, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( uuid, { 'type': 'send_message_to_frontend', 'message': message } ) def dummy_task(uuid): for i in range(3): event_triger(uuid, "") time.sleep(3) The consumers.py file has the following: class NotificationConsumer(WebsocketConsumer): def connect(self): self.uuid = self.scope["url_route"]["kwargs"]["uuid"] async_to_sync(self.channel_layer.group_add)( self.uuid, self.channel_name ) self.accept() self.send(text_data = json.dumps({ "type": "est", "msg": self.uuid, "channel": self.channel_name })) def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.uuid, self.channel_name ) print("DISCONNECED CODE: ",code) def send_message_to_frontend(self,event): … -
How to Set Responses Media Type to application/octet-stream in drf-spectacular?
I am currently using drf-spectacular for schema generation in my Django project. I need to set the media type of the responses to application/octet-stream in the @extend_schema decorator, but I am not sure how to do this. Could anyone provide guidance or examples on how to achieve this? Thank you in advance! paths: /file-download: get: summary: Download a file description: This API endpoint allows users to download a binary file. responses: '200': description: File downloaded successfully content: application/octet-stream: schema: type: string format: binary description: Binary file Looks like this -
Relation does not exist error when overriding get_queryset method of models.Manager
I have a model for storing music and it has last_queried_at field that is used for deleting the music object if not queried for a month. class CustomManager(models.Manager): use_in_migrations = True def get_queryset(self): queryset = super().get_queryset() queryset.update(last_queried_at=timezone.now()) return queryset class Music(models.Model): file = models.FileField(upload_to="music/") created_at = models.DateTimeField(auto_now_add=True) last_queried_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( User, models.SET_NULL, null=True, blank=True, related_name="music", ) objects = CustomManager() When I try to make migrations it throws an error django.db.utils.ProgrammingError: relation "app_music" does not exist LINE 1: UPDATE "app_music" SET "last_queried_at" = '2... I would appreciate if anyone could help me figure out how to solve this problem I tried to use django's makemigrations command and threw an error. I was expecting it to create migrations. -
Django - Site requested, but not rendered
I tied to create something with Django, but I currently suffer from a problem with the return statement. It doesn't work. Here is my code: ` def acc_settings(request): if request.method == "POST": # Extract JSON dictionary from request dict = json.loads(request.body.decode("utf-8")) if dict["request"] == "user_data_change": request.user.first_name = dict["firstname"] request.user.last_name = dict["lastname"] request.user.username = dict["email"] request.user.email = dict["email"] request.user.save() return redirect("/") if dict["request"] == "delete_account": print("Account deletion requested!") try: # Delete all models assigned to this user bgmodel = dashModels.diabetesData.objects.filter(user=helpers.key) profilemodel = models.userProfile.objects.filter(user=helpers.key) usermodel = User.objects.get(username = request.user.email) bgmodel.delete() profilemodel.delete() logout(request) usermodel.delete() return redirect("/") except: return redirect("/") if dict["request"] == "renew_keyfile": print("Keyfile will be renewed!") # Generate a new private key for the user key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096) uid = pgpy.PGPUID.new('{} {}'.format(request.user.first_name, request.user.last_name), email=request.user.email) key.add_uid(uid, usage={KeyFlags.Sign}, hashes=[HashAlgorithm.SHA256], ciphers=[SymmetricKeyAlgorithm.AES256], compression=[CompressionAlgorithm.Uncompressed], ) profilemodel = models.userProfile.objects.get(user=helpers.key) bgmodel = dashModels.diabetesData.objects.get(user=helpers.key) bgmodel.user = key profilemodel.user = key bgmodel.save() profilemodel.save() response = HttpResponse(key, content_type='multipart/signed') response['Content-Disposition'] = 'attachment; filename="new_key.asc"' logout(request) return response context = { "hostname": helpers.hostname, "firstname": request.user.first_name, "lastname": request.user.last_name, "email": request.user.email, } template = TemplateResponse(request, "settings.html", context) return template.render()` So, the 'return redirect("/")' does work, in the console I can see the request for my index site. But the index site is not rendered! Do you … -
there is error occur when i work with SQL
"The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'New York' that does not have a corresponding value in flights_airport.id. " how to solve this problem i try to migrate the table but does't work -
on Django admin panal DetailsView can I do CRUD Operation?
I have django admin panal custom page. where I am displaying report of models. I want to apply crud on the report itself, but I don't know how. class StudentView(DetailView): template_name = 'admin/Student/student/details.html' model = Student def get_context_data(self, **kwargs): student = super().get_context_data(**kwargs)['object'] address_details = AddressDetails.objects.filter(student=student) educations = Education.objects.filter(student=student) kwargs['educations'] = educations print(self.request) if self.request.method == "POST": action = self.request.POST.get('action', '') student_form = StudentUpdateForm(self.request.POST, instance=student) if student_form.is_valid(): student_form.save() return HttpResponseRedirect(reverse('student_detail', args=[student.pk])) return { **super().get_context_data(**kwargs), **admin.site.each_context(self.request), "opts": self.model._meta, } I tried this but it return 405 status code. -
SMTPServerDisconnected("Connection unexpectedly closed") on django
In my Django application, I'm trying to send emails via SMTP. This is my configuration in the settings: EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your_email@gmail.com' EMAIL_HOST_PASSWORD = 'your_password' DEFAULT_FROM_EMAIL = 'your_email@gmail.com' However, I'm encountering an exception that says SMTPServerDisconnected("Connection unexpectedly closed"), and I'm not sure why. I've tried changing the backend and the port, but it still doesn't work. What could be causing this issue, and how can I resolve it? -
There is always that one celery worker process, can't use kill command because the PID is constantly changing
I'm in the process of developing a project and I'm working on implementing background tasks and notifications for user feedback. I'm using Django in conjunction with Celery for task management and Redis as a message broker. Currently, I can successfully execute background tasks, but I've encountered an issue when attempting to gracefully stop the Celery worker and exit Redis. Here's my terminal output: ps aux | grep 'celery worker' aysegul 2577 0.0 0.0 408102576 1072 s001 R+ 11:35AM 0:00.00 grep celery worker Then; sudo kill -9 2577 Password: kill: 2577: No such process Then I tried: celery -A request_handler.celery control shutdown Last command gave me connection errors caused by multiple sources: redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused. I came across this command but it didn't work neither: ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9 kill: 2713: No such process I'm somewhat puzzled by this situation and wonder if this lingering process is necessary. I've even restarted my computer, yet the issue persists since yesterday. Could you kindly provide insight into the purpose of this lingering process and whether it's a matter that requires attention? Thank you. -
Django: how to optimize querying the database?
My models: class Company(models.Model): code = models.BigIntegerField(primary_key=True) def __str__(self): related_data = self.relateddata_set.all() tickers = ", ".join(related_data.values_list("ticker", flat=True)) titles = set(related_data.values_list("title", flat=True)) return f"{tickers} - {titles.pop()} - Code {self.code}" class RelatedData(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) ticker = models.CharField(max_length=8, null=False, blank=False, db_index=True) title = models.TextField(default="") search_vector_title = SearchVectorField(null=True) class Meta: indexes = [ GinIndex( OpClass(Upper("ticker"), name="gin_trgm_ops"), name="ticker_gin_idx", ), GinIndex(fields=["search_vector_title"]), ] I often perform the following search: search_input = "Some_input" for item in Company.objects.filter( Q(relateddata__ticker__icontains=search_input) | Q(relateddata__search_vector_title=search_input) ).distinct(): print(item) I can't have everything in Company model because companies may have several instances of RelatedData. Questions: How to optimize the __str__ method of Company model? Is it possible to improve the efficiency of search? How? -
Ngrok free domain setup
I am just getting started on using ngrok I have created an app/website on Django and trying to test it using ngrok So far the process has been ngrok config add-authtoken ngrok http 8000 Session Status online Account XXXXXXX (Plan: Free) Version 2.3.41 Region United States (us) Web Interface http://127.0.0.1:4040 Forwarding http://<temp-name>.ngrok-free.app -> http://localhost:8000 Forwarding https://<temp-name>.ngrok-free.app -> http://localhost:8000 Connections ttl opn rt1 rt5 p50 p90 0 0 0.00 0.00 0.00 0.00 where I use https://< temp-name >.ngrok-free.app.ngrok-free.app for my testing Through the Domains option in the website I have got a free domain thats <some-free-name>.ngrok-free.app how do I setup/run so that ngrok will use this domain, which will greatly help me in the process of testing Apricate the help -
Challenges Encountered in Retrieving Information Using Token Authentication in a Django REST API
Challenges Encountered in Retrieving Information Using Token Authentication in a Django REST API Experiencing Difficulty Performing GET and POST Operations with Token Authentication for Data Retrieval This is my views. from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import Student from .serlizer import StudentSerlilizer from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated class StudentInfo(APIView): authentication_classes = [TokenAuthentication] # Apply TokenAuthentication permission_classes = [IsAuthenticated] # Apply IsAuthenticatedOrReadOnly permission def get(self, request, format=None): stu = Student.objects.all() serlizer = StudentSerlilizer(stu,many=True) return Response(serlizer.data) def post(self,request,format=None): request_data = request.data serlizer = StudentSerlilizer(data=request_data) if serlizer.is_valid(): serlizer.save() msg = {'msg':'Your data has been saved'} return Response(msg) msg = {'msg':serlizer.errors} return Response(msg,status.HTTP_400_BAD_REQUEST) And this is my urls:- from django.urls import path from . import views # from rest_framework.authtoken.views import obtain_auth_token from rest_framework_simplejwt.views import TokenObtainPairView,TokenRefreshView,TokenVerifyView urlpatterns = [ # path('authtoken/',obtain_auth_token), path('gettoken/',TokenObtainPairView.as_view(),name="get_token"), path('refreshtoken/',TokenRefreshView.as_view(),name="refresh_token"), path('verifytoken/',TokenVerifyView.as_view(),name="verify_token"), path('studentinfo/',views.StudentInfo.as_view(),name="studentlist"), path('studentinfo/<int:pk>/',views.StudentRUD.as_view(),name="StudentRUD") ] When i tried to get the values by using Tokenauth, i'm getting this error: { "detail": "Authentication credentials were not provided." } This is how i tried to Get the values:- http GET http://127.0.0.1:8000/studentinfo/ 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjk1MzYxMTk5LCJpYXQiOjE2OTUzNjA4OTksImp0aSI6ImY1ODY1MWE5NjMwNTRhMDA4MzA6NTFmZTJmMzU1MTgwIiwidXNlcl9pZCI6MX0.GmlHfKR59s6SUDEI_ZHardNDDH7T_lEWYJlIBxc3LmI' HTTP/1.1 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Length: 58 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Fri, … -
Using models package to manage multiple models in Django but migration cannot be generated
I followed the steps in the documentation but couldn't succeed. What do I need to do to generate migration files? I try to put all models in models.py and it can be generated apartment/models/__init__.py: from .water_bill import WaterBill from .electricity_bill import ElectricityBill Directory Structure apartment/ views.py __init__.py models/ __init__.py electricity_bill.py water_bill.py Script executed python manage.py makemigrations apartment then show “No changes detected in app 'apartment'" -
how to resolve import error for package utils.stellar_utils in python django
Am recieving the follwong error #views.py import "utils.stellar_utils " could not be resolved but the i have just installed the lest version of the sdk here is a snap short of my view.py from stellar_sdk import Keypair from django.conf import settings from utils.stellar_utils import server def send_transaction(request): # your send transaction logic here source_keypair = Keypair.from_secret(request.user.secret_key) destination_public_key = request.POST['destination_public_key'] amount = request.POST['amount'] asset = Asset.native() transaction = ( TransactionBuilder( source_account=server.load_account(source_keypair.public_key), network_passphrase=settings.STELLAR_NETWORK_PASSPHRASE, base_fee=server.fetch_base_fee(), ) .append_payment_op(destination_public_key, amount, asset) .set_timeout(30) .build() ) transaction.sign(source_keypair) response = server.submit_transaction(transaction) and below is my requirements.txt aiohttp==3.8.5 aiohttp-sse-client==0.2.1 aiosignal==1.3.1 asgiref==3.7.2 async-timeout==4.0.3 attrs==23.1.0 certifi==2023.7.22 cffi==1.15.1 charset-normalizer==3.2.0 Django==4.2.4 frozenlist==1.4.0 idna==3.4 mnemonic==0.20 multidict==6.0.4 psycopg2-binary==2.9.7 pycparser==2.21 PyNaCl==1.5.0 requests==2.31.0 six==1.16.0 sqlparse==0.4.4 stellar-base-sseclient==0.0.21 stellar-sdk==8.2.1 toml==0.10.2 typeguard==2.13.3 tzdata==2023.3 urllib3==2.0.5 yarl==1.9.2 i am using the latest version os stella skk with all the dependencies installed