Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
react+django+rest_framework+jwt API refresh token sometimes response 401 Unauthorized
My problem is most of the time the token refreshed ok. Sometimes when I refresh manually, the server responds 401. If I refreshed again, the server responds 200. Not sure why. The django server side shows: Unauthorized: /api/token/refresh/ [28/Jan/2024 16:44:04] "POST /api/token/refresh/ HTTP/1.1" 401 58 [28/Jan/2024 16:44:04] "GET /api/ HTTP/1.1" 200 109 [28/Jan/2024 16:48:05] "POST /api/token/refresh/ HTTP/1.1" 200 531 [28/Jan/2024 16:52:06] "POST /api/token/refresh/ HTTP/1.1" 200 531 [28/Jan/2024 16:56:07] "POST /api/token/refresh/ HTTP/1.1" 200 531 [28/Jan/2024 17:00:08] "POST /api/token/refresh/ HTTP/1.1" 200 531 Frontend react code: context.js const refreshToken = async ()=>{ let localToken = JSON.parse(localStorage.getItem('authToken')) console.log(localToken) if (localToken){ try{ const res = await fetch(apiUrl + 'token/refresh/',{ method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ 'refresh': localToken.refresh }), }) if (!res.ok){ // if(res.status === 401){ // handleLogout(localToken) // } throw Error } const data = await res.json() setToken(data) setUser(jwtDecode(data.access).username) if(isInit){ setIsInit(false) } localStorage.setItem('authToken', JSON.stringify(data)) } catch (err){ console.log(err) } } } App.js useEffect(()=>{ if(!isLogin){ if(isInit){ refreshToken() } else{ console.log('interval') const interval = setInterval(()=>{ refreshToken() },1000*60*4) return ()=> clearInterval(interval) } } },[token]) backend urls.py I use the built-in Tokenrefreshview. urlpatterns = [ path('', PostList.as_view(), name='listcreate'), path('<int:pk>/', PostDetail.as_view(), name='detailcreate'), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
Using Custom Template Tag Inside Built in tags of Django
I have created a simple tag as below. @register.simple_tag(takes_context=True,name="calculate_billamount") def calculate_billamount(quantity,unitprice): return (quantity * unitprice) {% for order_detail in order_details %} {% if order_detail.orderid == order %} <tr> <td>{{order_detail.productid.productname}}</td> <td>{{order_detail.unitprice}}</td> <td>{{order_detail.quantity}}</td> <td>{% calculate_billamount quantity=5 unitprice=4 %} </td> <td>{{billamount}}</td> </tr> {% endif %} {% endfor %} This is just multiplying 2 numbers and returning the result. I am trying to use above simple tag inside a FOR and IF as shown below. I am getting below error. enter image description here when i try this individually, i am not getting any error i.e. it is working fine. <div> {% calculate_billamount quantity=5 unitprice=4 %} </div> Is there any restriction, that we cant use Custom Simple Template tags inside django built in template tags like for and if? Thanking you. -
django collectstatic not working with s3 backend behind nginx
I have a minio server as my object storage which django uses as its Static file storage (using django-minio-storage). I have set up an Nginx server to proxy minio. When I run the collectstatic command, it gets stuck in the first file and does not put the files to minio. Here is my config: settings.py DEFAULT_FILE_STORAGE = "minio_storage.storage.MinioMediaStorage" STATICFILES_STORAGE = "minio_storage.storage.MinioStaticStorage" MINIO_STORAGE_ENDPOINT = config("MINIO_STORAGE_ENDPOINT", "") MINIO_STORAGE_ACCESS_KEY = config("MINIO_STORAGE_ACCESS_KEY", "") MINIO_STORAGE_SECRET_KEY = config("MINIO_STORAGE_SECRET_KEY", "") MINIO_STORAGE_MEDIA_BUCKET_NAME = config("MINIO_STORAGE_MEDIA_BUCKET_NAME", "") MINIO_STORAGE_STATIC_BUCKET_NAME = config("MINIO_STORAGE_STATIC_BUCKET_NAME", "") MINIO_STORAGE_USE_HTTPS = True MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET = True MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET = True MINIO_STORAGE_MEDIA_OBJECT_METADATA = {"Cache-Control": "max-age=3600"} nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 500; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; error_log /dev/stdout; gzip on; server { listen 80; server_name _; ignore_invalid_headers off; client_max_body_size 0; proxy_buffering off; proxy_request_buffering off; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; real_ip_header X-Real-IP; proxy_connect_timeout 300; proxy_http_version 1.1; proxy_set_header Connection ""; chunked_transfer_encoding off; add_header Access-Control-Allow-Origin "*"; proxy_pass http://minio.svc:9000; } } } collectstatic -v3 result: Deleting 'admin/js/actions.js' the collectstatic command … -
Import package plugin to Django project
I have Python project in which i have plugins with setup.py and Django project in the same level. I want to use those plugins I made inside of Django app views but it cannot find modules I am trying to pass. graph_explorer is Django project. app_platform is Python package plugin which is not django app. api is another Python package plugin which is not django app. In home/views.py I am just trying to call method of app_platform dummy method and I am getting ModuleNotFoundError app_platform. Then i put this code inside of settings.py of Django projcet I get pass first ModuleNotFoundError for app_platform but now I get ModuleNotFoundError for api package which was imported inside of app_platform -
Optimizing Performance in a Django Application
How can I optimize my Django app to improve performance? When load testing my app, the response times start degrading significantly after a moderate number of concurrent users. I need strategies to help it maintain speed as usage increases. I tried caching template fragments and database queries using Django caching framework. I expected this would reduce the load on the database and speeds up rendering, but I didn't see much improvement in my tests. I profiled the app using Django debug toolbar and found some views were running inefficient queries. I attempted to refactor the queries and models, but the performance impact was minimal. I'm not sure what else could be optimized. I added database indexes on the most common query filters and ordering, hoping this would speed up the database operations. However, the speed up was not very significant under load. I deployed the app to a larger server with more CPUs, RAM and SSD storage hoping the increased resources would allow it to handle more load. But I'm still seeing slowdowns and need to optimize the code itself. I expected optimizing templates down to single queries and caching would get page speeds to below 500ms but I'm still … -
How to create hostpath PV for db.sqlite3 database in minikube
I'm building a project(frontend+backend+DB), containerize it, & deploy it on minikube(single node cluster). Due to absence of PV, I lost the data after pod update. Trying to figure out how I can create a PV for hostpath & keep that database on that storage for data persistance. File structure I tried out to link deployment.yml with pvc.yml & pvc.yml with pv.yml. While executing pv.yml file giving node affinity error & host path error. can't find how to resolve the error. settings.py for DB config service.yml pv.yml apiVersion: v1 kind: PersistentVolume metadata: name: mlh-pv spec: capacity: storage: 500Mi accessModes: - ReadWriteOnce hostPath: path: /home/parth/storage-mlh type: DirectoryOrCreate pvc.yml apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mlh-pvc spec: volumeName: mlh-pv storageClassName: manual resources: requests: storage: 500Mi volumeMode: Filesystem accessModes: - ReadWriteOnce deployment.yml (spec section) spec: selector: matchLabels: app: mlh-with-hostpath template: metadata: labels: app: mlh-with-hostpath spec: containers: - name: mlh-with-hostpath image: parth721/django-mlh:4.2 volumeMounts: - name: www-hostpath-storage mountPath: /app/db.sqlite3 resources: limits: memory: "300Mi" cpu: "500m" ports: - containerPort: 8000 volumes: - name: www-hostpath-storage hostPath: path: /home/parth/storage-mlh type: DirectoryOrCreate -
How to Build a Django CreateView with a Pre-Populated ForeignKey Field
I have the following two Django models: class Item(models.Model): description = models.CharField(max_length=250) total_quantity = models.PositiveSmallIntegerField(default=0) def get_absolute_url(self): return reverse_lazy('inventory-item-details', kwargs={'pk': self.pk}) class PurchaseEntry(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) ... I am displaying all of the Item objects I have inside a table. I added a link next to each row item. The link is labeled "Create a Purchase Entry", when opening the link it should display a form for creating PurchaseEntry objects (I'm going to use a generic CreateView for this). Everything is easy with the exception of one key part. When opening the form, I want the Item to be prepopulated with the one I just clicked on its link, so the user won't have to select from a list of items again. The only thing that came to mind was to include the Primary Key when navigating into the form, and use that primary key to select one of the options. But I honestly don't know how to implement this, it's just an idea at the moment, maybe you have a better one? Just for context, and in order for you to help me better here's some more code: My views file: class ItemListView(LoginRequiredMixin, generic.ListView): template_name = 'inventory/home.html' context_object_name … -
Using Django signals during the update instance
I have a project on Django Rest Framework, RabbitMQ and Celery. After sending a post request to create a mailing instance via API, Celery should send messages, and the Celery task number is saved in the mailing instance. The same should happen if you create a mailing instance in the Django admin panel. The mailing instance can be edited both through API and through the Django admin panel (in this case, the outdated Celery task is deleted and a new one is created, the number of the new Celery task is saved in the mailing instance). I solved this problem by overriding the methods in ModelViewSet (DRF) and ModelAdmin (Django). But I would like to solve the problem by using Django signals (on the one hand, this worsens the readability of the code, on the other hand, it eliminates the need to redefine methods). There are no problems with creating and deleting mailing instances and Celery tasks. But I can't create a signal that correctly handles the mailing instance update (the pre_save and post_save signals trigger a cyclic update of the mailing object). Mailing instance update -> a signal is triggered -> a Celery task is created -> the task … -
How Read Replica in django Tenants
I am using Django Tenant for its excellent ability to share a PostgreSQL database in a schema-based manner, which has significantly improved performance for my customers' queries. However, I now need to integrate a read replica for the database to generate reports for my users without impacting the performance of write operations. 've decided to utilize Django's default routing system for this purpose, but I'm encountering some challenges in getting it to work seamlessly with Django Tenants. After extensive research, I found a feature in Django Tenants that seems promising: EXTRA_SET_TENANT_METHOD_PATH (Django Tenants Documentation). However, I'm struggling to find examples or clear guidance on how to implement this correctly. Here's my current setup with the default Django router system: class DatabaseRouter(object): def db_for_read(self, model, **hints): """ Reads go to the read replica. """ return 'replica' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_list = ('default', 'replica') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None I understand that EXTRA_SET_TENANT_METHOD_PATH could be the key to solving this issue, but I'm not sure … -
How do I upload a decoded image to imageField using ContentFile?
Context: I'm creating a chat app in Django, when the user sends an image to a chat the image data get encoded into base 64 (using btoa() javascript func) and get sent to the server so the server could create a new message and store it in the database. This is my model: class Message(models.Model): sender_user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) image = models.ImageField(blank=True, null=True, upload_to='messages/') date = models.DateTimeField(default=timezone.now) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) def __str__(self) -> str: return self.text Problem: Whenever I use a decoded (base 64) image data as the content in the ContentFile class the content seems to be corrupted and the result image in the database can't be opened by any program. This is the code def create_message( self, sender_user_id: Union[str, int], text: str, image: Optional[str], chat_id: Union[str, int], ) -> None: """Creates and stores a new message object in the database. Args: sender_user_id (Union[str, int]): The id (numeric value) of the user that sent the message. text (str): What the message says. image (str): The encoded image data in base64 encoding. chat_id (Union[str, int]): The id (numeric value) of the chat that the sender sent this message on. """ sender_user_instance = User.objects.get(id=sender_user_id) chat_instance = … -
Django Form Generation filtering foreign key data
I have a Django form based on a Model, e.g. car. The model has a foreignkey Parts. I am trying to generate a form but filter the parts on 'available' = True. I can't find a way to do this (without generating it manually). Is there a way to filter the form, like a .filter() on an object? class Car(models.Model): name = models.CharField(max_length=200) parts= models.ForeignKey(Parts,on_delete=models.DO_NOTHING) def __str__(self): return self.name class Parts(models.Model): name = models.CharField(max_length=200) available= models.BooleanField(default=False) def __str__(self) return self.name And the form:- form = CarForm() And the template is using crispy forms {% crispy form %} -
Error "from imp import new_module ModuleNotFoundError: No module named 'imp'" on Debugger Launch Profile
I'm using Microsoft's Python and Django tutorial in VS Code, but when I try to create a debugger launch profile, I get the following error: File "/Users/andres/.vscode/extensions/ms-python.python-2023.4.1/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_utils.py", line 32, in save_main_module from imp import new_module ModuleNotFoundError: No module named 'imp' Also, there's an error message that appears on my "manage.py" file: Exception has occurred: SystemExit 1 File "/Users/andres/Documents/hello_django/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/andres/Documents/hello_django/manage.py", line 22, in <module> main() SystemExit: 1 According to a Google search, seems that the profile is trying to use the "imp" library, which has been deprecated since Python 3.4 and is currently replaced with import lib. However, I have confirmed that my environment is using Python 3.12.1 and I can't identify where this library is being called. I'll really appreciate any help! -
Django is adding an unwanted video to all my webpages [closed]
Django is adding this html to all my webpages. Why is it doing this and how do I stop it? <video src="https://signlearner.com/signs/asl-1/test.mp4" id="signlearner-test-video" style="display: none;"></video> I have tried searching my entire project for the keyword "signlearner" to see where it shows up and it doesn't show up anywhere in my project. I'm expecting that this video doesn't show up at all. Django or something is sneaking it in. -
Profile page not retrieving/updating data
I am unable to fetch data or update data on my profile page. I have taken a look at network tab and have tried to adjust settings.py but have not been able to resolve the issue. When I go on the profile page, I get the following error: Forbidden: /accounts/profile/ "GET /accounts/profile/ HTTP/1.1" 403 58 On the network tab, it says this under Response: {"detail":"Authentication credentials were not provided."} On Cookies header, it says: This cookie was blocked because it had the SameSite=Lax attribute and the request was made from a different site and was not initiated by a top-level navigation I am using Django's built in session framework for simplicity but I ran into this issue. Here are relevant parts of code: Settings.py: DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'accounts.CustomUser' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], } Here is UserProfile.vue: <template> <div> <h1>User Profile</h1> <form … -
geoDjango location api
Please I want to If I can create a website for my university that include map for students to search for specific location in the school. To know if I am able to do, or if it will not work, please suggest me other framework to use. -
PDFViewer for Django
I'm struggling to find a solution to embed a PDF Viewer into my Django website. Currently, I'm using an iframe to display a PDF, but now I want to enable annotations on the PDF directly on the website. The only option I've come across is using PDF.js, but it requires having Node.js alongside Django, and that introduces a host of other challenges. Does anyone know of an alternative approach to achieve this? Thanks! -
Zobrazení nahraných souborů v Django5
Django5 still shows me page not found for my uploaded files. Here are my files, please where is my error, I don't know what to do anymore. urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') models.py class Tutorial(SoftDeleteModel): image = models.ImageField(upload_to='') My images are uploaded in the uploads folder at the same level as the manage.py file. Thanks for your advice. -
Display Loading Screen While Processing Form Data in Django View
In Django I have an app that displays welcome message and empty form and then after submiting the form it displays processed data instead of welcome message and the same form in the same place as before, so user can input new data and submit it again. Simplified view code looks like this: def my_view(request): if request.method == "POST": my_form = MyForm(request.POST) if my_form.is_valid(): # Do some calculations return render(request, 'myapp/my_template.html', {"calculations_results":calculations_results}) else: my_form = MyForm() welcome_message = "Hello" return render(request, 'myapp/my_template.html', "welcome_message":welcome_message) And here is html code: <div class="main-div"> {% if welcome_message %} <div class="welcome-mess-div"> <div class="welcome-mess-div-2"> <h1 class="white-text">Hello!</h1> <br> <br> <h5 class="white-text">Welcome to my website, nice to meet you!</h4> </div> <div class="loading-screen"> <h1>Loading...</h1> </div> </div> {% else %} <div class="results"> {% for result in calculations_results %} <p>{{result}}</p> {% endfor %} </div> </div> <div class="form-div"> <form id="my-form" method="post" enctype="multipart/form-data" onsubmit="displayLoadingScreen()"> {% csrf_token %} {{form.input}} <button type="submit"></button> </form> </div> Please note, that because of the if statement ({% if welcome_message %}), it's possible to use only one template for this. As processing form data takes a while, I want to add a loading screen. I already managed to that when submitting the form is done form the 'welcome_message' perspective (GET … -
Getting 502 Bad Gateway error on nginx proxy manager with gunicorn
I am currently using nginx proxy manager in conjunction with Gunicorn: gunicorn main_app.wsgi:application --bind 0.0.0.0:8000 Everything functions properly when I select HTTP, as shown in the image. However, the only drawback is that static files are not loading because they cannot be located, resulting in a "Not Found: /static/" error. Upon switching to HTTPS, a 502 gateway error is encountered. The following error is logged: my-portfolio-app | [2024-01-27 18:26:18 +0000] [8] [INFO] Starting gunicorn 21.2.0 my-portfolio-app | [2024-01-27 18:26:18 +0000] [8] [INFO] Listening at: http://0.0.0.0:8000 (8) my-portfolio-app | [2024-01-27 18:26:18 +0000] [8] [INFO] Using worker: sync my-portfolio-app | [2024-01-27 18:26:18 +0000] [10] [INFO] Booting worker with pid: 10 my-portfolio-app | [2024-01-27 18:27:23 +0000] [8] [CRITICAL] WORKER TIMEOUT (pid:10) my-portfolio-app | [2024-01-27 23:27:23 +0500] [10] [INFO] Worker exiting (pid: 10) my-portfolio-app | [2024-01-27 18:27:23 +0000] [8] [ERROR] Worker (pid:10) exited with code 1 my-portfolio-app | [2024-01-27 18:27:23 +0000] [8] [ERROR] Worker (pid:10) exited with code 1. When running the application via python manage.py runserver 0.0.0.0:8000 with the scheme set to HTTP, everything works as expected, and static images are loaded. However, I prefer to use Gunicorn. here are my docker-compose files. Django docker-compose file version: '3' services: django_app: container_name: my-portfolio-app volumes: … -
Auto-populating BaseModel fields Django model
I have a base model class which is: class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_createdby', null=True, blank=True, on_delete=models.DO_NOTHING) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_updatedby', null=True, blank=True, on_delete=models.DO_NOTHING) class Meta: abstract = True And all my objects extend this parent class. I want it to automatically adjust the data for created_by and updated_by whenever user .save() the objects(either create or update). And I don't want to manually pass the user every time. I'm graphene and here's an example where I adjust the object and I don't want to pass the updated_by manually. class CreateWorkspace(graphene.Mutation): workspace = graphene.Field(WorkspaceType) class Arguments: name = graphene.String(required=True) description = graphene.String(required=False) @login_required def mutate(self, info, name, description): workspace = Workspace(name=name, description=description) return CreateWorkspace(workspace=workspace) Is there any automated way of doing it without the need to add a code for each subclass? -
Django webapp does not set azure variables
Oke so my main issue is that my django backend that is deployed cannot read Azure env variables. Context: For context i am using github actions to deploy my application. The workflow makes a docker image out of a docker file, then pushes it to my docker registry. After that does the usual installing python packages needed for the app and making migrations for the database. In my local enviroment i am using docker compose with a .env file and this works good, but now that i am deploying the app to azure in a docker container i get issues. My main reason is because i do some logging in my settings.py and also i try to make a user in my database, but i get an error that it can't find my "key" which is correct because before the error i am printing some env values which are empty aswel. root@905a7777498c:/usr/src/app# python manage.py createsuperuser key openai None key db name None key db user None Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File … -
Is there a way to prevent self-deletion of the superuser user in Django?
I need to restrict the self-deletion of super users in django admin (maintaining the ability to edit): If trying to self-delete it should result in a validation error Super user must maintain the ability to remove other users, so has_delete_permission() is not an option for me. I have tried using signals: @receiver(pre_delete, sender=User) def delete_user(sender, instance, **kwargs): if instance.is_superuser: raisePermissionDenied but, it results in HTTP status 403 and not Validation Error. Now I am trying using a custom user admin, where I have tried several methods (override save method, override form), but probably due to my inexperience with django I don't know if this approach is correct. So I turn to those who can help me. Thank you so much -
I have a problem creating a diary with Django
I am making a diary with Django. [urls.py] from django.urls import path from . import views urlpatterns = [ path('', views.diary_index, name = "diary-index"), path('int:month/', views.diary_date , name = "diary-date"), path('int:month/int:day/', views.diary_list, name = "diary-list"), [view.py] def diary_date(request, month) : day = HaruDiary.objects.filter(dt_created__month = month) context = {"month":month} return render(request, "change/diary_date.html", context) def diary_list(request, month, day) : day = HaruDiary.objects.filter(dt_created__month = month, dt_created__day = day) context = {"day":day} return render(request, "change/diary_list.html", context) [Button to select month - html] {% for num in "x"|rjust:"12" %} {{ forloop.counter }} {% endfor %} [After selecting the month, a button to select the day on another page] 01 I don't want to specify the month, but if I don't specify the month by putting int:month/int:day in urls.py, an error keeps popping up. Is there any way to fix this??..Please help... I tried a lot of things through ChatGBT, but I wrote and deleted it, so I don't have any data. I'm sorry. -
Check Constraint in Django
I want to include a check constraint for my model in my members app where the sex field should be male, female or null. Here is my code: from django.db import models from django.db.models import CheckConstraint, Q # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) telephonenum = models.IntegerField(null=True) sex = models.CharField(max_length=10, null=True) CheckConstraint(check=Q((sex == "Female") | (sex == "Male")), name="check_sex") This code is not working I can still make sex field something different than Female or Male. I've tried this code but it didn't work either: from django.db import models # Create your models here. human_sex = ( ("1", "Woman"), ("2", "Man"), ) class Member(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) telephonenum = models.IntegerField(null=True) sex = models.CharField(max_length=10, choices=human_sex, null=True) -
What is the best framework for backend? [closed]
I am learning programming to set up an internet store for myself. I have learned css, html, javascript, react, next for the front end and now I wanted to see what your suggestion is for the back end? Considering that I have no programming experience and I am not going to continue this course. But I will definitely need a lot of help in the future. I have reviewed the following languages and frameworks node JS Laravel Django