Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
scheduling post request after 2 minutes in djangorestframework?
Hello developers I am stuck to post request automatically by using APScheduler in djangoRestFramework each 2 minutes please help to do it main problems is pass request in scheduling job. class LogisticsTruckListView(APIView): def post(self, request): truck_id = request.data.get('truckListId') queryset = LogisticsTruckList.objects.filter(truckListId=truck_id) serializer = LogisticsTruckListSerializer(queryset, many=True) data = serializer.data # get vehicle no vehicle_no = data[0]['vehicle_no'] if vehicle_no: url = "https://track.cxipl.com/api/v2/phone-tracking/doc-latest-location?vehicleNumber="+vehicle_no headers = { "Content-type": "application/json", "authkey": "UB1CNQLKU32LPCFQJ2NGL7YY1E51HYF6" } response = requests.get(url, headers=headers, verify=False) if response.status_code == 200: data = response.json() return Response(data, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_400_BAD_REQUEST) here is my scheduling job code .. def start(): scheduler = BackgroundScheduler() viewSets = LogisticsTruckListViewSet() scheduler.add_job(viewSets.getTrackingDetails(), 'interval', minutes=1, id='tracking_details__001', replace_existing=True) scheduler.start() Help me out soon as possible I want to schedule a task in django rest framework -
Django problem with" python manage.py makemigrations"
Hi i'm doing the Mosh Tutorial about Django and when i run the command python manage.py makemigrations i have this in terminal File "C:\Users\Giovanni\PycharmProjects\PyShop\venv\Lib\site-packages\django\db\models \fields\__init__.py", line 1121, in __init__ super().__init__(*args, **kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' (venv) PS C:\Users\Giovanni\PycharmProjects\PyShop> This is my models.py from django.db import models class Product(models.Model): name = models.CharField(max_lenght=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_lenght=2083) -
Django: You're accessing the development server over HTTPS, but it only supports HTTP. code 400, message Bad request version
I am trying to access my Django website using python manage.py runserver , which returns me http://127.0.0.1:8000/. However, when I try to access this link using Google chrome, I get this error on chrome This site can’t provide a secure connection 127.0.0.1 sent an invalid On Anaconda prompt, I get this error: Code 400, message Bad request version ('ª') You're accessing the development server over HTTPS, but it only supports HTTP. I notice that Google Chrome always changes my website to http://127.0.0.1:8000/ I am uncertain if this is the issue because. I have been working on the Django project and have been accessing the website on chrome using the same method and there was no issues with it at all. Could it be because of the settings.py configurations that caused the error? import os from pathlib import Path import django_heroku # to host heroku import dj_database_url # to host heroku from decouple import config # to host heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d44=xloa_ngo&moz%cujtvuqpr7ub)hfbqss6$xnubj031q3!9' # SECURITY WARNING: … -
Group list active item appears 2 times in a list
Im writing program that shows static schedule for school organisations and now there is a page of schedule with relevant days-lessons, but the title of the day appears 2 times. Here is a screenshot of my issue: Issue Here is the html code of the page schedule.html {% extends 'app/layout.html' %} {% block body %} <ul class="list-group"> {% for i in subjects %} <li class="list-group-item active" aria-current="true">{{i.day}}</li> <li class="list-group-item " aria-current="true">{{i.title}}</li> {% endfor %} </ul> {% endblock body %} views.py def showSchedule(request, ID): relevant_group = Students.objects.get(id = ID) subjects = relevant_group.students.all().order_by("day") context = {"group": relevant_group, "subjects":subjects} return render(request, "app/schedule.html", context) How to make this blue(active item) Friday appear just 1 time? -
django conditional filtering
I have this model of Vehicle: class Vehicle(models.Model): ... driver = models.OneToOneField(Driver, related_name="vehicle", on_delete=models.CASCADE, blank=True, null=True) In my form i want to initialize the queryset of driver so only the driver that have no relations with vehicle appear in list (because its one-to-one relations). So in my forms.__init__: self.fields['driver'].queryset = vendor.drivers.select_related('user').filter(vehicle__isnull=True) but I realize in my edit form (using ModelForm), the driver not initialized in form because i guess, the queryset override it. The initial driver is not vehicle__isnull So what i want is, vehicle__isnull except for this initial driver if there is a driver already. How can I achieve that? Any help would be appreciated. -
Why doesn't models.py get created on running python3 manage.py polls from within a script?
I wrote many scripts to help me manage my django projects. One of them, cr_app.py creates a new app: #!/usr/bin/env python3 from subprocess import run def main(): create_app() def create_app(): name = input("The name of the app?\n") run(f"""python3 manage.py startapp {name}""", shell=True) if __name__ == "__main__": main() When I am inside of my virtual envirnment's project directory and, following the tutorial, I run manually python3 manage.py startapp polls then I find models.py already created inside of polls/. But this does not happen when I run cr_app.py and create a new app polls even though I run this script while being in the projects activated virtual environment (although cr_app.py is not, it is located in a different, remote directory). Why so? -
Running django project failing after upgrade to django 3.2.18
I upgraded my django project from django 3.0.6 to django 3.2.18. After that I cannot run my project with following command: python -m my_project.manage run server 127.0.0.1:8000 it produces below error message: python.exe: No module named my_project.__main__; 'my_project' is a package and cannot be directly executed However when I run: python manage.py runserver 127.0.0.1:8000 It works perfectly fine. Does anyone has similar issue? I suspected it was related to django app configuration but changes in this field does not help. -
Reverse for 'usecase-details' with no arguments not found. 1 pattern(s) tried: ['usecase\\-details/(?P<ucid>[^/]+)\\Z'] Django
I have three models user, usecase, and usecase assign: I have two views redirecting to the same page to show the details of the usecase and to assign new users and unassign users: I'm trying to execute the logic of this method: DELETE FROM usecase_assign WHERE usecase_assign.user_email = 'nmbarak'; How can I get the user_email from the template and pass it in the view to delete it? what I tried is to create two views, the first one for showing the usecase details and assign new users, the second one to un-assign and to redirect to the same page. My usecase_assign model: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) my views: @user_login_required def view_usecase_details(request, ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() usecase_details = usecase_details.prefetch_related("usecaseids") users = User.objects.all() #SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; usecase_assigned = UsecaseAssign.objects.select_related('user_email').values_list('user_email__user_name').filter(usecase_id=ucid) #to show list of users working on uc if request.method=='POST' and 'assignuser' in request.POST: user_email = request.POST['user_email'] userAssignCheck = UsecaseAssign.objects.filter(user_email=user_email, usecase_id=ucid) if userAssignCheck: messages.error(request, "user already added!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: userAssignObj = UsecaseAssign.objects.create(user_email_id=user_email, usecase_id=ucid) if userAssignObj: messages.success(request, "User was Successfully Assigned with Usecase!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned, … -
How to use metronic select2 style in django-select2
I have a form and i render that in template with django-select2 and also i downloaded one of metronic html templates with css and js files and they have select2 styles in there But select2 its not django-select2 package but i need django-select2 so how can i use their customize on my package? https://preview.keenthemes.com/html/metronic/docs/forms/select2 template.html {% render_field form.contractor_counter|add_class:"form-select" %} thats` how they say i need to use their template of select 2 {# <select class="form-select" data-control="select2" data-placeholder="Select an option">#} {# <option></option>#} {# <option value="1">Option 1</option>#} {# <option value="2">Option 2</option>#} {# </select>#} -
TemplateDoesNotExist at / in pythonanywhere
when i deploy the website to pythonanywhere, it show this Exception. i had checked there was the file but it show (Source does not exist). How can i solve it? i tied 1) add ('learning_logs/templates') to 'DIRS' 2) add (path.join(BASE_DIR, 'templates') to 'DIRS' The problem didnt solve even i tried above solution. Can anyone help? the templates i save in below path: learning_log\learning_logs\templates\learning_logs settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['learning_logs/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] view.py def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs\index.xhtml') -
DRF - How to generate nested json with serializer?
I'm a beginer in DRF and here is a simple illustration of the nested json I want to generate: { "shop_name": "some_text", "shop_intro": "some_text", "swiper_images": [ { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" }, { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" }, { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" } ] } Here is my models.py: from django.db import models class ShopIndexPage(models.Model): shop_name = models.CharField(max_length=128, default="Shop Name") intro_text = models.CharField(max_length=1000, default="Intro Text") def __str__(self): return "Shop text of " + self.shop_name class SwiperImage(models.Model): swiper_image = models.ImageField(upload_to='images/index/swiper-images', default="None") swiper_image_alt = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.swiper_image_alt Here is my serializer.py: from rest_framework import serializers from .models import ShopIndexPage, SwiperImage class SwiperImageSerializer(serializers.ModelSerializer): class Meta: model = SwiperImage fields = ['swiper_image', 'swiper_image_alt'] class ShopIndexPageSerializer(serializers.ModelSerializer): swiper_items = SwiperImageSerializer(many=True) class Meta: model = ShopIndexPage fields = ['id', 'shop_name', 'intro_text', 'swiper_items'] Here is my views.py: from .models import ShopIndexPage from .serializers import ShopIndexPageSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['GET', 'POST']) def index_list(request, format=None): if request.method == "GET": index_queryset = ShopIndexPage.objects.all() serializer = ShopIndexPageSerializer(index_queryset, many=True) return Response(serializer.data) elif request.method == "POST": serializer = ShopIndexPageSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) I got the following error: Got AttributeError when attempting …