Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load the display name when using `values()` of a `CharField` when using `models.TextChoices` in Django
I have a model that looks like this: models.py class Client(models.Model): class Status(models.TextChoices): CD = "CD", "Closed" UC = "UC", "Under Contract" status = models.CharField( max_length=2, choices=Status.choices, default=Pipeline.CD, ) and a view that looks like this: views.py class ClientsListView(generic.ListView): queryset = Client.objects.all() If I wanted to grab the display name of the status field, it would look something like this: clients.html {% for client in object_list %} {{ client.get_status_display }} {% endfor %} I want to change the ClientsListView class in views.py to use values() so I can limit the number of fields that are loaded so I changed it to this: class ClientsListView(generic.ListView): def get_context_data(self, **kwargs): context = super().get_context_data() context["clients"] = Clients.objects.all().values() return context But now I don't have access to the display name of status. How would I go about loading that into what is returned in values()? -
my registration view is not saving user data to database django python (only through admin panel)
I just started learning Django and got somewhat into it so far, but I've been stuck on why my views are not saving the model data successfully to the database (I'm using postgres). I found out that I'm able to add the models through the admin panel so I believe the fields are fine, I think it may be due to configuration? I'm not too confident on that, any help would be appreciated! Here's the project structure and code below Project Structure views.py from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from .forms import RegistrationForm, LoginForm from django.contrib import messages from django.http import * from .models import newUser, userEvents def registerView(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): # if the form is filled and data is valid if User.objects.filter(username=form.cleaned_data['user_name']).exists(): # Check if the record exists # in the DB already # redirects to the success page redirect('login/') else: createUser = newUser(user_name=form.cleaned_data['user_name'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email_address=form.cleaned_data['user_email'], date_of_birth=form.cleaned_data['date_of_birth']) createUser.save() # save the user to the database User.objects.create_user(createUser.user_name, createUser.email_address, form.cleaned_data['user_pass']) return render(request, 'login.html') # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm() # TODO: Create register.html template and then test! … -
Django tutorial, Page not found <int:question_id>
My views.py from django.http import HttpResponse, Http404 from django.shortcuts import render, get_object_or_404 from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) My urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('/', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ] When I going at 'http://127.0.0.1:8000/polls/1/' I receive 'Page not found' error but I definitely have this question_id, I can see this question_id in shell, it doesn't matter what ID I have write I always receive the same issue. -
Django session is lost after redirection to the same host
I've a class based django view where at some certain point I've some variables in the request.session, the user has been logged in in that view (just a few lines before), and I make a redirection to /sth/ . When the browser reaches /sth/, it has none of the previously set variables, they're gone, and no idea why. Checking the browser, the sessionid is different, but no idea why. Anyone would have an idea what can be problem, what to check? Thanks. -
Reverse for 'products_category' with keyword arguments '{'products_po_category': <QuerySet [<Product: Maybach>]>}' not found
Hi I need to implement the following: I have a form with a category selection, and based on the selected category, I need to redirect the user to a page with products for this category. URLS.PY from django.urls import path from first.views import productsHTML, productHTML, products_category urlpatterns = [ path("products_category", products_category, name = "products_category"), path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML"), ] VIEWS.PY from django.shortcuts import render, redirect from .models import Product from .forms import CategoryChoice def productsHTML(request): form = CategoryChoice(request.POST or None) if request.method == 'POST' and form.is_valid(): category = form.cleaned_data['category'] products_po_category = Product.objects.filter(category=category) return redirect('products_category', products_po_category=products_po_category, permanent=True) all_products = Product.objects.all() context = { 'form': form, 'products': all_products, } return render(request, "products.html", context) def products_category(request,products_po_category): context = { "products_po_category": products_po_category } return render(request, "product_category.html", context) Through form.cleaned_data['category'] I get data about the selected category and then, through Product.objects.filter(category=category) I get the objects of this category and after all this I redirect to the page with the products of this category, passing the list of objects of the selected categories. FORMS.PY from django import forms from .models import Product class CategoryChoice(forms.ModelForm): class Meta: model = Product fields = ('category',) widgets = { 'category': forms.Select(), } full text … -
Celery raises an Received unregistered task of type 'default.add error
I have a simple Django based Celery application. The folder structure is: celery_poc | |--db |----celery.py |----settings.py | |--demoapp |----apps.py |----models.py |----tasks.py The content of celery.py is : import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "db.settings") app = Celery("db") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() The content of settings.py is: INSTALLED_APPS = [ 'django_celery_results', 'demoapp', ] CELERY_BROKER_URL = "amqp://guest@localhost//" CELERY_RESULT_BACKEND = 'django-db' The content of tasks.py is: from celery import shared_task @shared_task def add(x, y): return x + y if __name__ == "__main__": add.delay(4, 4) I'm using RabbitMQ as the broker and Postgres as the results backend. When I ran tasks.py I get the following error from Celery: [2023-03-23 15:33:37,528: ERROR/MainProcess] Received unregistered task of type 'default.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[4, 4], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (81b) Thw full contents of the message headers: {'lang': 'py', 'task': 'default.add', 'id': '65488acd-5591-441a-b7d6-f5ff73a564e1', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '65488acd-5591-441a-b7d6-f5ff73a564e1', 'parent_id': None, 'argsrepr': '(4, 4)', 'kwargsrepr': '{}', … -
Django No records found on query
I'm trying to filter web search results of apartments on django3 but it doesn't matter what I put on the filters while filling the form, It shows the message "no records found" no mater how do I fill the form. The database is already populated. my views.py def apartments_list(request): name = request.GET.get('name') address = request.GET.get('address') status = request.GET.get('status') price_range = request.GET.get('price_range') no_of_person = request.GET.get('no_of_person') bed_type = request.GET.get('bed_type') query = Q() if name: query &= Q(title__icontains=name) if address: query &= Q(apartmentaddress__city__icontains=address) if no_of_person and no_of_person.isdigit(): query &= Q(persons=int(no_of_person)) if bed_type: query &= Q(bed=bed_type) if price_range: min_price = price_range.split('-')[0] max_price = price_range.split('-')[1] query &= Q(price__gte=min_price) query &= Q(price__lte=max_price) page = request.GET.get('page', 1) apartments = Apartment.objects.filter(query).order_by('price') paginator = Paginator(Apartment.objects.filter(query), 10) try: apartments = paginator.page(page) except PageNotAnInteger: apartments = paginator.page(1) except EmptyPage: apartments = paginator.page(paginator.num_pages) context = {} context['apartments'] = apartments context['name'] = name context['address'] = address context['no_of_person'] = no_of_person context['bed_type'] = bed_type context['price_range'] = price_range My models.py class Apartment(models.Model): APARTMENT_CHOICES = ( ("Available", "Available"), ("Booked", "Booked") ) clean_status = models.BooleanField(default=False) inspected_status = models.BooleanField(default=False) title = models.CharField(max_length=100) apartment_status = models.CharField( max_length=255, choices=APARTMENT_CHOICES, default='Available') services = models.CharField(max_length=255) capacity = models.IntegerField() bed = models.CharField(max_length=100) price = models.IntegerField() persons = models.IntegerField() category = models.ForeignKey(ApartmentCategory, on_delete=models.CASCADE) owner = … -
Better approach to serialize data that contains multiple related Models using Django Rest Framework
Background I am new to Django and DRF and I am currently writing a view that handles a GET request. The view will return a JSON that contains data associated with 5 related models. Here is a visualization of my database . And this is what I expect to get [ { "word": "hello", "entries": [ { "tag": null, "link": "", "value": "TEST" }, { "tag": null, "link": "", "value": "STUFF" } ] }, { "word": "Hello", "entries": [] } ] Problem My current approach is to use Django query to construct a self defined object and then define a DRF serializer to serialize it. The code looks like this # Inner Object class DetailEntry(): def __init__(self, tag, link, value): self.tag = tag self.link = link self.value = value # Outer Object class ReviewEntry(): def __init__(self, word, entries): self.word = word self.entries = entries class GetReview(APIView): def get(self, request, format=None): # get current user currentUser = User.objects.get(id=request.user.id) records = Record.objects.filter(user_id=currentUser) reviewEntries = [] for record in records: word = record.word_id quotes = Quote.objects.filter(record_id=record) detailEntries = [] for quote in quotes: tag = quote.tagAssignment_id link = quote.link value = quote.value detailEntries.append(DetailEntry(tag, link, value)) reviewEntries.append(ReviewEntry(word, detailEntries)) s = ReviewSerializer(reviewEntries, many=True) return Response(s.data) … -
How to send django template form to telegram bot in Django
I can't find way to send django template form to telegram bot in Django like send message to telegram bot via website! I don't know how to do this so i need help with explaining -
i have creating my app django but i can't use it
i'm using django i create my app with this commande django-admin startapp Bplan first it look everythings is right the new folder was added with all his fles i also add it in INSTALLED_APP [ ...'Bplan',...] but when i try to check the list off installed app with this commande : "python manage.py shell -c "from django.apps import apps; print([app.name for app in apps.get_app_configs()])" it show only the default app also when i try to migrate to database with python3 manage.py migrate every this look ok in the terminal but i cant see the new tables on my postgresql can you help me please -
django-fsm can't transition state
Why do I get the error below when I tried to do the transition? Is this a bug? Thanks >>> t = Task.objects.first() >>> t.state "(0, 'Open')" >>> t.to_in_progress() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dingli/projects/personal/django_history_fsm_guardian/lib/python3.11/site-packages/django_fsm/__init__.py", line 573, in _change_state return fsm_meta.field.change_state(instance, func, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/dingli/projects/personal/django_history_fsm_guardian/lib/python3.11/site-packages/django_fsm/__init__.py", line 339, in change_state raise TransitionNotAllowed( django_fsm.TransitionNotAllowed: Can't switch from state '(0, 'Open')' using method 'to_in_progress' Here is the model. STATES = ('Open', 'In Progress', 'Resolved', 'Re Opened', 'Closed') STATES = list(enumerate(STATES)) class Task(models.Model): title = models.CharField(max_length=100, null=False) description = models.TextField() state = FSMField(default=STATES[0], choices=STATES) def __str__(self): return f'{self.title}: {self.description}' @transition(field=state, source=['Open', 'Re Opened'], target='In Progress') def to_in_progress(self): pass @transition(field=state, source='In Progress', target='Resolved') def to_resolved(self): pass I also tried the following approach, but got the same error. @transition(field=state, source=[(0, 'Open'), (3, 'Re Opened')], target=(1, 'In Progress')) def to_in_progress_1(self): pass -
Trying to setup formsets for related models in Django (form_kwargs issues?)
Model code looks like this: class Question(models.Model): text = models.CharField(max_length=500) def __str__(self): return self.text def has_choices(self): return self.choices.exists() class Camp(models.Model): # Other attributes questions = models.ManyToManyField( Question, through="CampQuestion", related_name="camps" ) class CampQuestion(models.Model): camp = models.ForeignKey( Camp, on_delete=models.PROTECT, related_name="camp_questions" ) question = models.ForeignKey( Question, on_delete=models.PROTECT, related_name="camp_questions" ) def __str__(self): return f"{self.camp.name} - {self.question.text}" class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.PROTECT, related_name="choices" ) text = models.CharField(max_length=500) def __str__(self): return self.text class Answer(models.Model): registration = models.ForeignKey( "Registration", on_delete=models.PROTECT, related_name="answers" ) question = models.ForeignKey( Question, on_delete=models.PROTECT, related_name="answers" ) user_response = models.CharField(max_length=500, blank=True, null=True) user_choice = models.ForeignKey( Choice, on_delete=models.PROTECT, null=True, blank=True ) class Registration(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT) # Other attributes I'm trying to setup an Answer formset that contains 1 AnswerForm for every Question tied to a Camp - but I can't seem to make it happen. My AnswerForm looks like this (if a Question has Choice models we make it a Select - otherwise it's a Text field): class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ["user_response", "user_choice"] widgets = { "user_response": forms.TextInput(attrs={"class": "form-control"}), "user_choice": forms.Select(attrs={"class": "form-control"}), } def __init__(self, *args, **kwargs): question = kwargs.pop("question", None) super().__init__(*args, **kwargs) if question and question.has_choices(): self.fields["user_choice"].queryset = Choice.objects.filter( question=question ) self.fields["user_choice"].label = question.text self.fields["user_response"].required = … -
Is there a way to get my "Author" field prepopulating in my Django form?
I am making a review site and I have a Movie, Game, Show, and Review model and within my Review model I have "author" which is a foreign key and in my review form I have the "author" field and I want it to be populated with the username of the user that is logged in and leaving the review, I have searched this site and googled for hours and can't seem to find any solution ill leave my code I have at the moment below. Any help will be greatly appreciated! models.py forms.py views.py I have tried forcing it by using review.author = request.user, in my views.py and I have also tried it with request.user.username and finally I tried to do it using initials -
mod_wsgi for django with conda environment in Windows doesn't work
This is my first post in stackoverflow. I'll try to explain to you what I've done with steps and what I've done to try to solve the problems. Problem I'm struggling with the configuration of mod_wsgi for my django project. When i try to connect to localhost:8001 (port listened by mod_wsgi) I get an infinite loading or a "This site can’t be reached" page. What i've done I have installed apache2.4 with apachelounge (https://www.apachelounge.com/download/) in my C:\ drive. I have installed anaconda (I haven't set conda in path) and I created my environment for my django project (called production). It runs correctly if I run the command python manage.py runserver (if i go to http://localhost:7000/ (port set to manage.py) it works. I installed mod_wsgi in my conda environment with pip install mod-wsgi. Files httpd.conf (C:\Apache24\conf\httpd.conf) ServerName localhost Listen 8001 ... LoadFile "C:/Users/my_name/anaconda3/envs/production/python39.dll" LoadModule wsgi_module "C:/Users/my_name/anaconda3/envs/production/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/my_name/anaconda3/envs/production" WSGIScriptAlias / "C:/Users/my_name/my_path/Analyser/wsgi.py" <Directory "C:/Users/my_name/my_path/Analyser"> <Files wsgi.py> Require all granted </Files> </Directory> LogLevel info WSGIApplicationGroup %{GLOBAL} wsgi.py (C:/Users/my_name/my_path/Analyser/wsgi.py) import os import sys from django.core.wsgi import get_wsgi_application # add the project folder to the path (otherwise it says (core: ModuleNotFound) _BASE_DIR = r'C:\Users\my_name\my_path\Analyser' if _BASE_DIR not in sys.path: sys.path.append(_BASE_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") … -
is there any method that admin can manually verify the user who is registered an want to log in? [closed]
enter image description here this is the views.py section enter image description here And this is error i got after running try to log in enter image description here This is the models.py section My concept is simple, the new doctor is register and try to log in he can't log in because the admin is not approved him. If admin approves the verified booleanfield changes to true then doctor can log in.. kindly help to resolve this issue?? -
Split pdf files from request and send the splitted pdf's as response without saving it locally Django/Python
As mentioned in the title I have an API endpoint which receives a PDF file object from request. I need to split these PDF into multiple pdf's and send these split pdf's as response without saving any of these files locally using PYTHON inside a zip folder. Thanks in Advance!! I'm able to split and create zip if I save the files locally using pypdf2 but I just wanna know is there a way to split and put in a zip without saving locally. -
If user is not authenticated and adding something to cart, the item goes to the wishlist. But if user is logged in everything ok. DJANGO JS
I want my system to remember not only the products of logged in people, but also those who are not logged in. I made about the same cookie system for cart and wishlist that works until you loogged out. I'll put everything because idk where exactly to look main.html script part <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken') function getCookie(name) { var cookieArr = document.cookie.split(";"); for(var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); if(name == cookiePair[0].trim()) { return decodeURIComponent(cookiePair[1]); } } return null; } var cart = JSON.parse(getCookie('cart')) if (cart == undefined){ cart = {} console.log('Cart Created!', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" } console.log('Cart:', cart) var wishlist = JSON.parse(getCookie('wishlist')) if (wishlist == undefined){ wishlist = {} console.log('wishlist Created!', wishlist) document.cookie ='wishlist=' + JSON.stringify(wishlist) + ";domain=;path=/" } console.log('Wishlist:', wishlist) cart.html (wishlist almost the same) {% extends 'store/main.html' … -
stripe.txt not visible in my django project
I am following the tutorial via the link below. https://www.youtube.com/watch?v=ncsCnC3Ynlw&t=13787s I follow what the mentor did, but I don't have stripe.txt file in my django project, after I install stripe. pip install stripe the stripe.txt should be something like this. No auth:4242424242424242 Auth: 4000000000000025000003155 Error: 400000000000000000999555 Can anyone advise me how to solve this? Thank you so much -
How to load data from database to frontend step by step like big company websites do in Django fullstack?
We all know that Django web framework is powerful for loading tons of data and scalable to deliver it to user interface. So I got really common question, how do I fetch data step by step like Instagram or Youtube does? Instagram fetches videos, reels every 16 loops, First fetches 16 videos, then after watching last 16 th video then loads (prepares) another 16 videos, so how do I do my data to be fetched in exactly that way? Do I need js to do like that? Is it possible to do it in Python itself? I am not really sure amount of instagram fetches but, Can you please example some ways to do that? -
Compare performance with and without cache using django redis
I am using redis to implement caching for django project, I have created two function to compare the performance but function with caching seems slow any reason to that. Here is the loadtest output for the function without caching [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Max requests: 50 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Concurrency level: 1 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Agent: none [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Completed requests: 50 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Total errors: 0 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Total time: 0.40408834 s [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Requests per second: 124 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Mean latency: 8 ms and is the loadtest output for the function with caching [Thu Mar 23 2023 17:47:56 GMT+0530 (India Standard Time)] INFO Max requests: 50 [Thu Mar 23 2023 17:47:56 GMT+0530 (India Standard Time)] INFO Concurrency level: 1 [Thu Mar 23 2023 17:47:56 GMT+0530 (India Standard Time)] … -
What is the purpose of def get_instances_from_related() method in django_elasticsearch_dsl
I am working on creating elastic search indexing for the python Django project for a model with related tables. When I am working on it I came across the website https://pypi.org/project/django-elasticsearch-dsl/6.4.2/. I have followed the steps and implemented an elastic search for my model and it's working fine. But I can't find the purpose of the method def get_instances_from_related(self, related_instance). Why we are using this method, where and when we are it is called. Could anyone please explain this? Thank you. -
How to write a sql query and django queryset
Here i am having two tables Book,Publications Book tables is having the following fields id, book_name, pub_id And Publications table is having the following tables id, pub_name Using the pub_name how can i get the book_name in SQL query and Django query -
django-imagekit set dynamic width
I am using django-imagekit on my project, I cannot set dynamic size for processors. Is it possible to set it dynamic and make height auto ? models.py class Ad(TimeStampedModel): AD_MAIN = "main" AD_RIGHT = "right" AD_TYPE = ( (AD_MAIN, "Main"), (AD_RIGHT, "Right"), ) name = models.CharField(max_length=255, verbose_name="Номи") image= ProcessedImageField( upload_to="ads", format="webp", processors=[ResizeToFill(width=get_image_size, height=None)], options={'quality': 90}, ) ad_type = models.CharField( max_length=7, choices=AD_TYPE, default=AD_MAIN, ) is_active = models.BooleanField(default=False,) @property def get_image_size(self): if self.ad_type == self.AD_MAIN: return 1300 elif self.ad_type == self.AD_RIGHT: return 420 ] -
messages in the admin when subclassing BaseInlineFormset
I want to display a warning depending on entries made in the ItemInlineFormSet: from django.contrib import admin, messages from django.forms.models import BaseInlineFormSet from django import forms class SomeAdminForm(forms.ModelForm): class Meta: model = ModelA class ItemInlineFormSet(BaseInlineFormSet): def clean(self): msg = "test" class TheTabularInline(admin.TabularInline): model = ModelB formset = ItemInlineFormSet class ModelAAdmin(admin.ModelAdmin): inlines = [TheTabularInline,] form = SomeAdminForm I thought I could simply overrwrite save_model() or save_formset() in TheTabularInline to display the message: class TheTabularInline(admin.TabularInline): model = ModelB formset = ItemInlineFormSet def save_model(self, request, obj, form, change): messages.info(request, form.msg) But the variable is not accessible from there. Neither is request from within the clean() method of ItemInlineFormset. Do I have to overwrite the __init__()? -
Django not displaying action messages when used with apigateway http api
I have deployed a Django app on aws lambda and configured API gateway HTTP API. The action messages are not displayed when I perform actions like creating or deleting objects on Django admin. The action messages are properly displayed when I integrate Rest API instead of HTTP API. I already found keeping the Session storage in Django settings solves the problem, but I think it's a workaround instead of the solution. MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'