Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The term 'py' is not recognized as the name of a cmdlet
I have been trying to create a virtual environment for django project but I have been meeting the error below. py : The term 'py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 py --version ~~ CategoryInfo : ObjectNotFound: (py:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException Attached is also the graphic of the error as it appears on my system. I have added python to path in environmental variables yet it's not working. -
Installed Django 4 but project runs Django 2
I've been using django for a while and today when starting a new project I noticed that when I run: django-admin startproject mysite The settings.py generated file says: Generated by 'django-admin startproject' using Django 2.2.19 and the code is not the new one. I have projects written in django 4 and in django 2 and the code generated is equal to the django 2 I also ran: python -m django --version which returns: 4.1.7 Python version is 3.11 Anyone else have this issue? -
The products are not removing from the shopping cart after ordering in python-django
I am trying to make an e-commerce website. There is 1 problem which has been very hard to fix. The problem: After ordering, products are supposed to be deleted from the shopping cart. But it is not working. There are no syntaxis errors but there is still products remaining after ordering. Here is the part my views.py for it: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_products = OrderProduct.objects.filter(order=order) if order_products: order_product = order_products[0] else: order_product = OrderProduct.objects.create(order=order) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] session.modified = True return redirect('product_list') I really hope someone can help me, please. Someone answered this question about 3 days ago but their answer wasn't right. I commented on their answer but they are not answering. You can check my previous question if you need their answer. IT IS NOT WORKING! -
I am finding it difficult to run any py command on my django project
py -m venv myworld 'py' is not recognized as an internal or external command, operable program or batch file. I have been battling with the above error. Adding python to path in environmental variable -
Celery is not able to find my django module
I’m facing the below error when I try to start the celery using the command celery -A blogger.celery worker. I’m running the command from my package directory where I have my celery.py ModuleNotFoundError: No module named 'blogger' ———————— blogger/celery.py from celery import Celeryfrom django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blogger.settings") app = Celery('blogger') app.conf.enable_utc = Falseapp.conf.update(timezone='Asia/kolkata') app.config_from_object(settings, namespace='CELERY') —————— blogger/init.py from .celery import app as celery_app all = ('celery_app', ) ———————— blogger/setting.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379'CELERY_ACCEPT_CONTENT = ['application/json']CELERY_RESULT_SERIALIZER = 'json'CELERY_TASK_SERIALIZER = 'json'CELERY_TIMEZONE = 'Asia/kolkata'CELERY_RESULT_BACKEND = 'django-db'CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'————————— Please help me to resolve this error Please help me resolve this issue -
Django cannot create a new project
I have installed python and django, when i run this command django-admin startproject testproject The command run well but it does not create any folder with the name (testproject) or files. and there is no error messages. I am using Python 3.11.2 and Django v. 4.1.7 I tried to run the command and I expected it will create a project but it does not create the folder and no error messages. When I run the command again it give this CommandError: 'D:\DjangoProjects\testproject' already exists but there is NO folder in the directory. -
Creating a button to change a boolean using htmx
I am trying to create a workflow using django and htmx were a user needs to accept an entry by clicking a button. In the backend this is supposed to change a boolean from False to True. I followed this tutorial HTMX 09 - Like e unlike com HTMX trying to adapt the "Like" functionality to my purposes, however in my case there is no template (at least non that makes sense to me) and this results in a 403 error. What is my error of thought here? <models.py> from django.db import models from django.db.models import Model class PurchaseOrder(Model): name = models.CharField(max_length=200) approved = models.BooleanField(default=False) <views.py> from .models import PurchaseOrder from django.views.decorators.http import require_http_methods @require_http_methods(['POST']) def po_accept(request, pk): order = get_object_or_404(PurchaseOrder, pk=pk) order.approved_accounting = True order.save() context = {'order': order} return render(request, context) def my_approvals(request): orders = PurchaseOrder.objects.all() template = 'procurement/my_approvals.html' context = {'orders': orders} return render(request, template, context) <urls.py> from django.urls import path from . import views app_name = 'procurement' urlpatterns = [ path('', views.index, name='index'), path('my_approvals/', views.my_approvals, name='my_approvals'), path('po_accept/<int:pk>', views.po_accept, name='po_accept') ] <my_approvals.html> {% for order in orders %} {{ order.name }} <button type="button" class="btn btn-success m-3" hx-post="{% url 'procurement:po_accept' order.pk %}" > Accept </button> {% endfor %} -
change the category of multiple posts at once in django admin panel
i have a django project that in admin panel i want to have a dropdown menu to selec multiple posts and can change its categories at once and the page just shows categoriy based on post's law! thanks here is my admin.py from django import forms from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import Law, Category, Post class CategoryInline(admin.TabularInline): model = Category extra = 0 def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'parent': # get the selected law from the parent Post model try: law_id = request.resolver_match.kwargs['object_id'] except KeyError: return super().formfield_for_foreignkey(db_field, request, **kwargs) # filter categories based on the selected law kwargs['queryset'] = Category.objects.filter(law_id=law_id) return super().formfield_for_foreignkey(db_field, request, **kwargs) class PostInline(admin.TabularInline): model = Post extra = 0 class CategoryAdminForm(forms.ModelForm): class Meta: model = Category fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) law_id = self.instance.law_id if self.instance else None self.fields['parent'].queryset = Category.objects.filter(law_id=law_id) def save(self, commit=True): instance = super().save(commit=False) instance.slug = slugify(instance.name, allow_unicode=True) if commit: instance.save() return instance class CategoryAdmin(MPTTModelAdmin): form = CategoryAdminForm list_display = ['name', 'law'] list_filter = ['law'] def get_inline_instances(self, request, obj=None): if obj: self.inlines = [PostInline] else: self.inlines = [] return super().get_inline_instances(request, obj) class LawAdmin(admin.ModelAdmin): inlines = [CategoryInline] class PostForm(forms.ModelForm): class Meta: model = … -
getting error ['djongo' isn't an available database backend or couldn't be imported] wihile running makemigrations cmd in django
I have create one simple django project and try to connect with mongodb database but when hit python manage.py makemigrations or migrate cmd getting error- django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' python python v- 3.10 please help me out. pip list- Package Version asgiref 3.6.0 Django 4.1.7 djongo 1.3.6 dnspython 2.3.0 pip 23.0.1 pymongo 4.3.3 setuptools 67.6.0 sqlparse 0.2.4 tzdata 2022.7 setting.py file db connection and install app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dapp', 'djongo', ] DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'testdb', 'HOST': 'localhost', 'PORT': 27017, } } -
Windows 10 Run django project on virtual Ubuntu server
I have Windows 10 on my laptop. I faced with some problems using Windows for develop django app. For example, celery library couldn't run tasks on Windows 10. So I want to install ubuntu and use it with my pycharm for django projects. I download ubuntu in Windows Store. But how can I set it for work with my django projects and his virtual environment? -
INSTALLED_APPS not defined in cartoview?
I am trying to install geoserver and this error comes in cartoview when i run paver setup_geoserver: File "/home/developer/cartoview/cartoview/settings.py", line 24, in <module> INSTALLED_APPS += CARTOVIEW_INSTALLED_APPS NameError: name 'INSTALLED_APPS' is not defined I don't know why this error is coming. I have tried to manually define the variables but it is giving other errors like index out of range. can someone kindly help? -
How can I display multiple render calls on webpage?
I'm getting started with the Django framework but can't figure out how to have multiple render calls from the views python file appear on my webpage. Within the url python file, I tried adding a new path and calling the function similar to how I did for the createPunnettSquare (which worked fine). My project ran fine but I was expecting the title to say 'punnett square' but only 'punnett' appears. Thanks in advance for any help as this is my first post. If more information is needed I can defintely provide it. webpage output views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. # request -> response # request handler def createPunnettSquare(request): genotype1 = "Aa" genotype2 = "Bb" l_offsprings = [] punnett_square = [[""]*len(genotype1) for i in range(len(genotype2))] for i in range(len(genotype1)): for j in range(len(genotype2)): p_offspring = fill_array(request, j, i, genotype1, genotype2) l_offsprings.append(p_offspring) dy_offsprings = {"offsprings": l_offsprings} return render(request, 'hello.html', dy_offsprings) def fill_array(request, j, i, genotype1, genotype2): offspring = genotype1[j] + genotype2[i] if offspring[0].isupper() == False: offspring = offspring[::-1] return offspring def sayhi(request): return render(request, 'hello.html', {"name": "square"}) urls.py from django.urls import path from . import views # URL configuration module (every app can … -
I have a error in django html file where the IF statement is not working properly
So I have a like button and i want it to show an already liked button if the user has already liked the post. Here is my html {% for post in posts %} <div class="border-solid border-2 mr-10 ml-10 mt-3 px-2 pb-4"> <h1 class="text-2xl font-bold mt-2 mb-2"><a href="/user/{{post.User}}">{{post.User}}</a></h1> {% if post.User == request.user.username %} <button id="btn_{{post.id}}" type="submit">Edit</button> <div id="text_{{post.id}}" class="hidden"> <textarea required="" maxlength="300" class="border-solid border-2 w-full h-20" name="text" id="textarea_{{post.id}}" cols="30" rows="10">{{post.Content}}</textarea> <button id="btn1_{{post.id}}" class="bg-blue-600 rounded-lg px-4 py-2 mt-1 text-white">Confirm</button> </div> <script> document.querySelector('#btn_{{post.id}}').addEventListener('click', function() { document.querySelector('#Content_{{post.id}}').className = "hidden"; document.querySelector('#text_{{post.id}}').className = 'block'; }) document.querySelector('#btn1_{{post.id}}').addEventListener('click', function() { fetch('/edit/{{post.id}}', { method: "POST", body: JSON.stringify({ content: document.querySelector('#textarea_{{post.id}}').value }) }) .then(response => response.json()) .then(result => document.querySelector('#p_{{post.id}}').innerHTML = result.Content ); document.querySelector('#Content_{{post.id}}').className = "block"; document.querySelector('#text_{{post.id}}').className = 'hidden'; }) </script> {% endif %} <div id="Content_{{post.id}}"> <p id="p_{{post.id}}" class="text-xl">{{post.Content}}</p> <input id="" type="hidden" value="{{post.Content}}"> </div> <p>{{post.Date}}</p> {% if post.User != request.user.username %} <button id="btn3_{{post.id}}"> like </button> <script> document.querySelector('#btn3_{{post.id}}').addEventListener('click', function() { fetch('/like/{{post.id}}', { method: "post", }) .then(response => response.json()) .then(result => document.querySelector('#likes_{{post.id}}').innerHTML = result.likes ); }) </script> {% endif %} {% if post.id in has_liked %} <button class="btn4_{{post.id}}"> Unlike </button> {% endif %} <p id="likes_{{post.id}}">{{post.likes}}</p> </div> {% endfor %} This is the views.py function : def index(request): if request.method == "POST": text … -
How to display the GenericRelation field value in djagno admin
I have a model A class XYZ(TimeStampedModel): content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') my other model B is this where I have defined the GenericRelation field class MNO(models.model): tin = GenericRelation( XYZ, content_type_field='content_type', object_id_field='object_id', null=True, blank=True, on_delete=models.SET_NULL, ) I want to show this field tin in my MNO's model admin. On adding the field name to the list_display I get the following two errors - django.core.exceptions.FieldDoesNotExist (main culprit) TypeError: call() missing 1 required keyword-only argument: 'manager' How can I get its value to be displayed like a normal model field? -
How to get data from select from frontend Django
I have ListView and select with options in my Django template and i want to get value from select in my listview to change response by this data but i got None when i try to print that How am i suppose to do that? views.py def get_queryset(self): url = config('REPORT_PROJECT_BUDGET') select_front = self.request.GET.get('selection') payload = {'ObjectGUID': select_front, } print(payload) # response = requests.get(url, auth=UNICA_AUTH, params=payload).json() # print(response) queryset = [] return queryset def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['OBJECTS'] = ObjectList.objects.all() return context template.html <div class="select"> <select id="g1" name="selection"> {% for obj in OBJECTS %} <option value="{{ obj }}">{{ obj }}</option> {% endfor %} <option value="1">1</option> </select> </div> -
how to filter passing a string value and get data from database
event_id:"3", event name: "BTC price increases to ₹18,50,000.00 or more by next 24 hours? i am passing event name " BTC price" and filter Multiple event stored on a database, and i filter event name of "BTC price"..how to get this data -
Redis Authentication Error on Django Python
When I try to log in to the admin panel either it returns an invalid password error or Client Sent AUTH, but no password is set. The application is built using python Django but Redis is the one that results in the error. I have tried available online solutions to set password/keys, remove password but it seems none is working. It still results in either of the errors. The reason why Redis is used is so that a user can attempt a wrong password only specific number of times before it locks for a specific time. If there is an alternative to Redis or a way to make it run on my machine I would appreciate as removing it would result in security issues. The current python version is 3.8 and the Redis version is 4.0.2. The app was built with older versions of the same. -
django allow cors from any host in particular view
django-corsheaders provides a list of domains to specify to allow cors, however, it would apply to all the views. I have some views that do not have any authorised form and are intended for access from other domain, like serving a raw text string from db, and want to allow cors from any host only for this view @csrf_exempt def my_view(request): response = HttpResponse() response['Access-Control-Allow-Origin'] = '*' # some other code here return response However, it is managed by django.middleware.common.CommonMiddleware, and a 301 is responded in the middleware before reaching the view. Is there a way to do this? -
React Form not sending POST data to API
React code for Frontend function InputsSignUp(){ const [username, setUsername] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = (e) => { e.preventDefault(); fetch('/api/user/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email }), }) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error)); }; return ( <> <Container fluid="sm" style={{backgroundColor: 'white'}}> <h1>{email}</h1> <h1>{password}</h1> <Form> <Form.Group className="mb-3" controlId="formBasicUsername"> <Form.Label>Email address</Form.Label> <Form.Control type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> </Form.Group> <Button variant="primary" type="submit" onSubmit={handleSubmit}> Submit </Button> </Form> </Container> </> ) } Python code for Backend @csrf_exempt def signup(request): if request.method == 'POST': print("Hello") data = json.loads(request.body) user = User.objects.create( #username=data['username'], email=data['email'], password="hello", ) user.save() return JsonResponse({'message': 'User created successfully'}) I am trying to send data from frontend react to backend to create a user and store the data. But whenever I submit the data it does not reach the given api point. While using POSTMAN to send the data I am successfully able to create the user. Is there anything wrong with the react code? -
clean() getting None value for ModelChoice Field in django model form
Here in ModelForm the clean method is not fetching the values of production_process queryset it is giving the None value here is my views.py class ProductionCapacityCreateView(CreateView): template_name = 'manufacturing/production_capacity_form.django.html' form_class = ProductionCapacityForm context_object_name = "production_capacity" model = ProductionCapacity def get_form_kwargs(self): kwargs = super(ProductionCapacityCreateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client kwargs["request"] = self.request return kwargs def form_valid(self, form): print("FORM VALID") self.client = self.request.user.client self.object = form.save(commit=False) self.object.client = self.request.user.client p_process = form.cleaned_data['production_process'] num_of_people = form.cleaned_data['number_of_people'] date = form.cleaned_data['date'] try: self.object.save() messages.success(self.request, 'Day created successfully.') except BaseException as e: logger.exception(e) messages.error(self.request, 'Failed to create a day.') return HttpResponseRedirect(reverse("capacity_list")) here is my forms.py class ProductionCapacityForm(forms.ModelForm): date = forms.DateField(required=True, widget=forms.DateInput(attrs= { 'class':'datepicker' })) def __init__(self, *args, **kwargs): self.client = kwargs.pop('client') self.request = kwargs.pop('request') try: self.work_time = kwargs.pop('work_time') except: pass super(ProductionCapacityForm, self).__init__(*args, **kwargs) self.fields['production_process'].queryset = ProductionProcess.objects.filter(is_deleted=False).values_list("name", flat=True).distinct() self.fields['date'].widget.attrs\ .update({ 'placeholder': 'Select Date', 'class': 'input-class_name' }) def clean(self): production_process = self.cleaned_data.get('production_process') number_of_people = self.cleaned_data.get('number_of_people') datee = self.cleaned_data.get('date') pk = self.instance.pk if production_process: try: if production_process not in ProductionCapacity.objects.get(client=self.client, date=datee,production_process=production_process.id): self.cleaned_data['production_process'] = get_object_or_404(ProductionProcess,client=self.client,id=production_process.id) except: if ProductionCapacity.objects.filter(client=self.client, date=datee, production_process=production_process.id).exists(): raise forms.ValidationError('Production Process is already exists') self.cleaned_data['number_of_people'] = number_of_people self.cleaned_data['date'] = datee return super(ProductionCapacityForm, self).clean() class Meta: model = ProductionCapacity widgets = { "date": McamDateInput1, } fields = ['date', 'production_process', 'number_of_people'] … -
False positive variable not defined how to resolve?
I have some code and in settings.py file, it is saying that variable INSTALLED_APPS is not defined. The code is written like this: INSTALLED_APPS += ABC_INSTALLED_APPS Now we know that variables in python don't need defining then why is this problem arising? it is with a lot of other variables too. I tried to define variables manually but it is throwing another error in another variable of index out of range. Kindly help. -
Using the URLconf defined in learning_log.url,error 404
The python project about Django error Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: A special answer for this question. -
How to distinct in Django with a field beyond a foreign key
In the following model relationship, how can we make it distinct in the B field? class A(models.Model): b = models.ForeignKey("B") class B(models.Model): name = models.CharField(max_length=1024) The following will result in an error A.objects.distinct('b__name') django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("b"."name") "a"."id", ... -
How to implement server sent events in django app using http views?
I have a django asgi app that is served by daphne. I am trying to add Server Sent events to stream data from server to client. My asgi.py: """ ASGI config for app 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.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_asgi_application() My django view is below: import uuid from django.http import StreamingHttpResponse from rest_framework.views import APIView from .sse_helper import register_connection import logging log = logging.getLogger("sse_handler") class MySseView(APIView): # authentication_classes = [SessionAuthentication] # permission_classes = [IsAuthenticated] def get(self, request): log.info("Recived get request") response = StreamingHttpResponse(content_type="text/event-stream") # Set headers to enable SSE support response["Cache-Control"] = "no-cache" response["Connection"] = "keep-alive" # Generate a unique ID for this connection connection_id = str(uuid.uuid4()) business_id = "foo" # Register the connection in the dictionary register_connection(connection_id, str(business_id), response) return response The registered connections are processed by a background thread like this: sse_connections = {} def register_connection(connection_id, business_id, response): log.info("Registering sse connection %s for business %s" % (connection_id, business_id)) sse_connections[connection_id + '#' + business_id] = response def handle_events(): while True: # Iterate over the dictionary of connections log.info("Running handle_events on %d items" % len(sse_connections)) … -
Forbidden (CSRF token missing)
I just learned how to create a web server on raspberry using django, i am trying to improve it by using JS that generates form every time i send data but am getting this error and haven’t found a solution yet. Need some help. here the error when i run web server enter image description here My html <!DOCTYPE html> <html> <head> <title>blablablai</title> <script> function sendDirection(direction) { const data = new FormData(); data.append('direction', direction); const request = new XMLHttpRequest(); request.open('POST', '{% url "home" %}'); request.send(data); } function onMouseDown(direction) { sendDirection(direction); } function onMouseUp() { sendDirection('stop'); } </script> </head> <body> <h1>bzzzz....</h1> <button type="button" onmousedown="onMouseDown('forward')" onmouseup="onMouseUp()">Forward</button> <button type="button" onmousedown="onMouseDown('backward')" onmouseup="onMouseUp()">Backward</button> <button type="button" onmousedown="onMouseDown('left')" onmouseup="onMouseUp()">Left</button> <button type="button" onmousedown="onMouseDown('right')" onmouseup="onMouseUp()">Right</button> <form method="post" action="{% url 'change_speed' %}"> {% csrf_token %} <button type="submit" name="speed" value="25">Speed 25%</button> <button type="submit" name="speed" value="50">Speed 50%</button> <button type="submit" name="speed" value="75">Speed 75%</button> <button type="submit" name="speed" value="100">Speed 100%</button> </form> </body> </html> My views.py from django.shortcuts import render, redirect import smbus # Define I2C address SLAVE_ADDRESS = 0x27 # Initialize I2C bus bus = smbus.SMBus(1) # Define motor control functions def forward(): bus.write_byte(SLAVE_ADDRESS, ord('f')) def backward(): bus.write_byte(SLAVE_ADDRESS, ord('b')) def turn_left(): bus.write_byte(SLAVE_ADDRESS, ord('l')) def turn_right(): bus.write_byte(SLAVE_ADDRESS, ord('r')) def stop(): bus.write_byte(SLAVE_ADDRESS, ord('s')) def speed25(): bus.write_byte(SLAVE_ADDRESS, ord('1')) …