Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
`pip install` Gives Error on Some Packages on cpanel
Some packages give errors when I try to install them using pip install. This is the error when I try to install djoser, but some other packages give this error as well: ps: im trying to install libraries in a virtual envirement on cpanel. $ pip install djoser==2.1.0 Collecting djoser==2.1.0 Using cached djoser-2.1.0-py3-none-any.whl (46 kB) Collecting social-auth-app-django<5.0.0,>=4.0.0 Using cached social_auth_app_django-4.0.0-py3-none-any.whl (24 kB) Collecting django-templated-mail<2.0.0,>=1.1.1 Using cached django_templated_mail-1.1.1-py3-none-any.whl (4.7 kB) Collecting djangorestframework-simplejwt<5.0.0,>=4.3.0 Using cached djangorestframework_simplejwt-4.8.0-py3-none-any.whl (70 kB) Requirement already satisfied: asgiref<4.0.0,>=3.2.10 in /home/qcmouhxi/virtualenv/milestone2/3.9/lib/python3.9/site-packages (from djoser==2.1.0) (3.5.2) Collecting coreapi<3.0.0,>=2.3.3 Using cached coreapi-2.3.3-py2.py3-none-any.whl (25 kB) Collecting itypes Using cached itypes-1.2.0-py2.py3-none-any.whl (4.8 kB) Collecting uritemplate Using cached uritemplate-4.1.1-py2.py3-none-any.whl (10 kB) Collecting requests Using cached requests-2.28.1-py3-none-any.whl (62 kB) Collecting coreschema Using cached coreschema-0.0.4.tar.gz (10 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: django in /home/qcmouhxi/virtualenv/milestone2/3.9/lib/python3.9/site-packages (from djangorestframework-simplejwt<5.0.0,>=4.3.0->djoser==2.1.0) (4.1.1) Collecting pyjwt<3,>=2 Using cached PyJWT-2.5.0-py3-none-any.whl (20 kB) Collecting djangorestframework Using cached djangorestframework-3.13.1-py3-none-any.whl (958 kB) Collecting social-auth-core>=3.3.0 Using cached social_auth_core-4.3.0-py3-none-any.whl (343 kB) Collecting six Using cached six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting oauthlib>=1.0.3 Using cached oauthlib-3.2.1-py3-none-any.whl (151 kB) Collecting python3-openid>=3.0.10 Using cached python3_openid-3.2.0-py3-none-any.whl (133 kB) Collecting defusedxml>=0.5.0rc1 Using cached defusedxml-0.7.1-py2.py3-none-any.whl (25 kB) Collecting requests-oauthlib>=0.6.1 Downloading requests_oauthlib-1.3.1-py2.py3-none-any.whl (23 kB) Collecting cryptography>=1.4 Using cached cryptography-38.0.1.tar.gz (599 kB) Installing build dependencies ... … -
Why does Express serve static files using middleware instead of other ways?
I'm a Django developer. In Django we use an application to serve staticfiles. Then I found that in Express we use a middleware. Could anyone explain what are the pros and cons of both methods? -
How to avoid insertion of new row of same data in Mysql database when i press next or save button of forms in Django
My project has 4 forms in which i have a back,next and save button at the bottom. Everytime I press next or save button, a new row is added in database of the same data. How can I avoid that and can edit/update the same row when I changed the data in form. admission is 1st form personalinfo is 2nd form academic is 3rd form achievements is the 4th form Here is my views.py I am only pasting the code for 1st form as rest all are the same from django.http import HttpResponse from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import logout from django.contrib.auth.models import User from django.conf import settings from django.shortcuts import redirect from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from usersite.forms import admissionForm,personalinfoForm,academicForm from usersite.models import admission as admission2 from usersite.models import personalinfo as personalinfo2 from usersite.models import academic as academic2 from django.contrib.auth.models import User @login_required def admission(request): if request.user.is_authenticated: user = request.user print(user) form = admissionForm() #admission1 = admission2.objects.get(user=2) try: admission1 = admission2.objects.filter(user=user).latest('pk') except: admission1 = admission2.objects.filter(user=user) #admission1 = admission2.objects.all() return render(request,'admission.html', context={'form': form , 'admission1': admission1}) #return render(request,'admission.html', context={'form': form) else: return redirect('unauthorised') @login_required def submit_admission(request): if request.user.is_authenticated: user = request.user … -
I am trying to implement individual upload cancel using blueimp-jquery-fileupload in Django
have been trying to implement individual image file upload using blueimp_jquery_fileUpload. How can i get this done?. If i am to upload a single image, and cancel it, it does get cancelled however if its multiple images, it all cancels out. This is my template code: {% extends 'shared/base_profile.html'%} {% load static %} {% load crispy_forms_tags %} {% block title %} Upload Property Pictures {% endblock title %} {% block content %} <div class="row"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <!-- {% if form %} --> <!-- {{ form|crispy }} --> <!-- <div class="col"> {{ form.pictures }} </div> --> <!-- {% endif %} --> <div class="form-group"> <label>Select file to upload.</label> <input type="file" class="form-control" id="fileupload" placeholder="Select file"> </div> <input type="submit" value="Upload" id="submit" class="btn btn-success"> </form> <div id="uploaded_files"></div> <!-- <div class="col-sm-9 m-auto"> </div> --> </div> {% endblock content %} This is my javaScript code: 'use strict'; $(function (){ function previewDataDetail(img,imgSize,imgName){ return ` <div class="col-sm-12" id="progress_img"> <img src="${img}"> <span>${imgSize}</span> <div class="value_hold" style="display:none"> <p id="preview_name">${imgName}</p> </div> <button class="btn btn-dark">Cancel</button> <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" id="progress_bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style= "width:100%"></div> </div> </div> ` } function abortUpload(e){ e.preventDefault(); var template = $(e.currentTarget).closest( '#progress_img' ), data = template.data('data') || {}; data.context = data.context … -
django-filters and HTMX: Trigger a Filter on Multiple Views at Once
I have a simple app where I want to have a single filter dynamically update the queryset in two different Views at the same time. In this example, the user can filter based on city/country/continent and I'd like to dynamically update (1) the table showing the relevant objects in the model, and (2) the leaflet map to plot the points. I think the main issue here is that I need to trigger an update to the filter queryset on multiple 'views' at the same time and not sure how to structure my project to achieve that. Or if that's the right way to think about the problem. I'm trying to have a filter work with{% for city in cityFilterResults %} iterator in two different views at the same time. How can I achieve having two different views update based on a Filter using HTMX? index.html: (Note: My expected behaviour works if I switch the hx-get URL between either the table or the map. But they don't filter together and this is the issue I'm stuck on.) <body> <h3>Filter Controls:</h3><br> <form hx-get="{% url '_city_table' %}" hx-target="#cityTable"> <!-- <form hx-get="{% url '_leaflet' %}" hx-target="#markers"> --> {% csrf_token %} {{ cityFilterForm.form.as_p }} <button … -
djangorestframework does not work when django channel is applied :((
I am developing a chatting app that allows social login. While developing all restapi functions, including social login functions, and developing chat customers using channel libraries, there was a problem with social login. This code is chatcustomer using websocketcunsumer. enter code hereimport json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import * class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name .... this is setting for channel INSTALLED_APPS = [ 'channels', ] ASGI_APPLICATION = 'project.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } routing.py in project root from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() application = get_default_application() routing.py in chatapp from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] this is social login views.py @api_view(['POST']) def authenticate_kakao(request): access_token = request.data["access_token"] code =request.data['code'] """ Email Request """ print("process1") profile_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={"Authorization": f"Bearer {access_token}"}) print("process2") profile_json = profile_request.json() kakao_account = profile_json.get('kakao_account') email = … -
Django get id from model
how can I get id from just created model so that it can be used in item_name column. I was thinking about sth like this: class Items(models.Model): item_id = models.AutoField(primary_key=True) item_name = models.CharField( max_length=100, default="Item #{}".format(item_id) ) -
Connection Error 111 Python Third party api hitting
I got error "Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f0adc106cc0>: Failed to establish a new connection: [Errno 111] Connection refused',)" on server but same code is working on local. But server give this error. I also try verify=True in requests.post() -
Django Autoslug raise ValueError("Cannot serialize function: lambda")
Am trying to create a custom slug for a blog post, and am using django AutoSlug to generate the slug automatically but am getting ths error. raise ValueError("Cannot serialize function: lambda") ValueError: Cannot serialize function: lambda This is my models.py from autoslug import AutoSlugField class Blog(models.Model): .... category = models.ForeignKey(Category, on_delete=models.CharField, null=True, blank=True) tag = models.ManyToManyField(Tag, blank=True) title = models.CharField(max_length=255) pub_date = models.DateTimeField(auto_now_add=True) slug = AutoSlugField(populate_from=lambda instance: instance.title, unique_with=['category', 'tag', 'pub_date__month'], slugify=lambda value: value.replace(' ', '-'), null=True ) ..... I used the example given in the documentation but still am getting the error. I know it can also be done as below in its simplest form slug = AutoSlugField(populate_from='title') -
I keep getting TemplateDoesNotEXist after running my local server, using Django 4.0.2 how do I fix it
TemplateDoesNotEXist at \ myapp1/dashboard.html Request Method: GET Request URL: http://127.0.0.1:8000/ Exception Type: TemplateDoesNotEXist Exception Value: myapp1/dashboard.html ........................... I've already edited my template dirs, registered my apps in installed apps Here are my views From django.shortcuts import render def dashboard(request): form = DweetForm return render(request, "myapp1/dashboard.html") ............................ My project directory is like this my_project | my_project | myapp1 | --pycache-- Migrations templates/myapp1/dashboard.html init admin apps forms models serializers test urls views .............................. I didn't use pycharm or any other IDE to start the project I created the file manually on my windows, for the templates I created a folder in the app directory and created a file using notepad and then I inserted the HTML file, yet I keep getting the errors, I'll really appreciate any assistance. -
Why using validators=[URLValidator] when defining a model CharField doesn't make it check for URL-validity upon saving the corresponding ModelForm?
app.models.py: from django.core.validators import URLValidator from django.db import models class Snapshot(models.Model): url = models.CharField(max_length=1999, validators=[URLValidator]) app.forms.py: from django import forms from .models import Snapshot class SnapshotForm(forms.ModelForm): class Meta: model = Snapshot fields = ('url',) app.views.py: from django.http import HttpResponse from .forms import SnapshotForm def index(request): snapshot_form = SnapshotForm(data={'url': 'not an URL!'}) if snapshot_form.is_valid(): snapshot_form.save() return HttpResponse("") Why does it save 'not an URL!' into DB, despite the fact that it ain't a valid URL?! What is the right way to incorporate URLValidator? -
"from django.shortcuts import render" gets me an error [duplicate]
I have a decent amount of experience with Django, but recently I opened one of my old Django projects and realized there was something wrong with it. I looked through the files and I found that there were red wavy lines under: from django.shortcuts import render, from django.views import View, indicating that there is an error. I did not change anything I do not know what caused it. When I run the server I also get an error saying "name 'request' is not defined". Please help, here is the code: from django.shortcuts import render from django.views import View class Index(View): def get(self, requst, *args, **kwargs): return render(request, 'landing/index.html') -
TypeError: AsyncConsumer.__call__() missing 1 required positional argument: 'send
Well I am using channels as WebSocket and redis as storage to build chat application in Django.so to accomplish connection between the websocketconsumer with asgi file. I am trying to run the django server on windows but I am getting the following error, help me. Error Exception inside application: AsyncConsumer.__call__() missing 1 required positional argument: 'send' Traceback (most recent call last): File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\asgiref\compatibility.py", line 34, in new_application return await instance(receive, send) TypeError: AsyncConsumer.__call__() missing 1 required positional argument: 'send' WebSocket DISCONNECT /ws/test/ [127.0.0.1:59461] asgi.py """ ASGI config for chatapp project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from django.urls import path from home.consumers import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chatapp.settings') application = get_asgi_application() ws_patterns = [ path('ws/test/',TestConsumer) ] application = ProtocolTypeRouter({ 'websocket' : URLRouter(ws_patterns) }) consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class TestConsumer ( WebsocketConsumer ) : def connect(self): self.room_name = "test_consumer" self.room_group_name="test_consumer_group" async_to_sync(self.channel_layer.group_add)( … -
Increment at reload Django
I want to increment NUM at every reload in Django. how to do it? here is my view. def home(request): num = 0 if request.method == "GET": num += 1 context = {'num': num} return render(request, 'home.html', context) and here is my template. <body> <h2>Increment at reload!</h2> <h5>{{num}}</h5> </body> -
How to insert and delete data from database Django?
I have built a Django site that has an interface to add and delete data from database. The next thing I have to do is to add and delete data on the same database from a python script. I don't have written down code yet. To do this I was thinking to use commands similar to python-mysql. How can I add on and delete from the database with the script? -
breakpoints on django-rest-framework project in vscode are not hit in debug mode
I have django-rest project on my vscode.The problem is that when I run the project in debug mode the breakpoints are not catched!!. I just get response without being stopped on that specific breakpoint. This is my launch.json file { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true } ] } BTW I send the requests by swagger! I have also tried postman and got the same result! (just got the response without the code being stopped on this view ) I send the requests to ManageUserView -
Django Rest Framework nested manytomany serializer
I have to models as below: class PositionModel(BaseModel): """ User Position/Designation Model """ name = models.CharField(max_length=255) class Meta: ordering = ["created_at"] def __str__(self): return f"{self.name}" class SuperiorModel(BaseModel): """ Super model for position """ position = models.OneToOneField(PositionModel, on_delete=models.CASCADE, related_name='position_superior') superior = models.ManyToManyField(PositionModel, blank=True) def __str__(self): return f'{self.position.name}' Signals: @receiver(post_save, sender=PositionModel) def create_position_instances(sender, instance, created, **kwargs): if created: SuperiorModel.objects.create( position=instance ) @receiver(post_save, sender=PositionModel) def save_position_instances(sender, instance, **kwargs): instance.position_superior.save() What I want here is to create position with superior model. My expected payload for post is this: { "name": "test position", "superior": [1,2] # <-- Could be empty array if there is no superior } So that when I creates a position the superior value could be created in the SuperiorModel. Also in the get method I want to get the data same as the payload. -
What is the use of creating multiple IAM users on AWS
What is the difference between root users and IAM users and for a software engineering department with multiple SWE, how should the manager handle AWS -
What is the best, cleanest and shortest way to check if a given value is valid URL when working with models?
I rather want to use Django's built-in functionalities as much as possible and avoid implementing stuff myself as much as possible! Why doesn't the following code issue exceptions when given a non-URL value? models.py: from django.core.validators import URLValidator from django.db import models class Snapshot(models.Model): url = models.URLField(validators=[URLValidator]) views.py: from django.http import HttpResponse from .models import Snapshot def index(request): a = Snapshot(url='gott ist tot') a.save() -
ValueError: Cannot assign "username'": "Comment.created_by" must be a "User" instance
I'm trying to create a comment to a model and I'm getting a ValueError when i try to call the User model. I don't know what I am doing wrong, here are my code snippets models.py from django.contrib.auth.models import User class Comment(models.Model): ***** ***** created_by = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE) views.py @api_view(['POST']) def add_comment(request, course_slug, lesson_slug): data = request.data name = data.get('name') content = data.get('content') course = Course.objects.get(slug=course_slug) lesson = Lesson.objects.get(slug=lesson_slug) comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=request.user.username) return Response({'message': 'Comment added successfully'}) urls.py urlpatterns = [ **** **** path('<slug:course_slug>/<slug:lesson_slug>/', views.add_comment), ] [17/Sep/2022 12:37:52] "OPTIONS /api/v1/courses/python-programming/lesson-one/ HTTP/1.1" 200 0 Internal Server Error: /api/v1/courses/python-programming/lesson-one/ Traceback (most recent call last): File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch … -
ModuleNotFoundError: No module named 'madlibs_project' django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I have tried all the solutions I have seen but I am still having the same error. I am trying to populate my database with some fake data generated in the file below: population_madlibs_app.py import random from madlibs_app.models import User from faker import Faker import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'madlibs_project.settings') django.setup() fakegen = Faker() fname = ['Charles', 'Stephen', 'Mike', 'Cornell', 'John', 'Yemi', 'Tomiwa'] lname = ['Nurudeen', 'Ayotunde', 'Ajiteru', 'Kolade', 'Babatunde', 'Ifeanyi', 'Ola'] email_client = ['yahoo.com', 'gmail.com', 'outlook.com'] def add_user(): fname = random.choice(fname) lname = random.choice(lname) emailed = '{}.{}@{}'.format(fname, lname, random.choice(email_client)) ur = User.objects.get_or_create( first_name=fname, last_name=lname, email=emailed)[0] ur.save() return ur def populate(n=1): for entry in range(n): create_user = add_user() if __name__ == '__main__': print('Processing...') populate(10) print('Succesfully created!') -
How to check for a specific attribute of the object referenced by foreign key in Django
Newbie here, forgive me if it's an easily solveable question. So, I have a UserProfile model(one to one field related to base user) and posts and comments model. Both posts and comments are related to their author by a foreign key. Both posts and comments have rating attribute(Int). For this example I'll talk about comments. My question is, how do I get all comment objects related to user by foreign key, and is it possible to not retrieve all comments themselves, but to retrieve only their rating values? My UserProfile model looks like this class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) birthdate = models.DateField post_rating = models.IntegerField(default=0) comment_rating = models.IntegerField(default=0) def update_post_rating(self): pass def update_comment_rating(self): pass My Comment model looks like this class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.SET('DELETED')) post = models.ForeignKey(Post, on_delete=models.CASCADE) rating = models.IntegerField(default=0) content = models.TextField date = models.DateField(auto_now_add=True) def like(self): self.rating = + 1 self.save() def dislike(self): self.rating = - 1 self.save() -
Save content of zip file in django
Good Day, I would like to save the content of the zip file. My code works, but they save only the filename and not the content or actual files neither in the database nor the project. I need to save in the database the content of each file. Can someone please help me to fix my error? My code looks like this: uploaded_file, = request.FILES.getlist('document[]') with zipfile.ZipFile(uploaded_file.file, mode="r") as archive: for zippedFileName in archive.namelist(): newZipFile = UploadedFile(document= zippedFileName) newZipFile.user= request.user files = newZipFile.save() success=True return render(request, 'uploader/index.html', {'files': [uploaded_file]}) -
In django how to delete the images which are not in databases?
I have created a blog website in Django. I have posted multiple articles on the website. After deleting the article, the article gets deleted but the media files are not removed. I want to delete all media files which are not referred to the articles. I know, I can create Django post-delete signal and delete media files from there. But it will applicable for only future use. I want to delete previous media files which are not in my database. -
How to use vue js inside django template? Is it problem with Vue js only?
In my index.html i have following code: <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app">{{ message }}</div> <script> const { createApp } = Vue createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app') </script> when i open in browser there is error in console [Vue warn]: Component is missing template or render function. at