Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Redirect User to their corresponding View and Templates in Django
I have 2 different user types at the moment. After a successful login, I want the user to be redirected to its specific dashboard. Depending on the user, it is possible to load in a different template in a generic view Class: if request.user.user_type == 1: # load template A if request.user.user_type == 2: # load template B But I want to have two separate View Classes for each Type. How can I achieve this? -
How to render student tuition fees payment records on template in django
I have some models for student fees payments and would like to render the following based on the models: Classes, No of students in each class, Amount Payable in each class, & Total amount paid in each class My models are as below: for Classroom setup class ClassArmSetup(models.Model): SECTION = ( ('Primary', 'Primary'), ('Secondary', 'Secondary'), ('Creche', 'Creche'), ('Nursery', 'Nursery'), ) id = models.AutoField(primary_key='True') name = models.CharField(max_length=255, unique=True) short_name = models.CharField( 'Classroom Short Form', max_length=20, blank=True ) academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE, null=True) term = models.ForeignKey(TermSetup, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) objects = models.Manager() def classroom_code(self): if not self.code: return "" return self.code class StudentClassRegistration(models.Model): STATUS = [ ('Active', 'Active'), ('Withdrawn', 'Withdrawn'), ('Completed', 'Completed'), ] chosen_class = models.ForeignKey( ClassArmSetup, related_name='admission_students', on_delete=models.CASCADE, blank=True, null=True ) admitted = models.BooleanField(default=False) admission_date = models.DateField(blank=True, null=True) migration_status = models.CharField( max_length=255, blank=True, null=True, default='Active' ) status = models.TextField(choices=STATUS, verbose_name='Status', null=True) rejected = models.BooleanField(default=False) assigned_as_student = models.BooleanField(default=False) academic_year =models.ForeignKey(AcademicYear, on_delete=models.CASCADE, null=True, verbose_name='Session') term =models.ForeignKey(TermSetup, on_delete=models.CASCADE, null=True, verbose_name='Term') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.lastname) + ' ' + str(self.firstname) + ' ' + str(self.othername) class Meta: ordering = ['chosen_class'] class TuitionFeesSetup(models.Model): year= models.ForeignKey(AcademicYear, on_delete=models.CASCADE, null=True, verbose_name="Session") term= models.ForeignKey(TermSetup, on_delete=models.CASCADE, null=True, verbose_name="Term") … -
How can i show multiple tag from tag model in django
I'm beginner in Django/Python and I need to create a multiple select form. I know it's easy but I can't find any example. i use django-taggit.i want to select multiple tag in tag form with search engine . here is my forms.py class QuestionForm(forms.ModelForm): test = Tag.objects.order_by('name') for tag in test: print(tag) tags = forms.ModelMultipleChoiceField(label='Tags', queryset=Tag.objects.order_by('name'),widget=forms.SelectMultiple) class Meta: model = Question fields = ['title', 'content','anonymous',"tags"] widgets = { 'title' : forms.TextInput(attrs={'class':'form-control form-control form-control-lg '}), 'content' : forms.Textarea(attrs={'class':'form-control'}), # 'tags' : forms.Textarea(attrs={'class':'form-control'}), } form.html {{form.tags}} i want this -
Django post_save signal not working properly
In my models.py file, I have a class named OrderPayment, now whenever I create a new object of OrderPayment, I want to also create a Transaction object. Am trying to do this with post_save signal but it not working. Below is how the code looks @receiver(post_save, sender=OrderPayment) def orderpayment_setup(sender, instance, **kwargs): print(instance.order.dispatch_rider.company) print(instance) wt = Transaction.objects.create( wallet=Wallet.objects.get(user=instance.order.dispatch_rider.company), amount=instance.amount, description="Dispatch Order", status='success', transaction_type='deposit' ) print(wt) The orderpayment_setup function gets triggered but the Transaction object is not created. I also sees the first two print statement but I don't see the last one. I don't know what I'm not doing right -
How to load json, pickle and h5 files into views.py file in Python Django?
I am trying to display a chatbot that I created on a django site. So I need to load some training data (json, pickle and h5 files) into views.py file. But when I run the server it says: FileNotFoundError: [Errno 2] No such file or directory: 'mysite/polls/intents.json' even though views.py and intents.json are in the same folder. Do you have any suggestions? Here's the code from views.py: from django.shortcuts import render from django.http import HttpResponse import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np from keras.models import load_model import json import random intents = json.loads(open('mysite/polls/intents.json').read()) model = load_model('mysite/polls/chatbot_model.h5') words = pickle.load(open('mysite/polls/words.pkl','rb')) classes = pickle.load(open('mysite/polls/classes.pkl','rb')) # Create your views here. def index(request): def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] return sentence_words # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence def bow(sentence, words, show_details=True): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words - matrix of N words, vocabulary matrix bag = [0]*len(words) for s in sentence_words: for i,w in enumerate(words): if w == s: # assign 1 if current word is in the vocabulary position bag[i] … -
I can't add data to the database using a Django form
If I leave everything as it is, then an error pops up when submitting the form "Select a valid choice. That choice is not one of the available choices." And, for example, if in forms.py I change Product.objects.values_list('product_name') to a class with one field, for example, Category.objects.all(), the form is submitted without errors But I need exactly the first option, where I select a specific class field (product_name), so that there are the necessary options in the form in the select... Who knows how to solve this problem? models.py: class Account(models.Model): uploader_mail = models.EmailField(max_length=254) body = models.CharField(max_length=4096) product = models.ForeignKey('Product', on_delete=models.PROTECT) class Product(models.Model): product_name = models.CharField(max_length=400) description = models.CharField(max_length=4096) price = models.DecimalField(max_digits=8, decimal_places=2) geo = models.CharField(max_length=2) product_logo = models.ImageField(upload_to='img/logos', blank=True) category = models.ForeignKey('Category', on_delete=models.PROTECT) def __str__(self): return self.product_name, self.description, self.geo, class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category forms.py: class AddForm(forms.Form): uploader_mail = forms.EmailField( label='Owner mail', initial='test@test.test', widget=forms.EmailInput(attrs={'class': 'form-control'})) body = forms.CharField( label='Data line by line', widget=forms.Textarea(attrs={'class': 'form-control','wrap': "off", })) category = forms.ModelChoiceField( queryset=Product.objects.values_list('product_name', flat=True), label='Category', empty_label=None, widget=forms.Select(attrs={'class': 'form-select'})) views.py: def edit(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): print(form.cleaned_data) else: form = AddForm() editable = {'form': form, } return render(request, 'goods_list/edit.html', editable) -
ajax not work when click open in new window after right click in django template
i created a link with ajax this is a html coded: <a id="post_click" href="{{ post.online_url}}" rel="nofollow"> <button class="w-100 " type="button" name="button"> <span class="">link</span> </button> </a> and this is ajax : $(function () { $('#post_click').on('click', function () { var Status = $(this).val(); var id = {{post.id}} $.ajax({ url: "/post-click/" + id, data: { }, dataType : 'json' }); }); }); if i push left click ajax work fine in sever side, but when i push left right click and choose open in new window ajax doesnt work -
Django Problem : I want to see reverse order in django admin many to many field
class Question(models.Model): id = models.AutoField question = models.CharField(max_length=100) answer = models.CharField(max_length=100) class TestSeries(models.Model): id = models.AutoField quiz_name = models.CharField(max_length=100) all_question=models.ManyToManyField(MyQuestion) This is my model.py code when i open my admin panel on test series previous added are shown in order : Oldest first i want to see that in newest first manner . please tell me , how can i do that -
Does anyone know how to deploy Redis as cache along Postgres and Digital Ocean App for Django app?
I deployed Django's app with Digital Ocean App service. This is easy and quick without me having to deal with setting up a Ubuntu Droplet or anything like that for Django. I also got Postgres as the main database for the Django app. The problem is when I also set up Redis Managed Database as a cache server for my app, using VPC network connection such as rediss://private-location-on-digital-ocean:port# (also added the Django App and my own IP address as trusted source) - (also installed django-redis using pip) - to my chagrin I either got Internal Server Error or some vague error said that I have to check the log. By the way I did update the requirements.txt to make sure all packages were installed for Redis to run properly with Django app. Also, I set up the Redis as the CACHE backend in settings.py. The only thing I see is that Postgres is being listed as a component for my Django app and Redis DB is not but it's using the same VPC that my Django app is using. What could be the problem that I missed in order for me to get Redis to act as a cache server … -
What is better ways to store id after successful login?
For my project, I am using Angular + Django Rest Framework. I am storing id in local storage (using Angular). But I want to learn other ways to do it. Can we use (In Django) Session Cache How? -
How to detect enters from text and display on html page using html javascript
I have below data from backend(django) "Innovator in Analytical Process & Environmental Instrumentation\r\nT&C:\r\nPayment: 100% advance against PI prior to Dispatch.\r\nPrices: Ex-works Mumbai.\r\nInstl. and Comm. - Inclusive for Mumbai region. For outstation, Travel, Food\r\nand Lodging charges extra.\r\nFreight: In your scope.\r\nGST: Extra @ 18%.\r\nDelivery: 2-3 weeks after receipt of advance payment.\r\nWarranty: 1 Year from the date of installation.\r\nCustomer's scope:\r\n1. All kinds of Civil/Electrical/Plumbing works.\r\n2. Construction or Modification of the Line.\r\n3. Tubing for Sample inlet and outlet with tapping on the line with PU push\r\nconnector.\r\n4. Electrical, LAN and signal cables - Supply and laying.\r\n5. Online or Offline UPS - 1 KVA.\r\n6. SIM/LAN/Wifi/Dongle for connectivity.\r\n7. DM Water and Sulphuric Acid.\r\n8. Mounting of Flow Meter or 3-way valve.\r\n9. Lab Test Reports." Its have enters in the text I wish to show them on frontend in my this code : my text is getting from {{response.remarks}} <ul class="list list-unstyled mb-0 text-left"> <li><h6 class="my-1">Message Displayed </h6></li> <li>{{response.remarks}}</li> </ul> But its showing me like this But want them with enters how can I do this -
Access Postgres generate_series function via Django model syntax
I need to use Django Models to create roughly the following SQL: SELECT series AT TIME ZONE 'utc' AS forecast_hour, app_forecasts.inventory AS inventory FROM generate_series(DATE_TRUNC('hour', TIMESTAMP '2022-05-01 04:00:00+00:00'), DATE_TRUNC('hour', TIMESTAMP '2022-09-03 03:00:00+00:00'), '1 hour'::interval) series LEFT JOIN app_forecasts ON series = DATE_TRUNC('hour', app_forecasts.forecast_at) AT TIME ZONE 'utc' It would look something like: Forecast.objects.annotate(dates=Func(..., ..., Value('1 day'), function='generate_series'))