Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set different custom fields for articles in different article categories in Django?
I am a python rookie. I am using Django 4.X to create some basic CMS functions. The features I expect are: custom article classification, custom fields within article classification, and the ability to add different field contents based on user needs when adding articles in different categories. For example, Category 1: In addition to adding titles and article content, users also need to add weather information, while Category 2: users need to add price and quantity in addition to titles and article content. Here are the features I have already implemented and successfully run: Article publishing Article classification Custom fields within article classification Here is the feature I am unable to implement: When the user enters the page from post/int:category_id/add/, they should be able to add an article with the specific category ID and see the input fields for the custom fields I have added for that category ID. Here is my models.py and views.py code: models from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') custom_fields_group = models.ForeignKey('CustomFieldsGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='自定义字段组') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name class Meta: verbose_name = "多层分类" verbose_name_plural … -
Persistent 403 Forbidden with Apache + Django
I hope you can help me with a problem that seems simple but I don't understand where the error comes from My Django application remains inaccessible with my current configuration apache2/error.log [Fri Mar 24 16:35:24.094998 2023] [mpm_event:notice] [pid 101389:tid 140233809427776] AH00494: SIGHUP received. Attempting to restart [Fri Mar 24 16:35:24.168460 2023] [mpm_event:notice] [pid 101389:tid 140233809427776] AH00489: Apache/2.4.54 (Debian) mod_wsgi/4.7.1 Python/3.9 configured -- resuming normal operations [Fri Mar 24 16:35:24.168499 2023] [core:notice] [pid 101389:tid 140233809427776] AH00094: Command line: '/usr/sbin/apache2' [Fri Mar 24 16:35:27.794864 2023] [authz_core:error] [pid 106856:tid 140233787946752] [client 192.168.130.131:55869] AH01630: client denied by server configuration: /home/sullivan/webapp/webapp-proto/appback/wsgi.py appback/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appback.settings') application = get_wsgi_application() apache2 webapp_prod.conf <VirtualHost *:80> ServerName localhost WSGIDaemonProcess webapp_prod python-home=/home/sullivan/venv python-path=/home/sullivan/webapp/webapp-proto/webapp/appback/ WSGIProcessGroup webapp_prod WSGIScriptAlias / /home/sullivan/webapp/webapp-proto/appback/wsgi.py # WSGIScriptAlias / /home/sullivan/webapp/webapp-proto/appback/django.wsgi <Directory /home/sullivan/webapp/webapp-proto/webapp/appback/> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> apache2 apache2.conf # Global configuration # # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the Mutex documentation (available # at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>); # you will save yourself a … -
How to show required request body using django rest framework + drf_spectacular + swagger
I started using drf_spectacular and swagger recently, I have a an API endpoint that expects request body with field in it, however I can't seem to understand how to reveal this in the UI. my view: @extend_schema( responses={200: TripSerializer}, ) def get(self, request: Request) -> Response: trip = TripService.get_trip(trip_id=request.data.get("trip_id")) if trip is None: return Response(status=status.HTTP_404_NOT_FOUND) trip_serializer = TripSerializer(trip) return Response(trip_serializer.data, status=status.HTTP_200_OK) my request body: { "trip_id": "1" } my swagger UI ps will appriciate any help, Thanks -
Adding prerequisite to course sections
I am using the Tutor + OpenEdx open source platform and am looking to be able to set the prerequisite requirement for the individual sections as you can see this is already possible with the subsections but do not think there's an option for the individual sections. For example in the screenshots attached would like to have "Python" and "C++" locked until the student has completed "Intro to Programming". Think this is only possible with the subsections and not the sections at the moment so would like to build a plugin for it (or make changes to the code) to allow one to do the same with the sections. Would anyone be able to provide guidance on how to make this possible? -
I download Django project with Virtual Environment but cannot use it
I use FTP download my djaongo project from server to laptop. After that, In folder virtual environment it have many file like this image. I use this command to access virtual environment. .\myproject_env\bin\activate.ps1 It show (myproject_env) in front of path but when I use command python manage.py runserver it show error like this. How to fix it? (base) (myproject_env) PS D:\Django\myproject\myproject> python manage.py runserver Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. -
Getting error:"ORA-12505: TNS:listener does not currently know of SID given in connect descriptor". when connecting DJANGO to a remote oracle database
i can successfully connect to the remote database from my laptop through the follwing sqlplus command: sqlplus pdb1admin/mypass@192.168.18.102:1521/pdb1 but when i enter the credentials in my django project it gives the error:"ORA-12505: TNS:listener does not currently know of SID given in connect descriptor". my pluggable database name is pdb1. my service name is also pdb1. my username for the pdb1 database is pdb1admin. my password is 'mypass' and my port is 1521. my settings.py file in django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'pdb1', 'USER': 'pdb1admin', 'password':'mypass', 'HOST':'192.168.18.102', 'PORT':'1521', } } here is my tnsnames.ora file which is on my other computer which have the oracle database running. XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) ) PDB1 = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = pdb1) ) ) LISTENER_XE = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) LISTENER_PDB1 = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) ORACLR_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) ) (CONNECT_DATA = (SID = CLRExtProc) (PRESENTATION = … -
Cannot use fetch with Django: blocked by CORS policy although CORS is set up in Django
There are many solutions on SO for this problem. Some are extremely detailed (e.g. this one). However, although I think I have followed the setup instructions explicitly, I still cannot get it to work. Can someone please point out my error? js let endpoint = 'http://192.168.4.28:8000/test-put' const form_data = new FormData(); form_data.append("payload", payload); await fetch(endpoint, { credentials: "include", method: "PUT", body: form_data, headers: { "X-CSRFToken": getCookie("csrftoken"), }, }) urls.py path('test-put/', views.TextPut.as_view()), views.py class TextPut(View): def put(self, request): return {} settings.py ... CORS_ALLOWED_ORIGINS = [ 'http://localhost:8888', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8888', ] ... INSTALLED_APPS = [ ... 'corsheaders', ... ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... 'django.middleware.common.CommonMiddleware', ... ] This produces the error: Access to fetch at 'http://192.168.4.28:8000/test-put' from origin 'http://localhost:8888' has been blocked by CORS policy: Response to preflight request doesn't pass access control -
Django: Deployment to different companies using the same project?
If, for example, ten people from different companies want to use my Django site. I think, I need a different database per company. Does this means ten different Django projects/instances being deployed? With different domains and separate databases? This seems unmanageable if one needs to update the code. (I am using PythonAnywhere a d mySQL but I don't care what I use in the end, just that I do this the right way so I don't end up with a major problem. I am looking to keep it as simple as possible to start and learn.) To all, what is your method to handle the 'selling' on a subscription basis a website to different organization while keeping everything organized? An example is a CRM program. If I an employee wants to see all the notes about Customer A, I don't want them seeing customers from different companies when I query to get .all(). So I am guessing I need different databases, deployments etc. . . Thank you, I don't even know what to search on Google to read about this or else I probably wouldn't be asking it here. -
Creating a student from applicant model
`Kindly help me figure out how to create a student from my applicants models and also giving the students a custom registration number that will be incrementing as new students register. I tried searching to figure out but i could not find a solution. This my Applicant model -
I am facing this issue in django
-while I am making a project in django django-admin startproject hello -I am facing this issue in django, while using this command server is not working -python manage.py runserver -server show this error: -python: can't open file 'manage.py': [Errno 2] No such file or directory -while I am making a project in django django-admin startproject hello -I am facing this issue in django, while using this command server is not working -python manage.py runserver -server show this error: -python: can't open file 'manage.py': [Errno 2] No such file or directory -
Django: Can I make genre selection tables for three different tables that have different genre?
as in the title, I would like to make a separate single table for the genres of movies, books and CDs. When creating a product, I would like to limit the choice of genre depending on what kind of product we want to make. Is this idea of making one table good? Or is it better to make three separate ones. I will add that all product models inherit from the product. At the moment it looks like this from polymorphic.models import PolymorphicModel from django.db import models from django.urls import reverse from django.core.exceptions import ObjectDoesNotExist class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Disco', 'Disco'), ('Electronic music', 'Electronic music'), ('Rap', 'Rap'), ('Reggae', 'Reggae'), ('Rock', 'Rock'), ('Pop', 'Pop'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) def full_clean(self, exclude, validate_unique=True, validate_constraints=True): if CD.objects.filter(genre=self.genre, tracklist=self.tracklist).exists(): ValueError('Within one genre, we cannot offer two albums with the same track list') try: cds = CD.objects.filter(band=self.band) tab = [] for cd … -
Django taking too long to initialize middleware
I'm investigating some slow requests in our server using Datadog frame graphs. I found an interesting thing: this long delay to initialize/call the Django middleware stack. Any idea of what might be causing this issue/delay? -
how to put actions on a command in django?
I have a models django command which has a status field which should normally allow the administrator to put actions such as (on hold, validate reject or still in processing when a customer places an order but I don't know how to proceed to implement it please help me. my command models from django.db import models from user.models import User from main.models import * class Command(models.Model): class Status(models.TextChoices): PENDING = "PENDING" REJECTED = "REJECTED" CANCELED = "CANCELED" PROCESSING = "PROCESSING" READY = "READY" DELIVERED = "DELIVERED" user = models.ForeignKey(User, on_delete=models.CASCADE) cart = models.ForeignKey( Cart, verbose_name="panier", on_delete=models.CASCADE) type = models.CharField(max_length=50) data = models.JSONField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=20, choices=Status.choices, default="PENDING") email = models.EmailField(max_length=50, null=True) phone = models.CharField(max_length=60) name = models.CharField(max_length=30) company = models.CharField(max_length=50, default='') address = models.CharField(max_length=100, default='') appartement = models.CharField(max_length=100, default='', null=True, blank=True) city = models.CharField(max_length=50, default='') country = models.CharField(max_length=50, default='') here is the view, here I can't put anyone, I have no idea def command_action(request , act): action = get_object_or_404 (Command,id = act) if request.method == "POST": action I can't find an algorithm to solve this help me with some ideas -
Not able to run two consumers simultaneously using Django Channels
consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import asyncio class WebSocketConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): print(f"*********{text_data}*****") asyncio.create_task(self.send_count()) # run send_count in a separate task async def send_count(self): for i in range(0, 100000): print(i) await self.send('count completed') print('count completed') class SecondConsumer(AsyncWebsocketConsumer): async def connect(self): print("\n\n\n\n\n\n\n\n\n Reaching second consumer"\n\n\n\n") await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): await self.send('you are connected to socket') routing.py from django.urls import re_path from . import consumers websocket_urlpatterns=[ re_path(r'ws/1/', consumers.WebSocketConsumer.as_asgi()), re_path(r'ws/2/',consumers.SecondConsumer.as_asgi())] when WebSocketConsumer is running for loop if I try to run SecondConsumer from a new tab I am not able to connect to the websocket. I want to run both consumers from different browser tabs simultaneously -
How to study Python for Machine learning from scratch?
I am currently Studying in College , My first semester is over and I want to learn Python for machine learning with my College Degree, they are teaching C++ in college , Plz guide me! I tried learning it myself but couldnt manage time so plz guide me -
Celery beat creating multiple instances of the same task Django
This has been asked quite a few times but I couldn't find a satisfactory solution so requesting for help after searching for several hours I have defined celery broker with rabitmq and backend with redis. Earlier broker was with redis however it was giving the problem of multiple instances even without celery beat. This is a known issue When i am using celery beat, the issue is resurfacing This is my celery beat in settings.py of django project CELERY_BEAT_SCHEDULE = { 'update-every-minute': { 'task': 'apiresult.tasks.update_database', 'schedule': 60.0, }, } Am calling the async task from apps.py of the apiresult app from django.apps import AppConfig class ApiresultConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apiresult' def ready(self): from apiresult.tasks import update_database update_database.delay() tasks.py in apiresult app contains the update_database function @shared_task def update_database(): I have read we can use distributed locks to achieve it, but is there a simpler way to ensure only one instance of a task runs. I have tried celery redbeat but thats not helping either. Any help here is appreciated -
I cant install django-jquery : No matching distribution found for django-staticfiles-jquery
I have this version of python : Python 3.10.7 and this version for django : 3.2.15 I want to install jquery using : pip install django-staticfiles-jquery but i got this : ERROR: Could not find a version that satisfies the requirement django-staticfiles-jquery (from versions: none) ERROR: No matching distribution found for django-staticfiles-jquery I dont know what's the problem -
Django makemigrations throws error because unknown field
I am working on my first wagtail app. I already got some issues with the migrations. I wanted to chagne the models.ImageField to ImageChooserBlock() after I already did the first migration. This is my new model: class AboutPage(Page): template= "event/about.html" text = RichTextField() team_photo = ImageChooserBlock() content_panels = Page.content_panels + [ FieldPanel('team_photo'), FieldPanel('text'), ] But this throws the following error in the console: django.core.exceptions.FieldError: Unknown field(s) (group_foto) specified for AboutConnectedPage After running makemigrations. What could be the problem? -
Writing data to django database
I have a website project, but it is still raw. The problem is that I wrote a separate user registration page and the data from this page is written to the data table, but as soon as in forms.py I add additional parameters such as - there are at least 8 characters in the password, then the data stops being written to the database. I've tried everything I can, I've added this to the template form {% if form.errors%}. But stupidly there is no mistake. And I also gradually cleaned up for each parameter, but it didn't help either. I came here to find out what the error is, help me with all the necessary codes below, if you need something, write me I will throw it off. And I did migrations too This is forms.py users applications from .models import UserProfile from django import forms from django.forms import ModelForm, TextInput from django.core.validators import RegexValidator, EmailValidator class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ['email', 'password', 'password2', 'first_name', 'last_name', 'phone_number'] widgets = { "email": TextInput(attrs={ 'class': 'form', 'placeholder': 'Email', 'type': 'text' }), "password": TextInput(attrs={ 'class': 'form', 'placeholder': 'Password', 'type': 'password' }), "password2": TextInput(attrs={ 'class': 'form', 'placeholder': 'rePassword', 'type': 'password' … -
gunicorn.sock failed (13: Permission denied) while connecting to upstream
On one of my django application hosted on AWS i have an issue with my gunicorn / nginx interraction. When i'm going on AWS instance's Public IPv4 DNS i have the error *3 connect() to unix:/home/ubuntu/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: myip, server: mywebsite.nd, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/gunicorn.sock:/ I'm stuggling on it for couple of days. /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/myapp ExecStart=/home/ubuntu/venv/bin/gunicorn \ --access-logfile - \ --workers 2 \ --bind unix:/home/ubuntu/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket : [Unit] Description=gunicorn socket [Socket] ListenStream=/home/ubuntu/gunicorn.sock [Install] WantedBy=sockets.target I already test to put my gunicorn.sock on differents folders owned by user ubuntu without any success. My nginx conf is fine since it worked few days ago. My gunicorn.sock is always created by root:root. ls -la /home/ubuntu/gunicorn.sock srw-rw-rw- 1 root root 0 Mar 24 10:49 /home/ubuntu/gunicorn.sock Tried to chown ubuntu:www-data on it but when gunicorn.socket is restarted it recreated it with root:root. Btw on my others application it doesn't seem to be a problem. All solutions found on SO may pose as a serious security risk on my public facing server (changes nginx user to root, setsebool -P httpd_can_network_connect 1 etc..) so don't want … -
Django function update object not working, he is create new object instead update
this function generate new object instead update existing one, how can i modify to update? def brand_upd(request, slug): data = get_object_or_404(Brand, slug=slug) form = BrandForm(instance=data) if request.method == 'POST': form = BrandForm(request.POST, request.FILES, instance=data) if form.is_valid(): form.save() return redirect('contul_meu') context = {'form': form} return render(request, "brand/brand_create.html", context) this function does not work to modify an existing object but creates a new object. where can the problem be? -
Prefetch in models of complex relationships
Given the following models, I would like to get objects across the models in prefecth. class A(models.Model) b = models.ForeignKey("B", related_name="a") code = models.IntegerField(default=0) class B(models.Model) c = models.ForeignKey("C", related_name="b", blank=True, null=True) class C(models.Model) name = models.CharField(max_length=12) c_list = C.objects.prefetch_related( Prefetch( "b__a", queryset=A.objects.order_by("code"), to_attr="a_list", ) ) for c in c_list: print(c.a_list) The following error occurs AttributeError: 'C' object has no attribute 'a_list' I want to get an object of A directly from an object of C. How can I achieve this? Thanks in advance. -
Identifying Anonymous Users uniquely for custom Websocket communication in Django Rest Framework
I am using Django Rest Framework with ASGI capabilities. I have enabled a websocket. For each websocket connection, i get a channel_name which i suppose is unique. Nevertheless when i received a Request on http for example to do some calculation i am not able to understand how am i suppose to send it back to the right, unique Anonymous User. I have enabled Json Web Token JWT authentification and even though SessionMiddleware is added to my DRF, i dont get any Session Info (it is None in the request for session_key, the session doesn't exist). My goal was to associate a session_key to a channel_name in the database and when the calculation is finished to send back the results to the correct Anonymous User by Websocket with this mapping. Am i on the right path? Is there another solution since i cant get a session cookie or session at all. -
Django Custom filter doesn't register
Can't seem to get my custom template tag to work So I need a custom template tag in order to index variables in django templates, so I did this file structure templatetags __init__.py index_dict.py ... models.py views.py index_dict.py from django import template register = template.Library() @register.filter(is_safe=True) def index_dict(var, arg): try: return var[arg] except: return None and comments.html where is is being used {% if canUserEdit|index_dict:comment or canUserEdit %} <!-- Inner HTML --> {% endif %} The error is this TemplateSyntaxError at /post/1/ Invalid filter: 'index_dict' and it gets triggered in the html I don't understand what I'm doing wrong, it seems im following the documentation but nothing seems to work any ideas -
How to add css file to my css_settings in settings.y
I`m using django-select2 but its not important and i want to add some new css styles to that settings but if i add them i got an error because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. settings.py SELECT2_CSS = [ os.path.join(BASE_DIR, 'static_src/css/style.css') ]