Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
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