Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve logout error when using Django-Jazzmin?
I hope you are doing fine! I have built a django project recently, and while searching for methods to customize the admin panel, I found Django-Jazzmin. It is working and cool and all that, but I have one single problem with it, whenever I try to logout from the admin page, it returns the error 405, a.k.a "method not allowed". I am working with the Django 5.0.2 framework. Did someone find the solution for this problem? I tried to go to "my-virtual_env\Lib\site-packages\jazzmin\templates\admin\base.html" and modify the logout block to : <form method="post" action="{% url 'admin:logout' %}"> {% csrf_token %} <button type="submit" class="dropdown-item"> <i class="fas fa-users mr-2"></i> {% trans 'Log out' %} </button> </form> but it didn't help! -
Django - How to use AJAX within a form
I'm trying to use AJAX for the first time as we have a Django project but a required feature is for one form to behave more like a react app or SPA so I'm trying to use AJAX to add that functionality. I have the following template for the page. It has a form to let the user select from a dropdown what their highest education is and should have a modal appear to let the user input a qualification at a time to be added to the database and displayed on the table. The issue is when the user fills out the modal and clicks submit it seem's to perform just a normal GET request as can be seen below rather than the API request to create qualifications from the modal. AJAX seemingly isn't intercepting the request. GET REQUEST "GET /applications/personal-details/prior-attainment/4/?csrfmiddlewaretoken=s54x6U2BczYThuoYKTryBZwUzdPDuaxmzzubamRRz2Lw4qX1ztjGnAP1XcryPHXP&subject=Maths&qualification_name=Nat+5&date_achieved=2024-02-13&level_grade=A HTTP/1.1" 200 7974 {% extends 'base.html' %} `{% block content %} <div class="container mt-5"> <h2>Prior Attainment and Qualifications</h2> <form id="priorAttainmentForm" method="post" action="{% url 'prior_attainment_view' application_id %}"> {% csrf_token %} <div class="form-group"> <label for="highestQualification">Highest Qualification Level</label> <select class="form-control" id="highestQualification" name="highest_qualification_level"> {% for value, label in form.highest_qualification_level.field.choices %} <option value="{{ value }}" {% if form.highest_qualification_level.value == value %} selected {% … -
ValueError: Cannot serialize
class QuestionMaster(models.Model): """summary Args: id (AutoField): Auto Incremented. subject_id (ForeignKey): Subject name. qzm_id (ForeignKey): Quiz Name. qt_id (Foreignkey): Quiz Type Name. qm_picture (ImageField): Question Reference Image. qm_question (CharField): Question Name. qm_no_options (SmallIntegerField): No of option for question. qm_avg_attempted (DecimalField): Avg percentage user attemped this question. qm_avg_success (DecimalField): Avg percentage answer question correctly. qm_avg_pass (DecimalField): Avg percentage passed question. qm_avg_failed (DecimalField): Avg percentage user choosed wrong question. um_created_by (ForeignKey): User who created question. um_created_dt (DateField): On date question created. qm_is_bonus_qn (BooleanField): Bonus qustion, you will get more points. qm_time_limit (SmallIntegerField): Time limit to chose options. Time is in mili seconds. is_active (BooleanField): Active Status of question. """ id = models.AutoField(primary_key=True) subject_id = models.ForeignKey('SubjectMaster', db_column='subject_id', default=SubjectMaster.objects.get(pk=1), on_delete=models.SET_DEFAULT, verbose_name='Subject ') qzm_id = models.ForeignKey('QuizMaster', db_column='qzm_id', default=QuizMaster.objects.get(pk=1), on_delete=models.SET_DEFAULT, verbose_name='Quiz Name ') qt_id = models.ForeignKey('QuizTypeMaster', db_column='qt_id', default=QuizTypeMaster.objects.get(pk=1), on_delete=models.SET_DEFAULT, verbose_name='Quiz Type ') qm_picture = models.ImageField(upload_to='web', blank=True, null=True, help_text='(Optional)', verbose_name='Q. Image') qm_question = models.TextField(max_length=256, blank=True, null=True, verbose_name='Question ') qm_no_options = models.SmallIntegerField(default=4, verbose_name='Set number of Option ') qm_avg_attempted = models.DecimalField(max_digits=2, decimal_places=2, default=Decimal('00.00'), verbose_name='Attempted (%)') qm_avg_success = models.DecimalField(max_digits=2, decimal_places=2, default=Decimal('00.00')) qm_avg_pass = models.DecimalField(max_digits=2, decimal_places=2, default=Decimal('00.00')) qm_avg_failed = models.DecimalField(max_digits=2, decimal_places=2, default=Decimal('00.00')) um_created_by = models.ForeignKey('UserMaster', db_column='um_created_by',default=UserMaster.objects.get(pk=2), on_delete=models.SET_DEFAULT) qm_created_dt = models.DateField(verbose_name='Created On', default=timezone.now) qm_is_bonus_qn = models.BooleanField(default=False) qm_points = models.SmallIntegerField(default=5) qm_time_limit = models.SmallIntegerField(default=10, help_text='Time … -
Problem with Django-compressor on my test case for Django Views
Context I'm working on a Django project and recently felt the need to test my views to ensure their proper functioning. To achieve this, I decided to set up unit tests and acceptance tests with Behave. However, when running my tests, I encountered an issue related to Django Compressor, a library I use for compressing static files in my project. Problem Every time I try to execute my tests cases about views this error raises : raise OfflineGenerationError( compressor.exceptions.OfflineGenerationError: You have offline compression enabled but key "3e7f5ee33c06d182d3e3f00854139e79ed028f324df0775d235088d452390285" is missing from offline manifest. You may need to run "python manage.py compress". Here is the original content: <link href="/static/themes/snexi/custom.scss" rel="stylesheet" type="text/x-scss" media="screen"/> <link href="/static/css/global.css" rel="stylesheet" type="text/x-scss" media="screen"/> When i try locally the command python manage.py compress this error raises : CommandError: An error occurred during rendering customer/agencies/send_links/list.html: [Errno 21] Is a directory: '/home/rbouard/dev/snexi_v2/src/snexi/static' This is not specific for one template. Configuration Here's an overview of my current configuration: Django version 5.0.1 Django Compressor version 4.4 This my Django settings about static files and compressor : # Static files STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS: List[str] = [os.path.join(BASE_DIR, 'snexi', 'static'), ] SASS_PROCESSOR_ROOT = '%s/static/' % (BASE_DIR,) # FIXME : à bouger … -
consumer: Cannot connect to amqp://awaazde:**@rbmq.local:5671/awaazde: [Errno 111] Connection refused
I am using ECS with EC2 launch type, where my four services are running like Frontend in angular, backend in python django, redis and rabbitmq, Now my my backend is must connect with rabbitmq where rabbitmq make connections with backend service and in backend service celery is there which is give workers to rabbitmq via ampq protocol now for i need to make connection with between two, and i have make connection via .env file. I have enable Service discovery where i have made namespace named "local" , its automatically create privaate hostedzone named "local" into route 53 , now i have create service with service discovery. In Local machine its working with mention envrionment "amqp://guest:@127.0.0.1:5671//" but in ecs in task defination i have decair this environment varibale with service discovery namespace its give me an error like this " consumer: Cannot connect to amqp://guest:@rbmq.local:5671//: [Errno 111] Connection refused." - connot resove the DNS name Note: - with out .env file not able to connect any service via mentions credentials, Please help me with this. I want to make it work by only task defination environment variable not by .env file and also its also able to resolve service discovery … -
Filebeat CPU throttle in kubernetes with django logging
I have a simple Django API served with gunicorn on a Kubernetes cluster. And after long time of running the pod seems to CPU throttle. So I tried to investigate, I used Lucost to swarm my API of requests to see how it handles a unsual amount of requests. Here is a recap of normal activity of the API: 60 requests per hour 10 lines of log per request 600 lines of logs per hour So it's not an intensive requested API. Internally the API will check the body and make a request to CosmosDB server to retreive some data and then format it to send it back to the caller. Less than 200ms requets with very few memory needed. When doing a swarm with locust, I see that the cpu throttles and when using top command in the pod, I see that filebeat uses 40-60% of the cpu. While in normal activity it stays at 0.1-0.5% CPU. I kill -9 the PID of the filebeat, did the same swarm, and everything was smooth. I thought that my log file was too big and filebeat had issue with reading the file. Here is how my django logger is defined: "app_json_file": … -
data is not fetching and displaying in html
<li class="drop-down-bike-1"> <a href="#">MODERN CLASSICS</a> <ul class="modern-list"> <li class="drop-down-bike-display"> <div class="mod-list" style="width:400px; height:600px; overflow-y: scroll;"> hello {% for bi in mod_bike %} <a href="#"> <div class="card mb-3 border-0 listc" > <div class="row g-0"> <div class="col-md-4"> <img src="{{ bi.image }}" class="img-fluid-bike rounded-start" alt="..." > </div> <div class="col-md-8"> <div class="card-body"> <h3 class="card-title bikeName">{{ bi.name }}</h3> <p class="card-text" style="width:200px"><small class="text-muted">price from ₹ {{ bi.price }}</small></p> </div> </div> </div> </div> </a> {% endfor %} </div> </li> </ul> </li> this is the html code for fetching details from database def nav(request): category_names = ['ADVENTURE', 'CLASSICS', 'ROADSTER', 'ROCKET3'] adventure_cat = Category.objects.get(name='ADVENTURE') modern_cat = Category.objects.get(name='CLASSICS') road_cat = Category.objects.get(name="ROADSTER") rocket_cat = Category.objects.get(name="ROCKET3") adv_bike = Bike.objects.filter(category=adventure_cat) mod_bike = Bike.objects.filter(category=modern_cat) road_bike = Bike.objects.filter(category=road_cat) rocket_bike = Bike.objects.filter(category=rocket_cat) context = { "adv_bike": adv_bike, "mod_bike": mod_bike, "road_bike": road_bike, "rocket_bike": rocket_bike, "adventure_cat":adventure_cat, "road_cat": road_cat, "rocket_cat": rocket_cat, "modern_cat": modern_cat, } return render(request, 'nav.html', context=context) this is my views code for fetching data from models the problem is that the data is not fetching and displaying in the html page. i need to fetch and display data in the html page . -
Securely Retrieving File URL from Google Cloud Platform Storage using Django for Frontend Display
How can I securely retrieve the URL of a file uploaded from the frontend to Google Cloud Platform (GCP) storage using Django, and then display it on the frontend for users without making it publicly accessible? Any assistance on this matter would be greatly appreciated. -
Fail to install pymysqlclient for python3.10.11 (via pip3) in cnetOS 7.9 x64
I Fail to install pymysqlclient for python3.10.11 (via pip3) in cnetOS 7.9 x64 Looking in indexes: http://mirrors.aliyun.com/pypi/simple/ Collecting mysqlclient Using cached http://mirrors.aliyun.com/pypi/packages/79/33/996dc0ba3f03e2399adc91a7de1f61cb14b57ebdb4cc6eca8a78723043cb/mysqlclient-2.2.4.tar.gz (90 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/home/code/nrcoa/venv/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> main() File "/home/code/nrcoa/venv/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/home/code/nrcoa/venv/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-hww7nl84/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-hww7nl84/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-hww7nl84/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 155, in <module> File "<string>", line 49, in get_config_posix File "<string>", line 28, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: … -
A lightweight approach to processing Django Queryset data
I am looking for a optimal way to perform simple data processing from Django Queryset. I would like to not need to install libraries with high volumes like Pandas or numpy. The number of rows in Queryset should not exceed 2000. The idea is to perform basic functions such as x1, x2, x3 below. I want to avoid a separate database query for each of them so I'm thinking to get all this data once from the database, convert it to a standard data structure and calculate the results. Queryset Sample: T1_id T2_id T1_value T2_value 1 2 2 0 3 5 0 0 4 1 1 1 2 7 0 3 Pandas code equivalents: data = [[1, 2, 2, 0], [3, 5, 0, 0], [4, 1, 1, 1], [2, 7, 0, 3]] df = pd.DataFrame(data, columns=['T1_id', 'T2_id', 'T1_value', 'T2_value']) x1 = df[df['T1_id'] == 1]['T1_value'].mean() # Mean of T1_value from rows where T1_id == 1 x2 = df[df['T1_id'] == 1]['T2_value'].sum() # Sum of T2_value from rows where T1_id == 1 x3 = len(df[df['T1_id'] == 1]) # Number of rows where T1_id == 1 -
Django application deployed on Railway.app experiencing repeated worker timeouts and SIGKILL signals
I have deployed a Django application on Railway.app, utilizing Gunicorn 21.2.0 as the WSGI server. However, I'm encountering a persistent issue where the workers are timing out and subsequently being terminated with a SIGKILL signal. Here's a snippet of the logs: [2024-02-13 07:26:54 +0000] [7] [CRITICAL] WORKER TIMEOUT (pid:22) [2024-02-13 07:26:55 +0000] [7] [ERROR] Worker (pid:22) was sent SIGKILL! Perhaps out of memory? ... [2024-02-13 07:35:04 +0000] [7] [CRITICAL] WORKER TIMEOUT (pid:54) [2024-02-13 07:35:05 +0000] [7] [ERROR] Worker (pid:54) was sent SIGKILL! Perhaps out of memory? This pattern repeats consistently, with workers timing out and subsequently being killed. The application appears to be experiencing memory issues, as suggested by the error message. I've tried adjusting various configurations, such as increasing worker timeouts and tweaking memory allocation, but the problem persists. My suspicion is that the application may be exceeding the memory limits imposed by the hosting environment. Has anyone encountered similar issues while deploying Django applications on Railway.app? Any insights or suggestions on how to diagnose and resolve this problem would be greatly appreciated. Thank you! -
pythonanywhere live chat django project is not showing messages
I created a ecommerce live chat Django project and I deployed it on PythonAnywhere in my local host its working but on PythonAnywhere message is not sending can anyone tell me the solution I didn't get any solution if someone have please tell me -
Managing Multiple Types of User with Custom Permissions
I'm facing issues with managing different types of users. And need to customize the admin panel for each users having custom permission. This is my first major project and do not have any mentor to guide me. Following are the models, I'm working with. The actual models have more fields. class User(AbstractUser): ''' Regional Admin and Admin can login to the admin panel. Regional Admin can only access the nodes data of regions they are assigned to. ''' class UserTypeChoices(models.TextChoices): ADMIN = 'ADMIN', 'Admin' REGIONAL_ADMIN = 'REGIONAL_ADMIN', 'Regional Admin' NORMAL_USER = 'NORMAL_USER', 'Noramal User' email = models.EmailField(unique=True, validators=[EmailValidator(message="Invalid Email Address")]) user_type = models.CharField(max_length=20, choices=UserTypeChoices.choices, default=UserTypeChoices.NORMAL_USER) def __str__(self) -> str: return self.username # Country Model class Country(models.Model): name = models.CharField(max_length=100, unique=True) population = models.PositiveBigIntegerField(validators=[MinValueValidator(0)], default=0) class Meta: verbose_name_plural = "Countries" def __str__(self) -> str: return self.name # Each country might be divided into one or more zones class Region(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=100) # East West North South def __str__(self) -> str: return self.name # Each nodes represents some point in a particular region class Node(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) name = models.CharField(max_length=100) length = models.FloatField(validators=[MinValueValidator(0)]) def __str__(self) -> str: return self.name The Admin here is the super … -
django,redis,rqworker,docker config issue
Im trying to use redis to queue tasks with rqworker for a django backend which has asgi application as well. I used daphne to run asgi application. Im trying to dockerize the whole application using docker compose. This is my Django project directory structure: docker-compose.yml version: '3' services: backend: build: . command: python3 manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/app depends_on: - redis worker: build: . environment: - DJANGO_SETTINGS_MODULE=backend.settings command: daphne -b 0.0.0.0 -p 8001 backend.asgi:application volumes: - .:/app depends_on: - redis worker2: build: . environment: - DJANGO_SETTINGS_MODULE=backend.settings command: python3 manage.py rqworker default volumes: - .:/app depends_on: - backend - redis redis: image: redis:latest ports: - "6379:6379" I'm facing this issue: (chai) narsimhar@Narsimhas-MacBook-Pro backend % docker-compose up ..... ..... ..... ..... worker-1 | File "/app/./backend/asgi.py", line 15, in <module> worker-1 | from users.routing import websocket_urlpatterns worker-1 | File "/app/./users/routing.py", line 3, in <module> worker-1 | from . import consumers worker-1 | File "/app/./users/consumers.py", line 8, in <module> worker-1 | from users.tasks import prep_text worker-1 | File "/app/./users/tasks.py", line 20, in <module> worker-1 | async def prep_text(text): worker-1 | File "/usr/local/lib/python3.10/site-packages/django_rq/decorators.py", line 28, in job worker-1 | queue = get_queue(queue) worker-1 | File "/usr/local/lib/python3.10/site-packages/django_rq/queues.py", line 164, in get_queue worker-1 … -
Need guidance for project on "Automatic resume parser and ranker" in python
this is my first time doing an AI project and I don't know anything. The project is to build a website that converts the unstructured resume into structured format and the ranks them based on given job description. The ranking is done using a hybrid model of KNN and RNN-LSTM. Please give me the steps I need to follow to create this project (also if possible please provide the topics I need to learn or links). I'd be thankful if the steps are detailed as possible. (note: this if for my final year project and doesn't need to be efficient or something complicated, I only need the output.)(PLEASE HELP) I am able to build the website with HTML,CSS and JS, but still have not decided on the backend, should I use Django or Node.js? -
Creating a web app from Jupyter Output Interface using Django or React?
I am working on a project for a research group where I have to create a web app for this tool, AdaTest. Currently, the tools runs on a jupyter notebook, where an interface pops up and the user can interact with the tool to approve and deny tests for machine learning models. I want to essentially port this interface onto a web app. Any thoughts on the best way to go about doing this? Or would I have to essentially reinvent the tool altogether to make this work? I've tried using the repl_html method to generate a html script, and then using Django to render that html code as a HttpResponse. However, the tool did not work as anticipated and the tests did not render. I've also thought about directly moving the kernel of the notebook into a web app, making the whole kernel the interface. However, I have no idea where to begin with that. Any suggestions are appreciated! -
How do I create a custom RegistrationForm using django-registration in Django 5.0.2 with Django Registration 3.4
I admit I'm new to Django but I've been banging my head against the wall with this problem all day. I've created a new application and inherited classes from django_registration, but it seems my form data is never saved. My fields show up and are accessible on the front end as well as the administration area, but user registration never seems to happen and I don't get an error. (It is working fine with standard django-registration but I want to expand it and plan for the future.) forms.py from django_registration.forms import RegistrationForm from authentication.models import MyCustomUser from django import forms class MyCustomUserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = MyCustomUser #fields = "__all__" fields = ['username', 'email', 'first_name', 'last_name', 'profile_photo', 'password1', 'password2'] models.py from django.contrib.auth.models import AbstractUser from django.db import models from django import forms class MyCustomUser(AbstractUser): ROLE_CHOICES = ( ('APPLICANT', 'Applicant'), ('EMPLOYEE', 'Employee'), ('ADMIN', 'Admin'), (None, 'None') ) role = models.CharField(max_length=30, choices=ROLE_CHOICES) profile_photo = models.ImageField() #username = forms.CharField(max_length = 100) #this is already handled for us in AbstractUser #email = forms.EmailField(max_length = 100) #this is already handled for us in AbstractUser #password1 = forms.CharField(widget = forms.PasswordInput(), max_length = 100) #this is already handled for us in AbstractUser #password2 = forms.CharField(widget = forms.PasswordInput(), … -
ajax real-time page refresh
Well, in general, I'm doing a small project on django and I decided to implement a convenient search for any parameter from my form. all js was written to me by chatgpt and I don't understand it at all at all, and in general I'm working with "search" for the first time. also, what worries me now is that it is actually being searched for, but very crookedly. everything is shaking and the header is duplicated under the search. I need a dynamic page update when searching for the number, VIN, sent_at, status fields. html {% block title %} Для крутых {% endblock %} {% block content %} <div class="container"> <div class="row mt-3"> <input type="search" id="search-input" name="q" class="form-control form-control-dark text-bg-dark" placeholder="Поиск..." aria-label="Поиск"> <div id="applications-list" class="mt-3"> {% for application in applications %} <div class="application-item"> <p><strong>Имя:</strong> {{ application.name }}</p> <p><strong>Номер телефона:</strong> {{ application.number }}</p> <p><strong>VIN номер машины:</strong> {{ application.VIN }}</p> <p><strong>Описание проблемы:</strong> {{ application.description }}</p> <img src="{{ application.image.url }}"> <p><strong>Отправлено:</strong> {{ application.sent_at }}</p> <p><strong>Статус:</strong> {{ application.status }}</p> <br> </div> {% endfor %} </div> {% include 'includes/pagination.html' %} </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { function searchAndUpdate() { let searchQuery = $('#search-input').val(); $.ajax({ url: window.location.href, data: { q: searchQuery }, success: function(data) { … -
IntegrityError at /password-manager/user/17/add_password/
I'm trying to implement a password-manager app for storing passwords. Here I'm trying to add a password for the current user. I'm getting this error: IntegrityError at /password-manager/user/17/add_password/ FOREIGN KEY constraint failed This is the view: def user_add_password(request,id): obj = get_object_or_404(UserModel, id=id) form = PasswordForm(request.POST or None, user=obj) if form.is_valid(): form.instance.user = obj form.save() return redirect(reverse('password:user_home_page', kwargs={'id': obj.id})) context = { 'form': form, 'object': obj } return render(request, 'add_password.html', context) This is the form: class PasswordForm(forms.ModelForm): class Meta: model = Password fields = ['user', 'platform', 'password'] widgets = { 'user': forms.HiddenInput(), } def __init__(self, *args, **kwargs): # Get the user from the initial data or set it to None user = kwargs.pop('user', None) print(user,'@@@@@@@@@@@@@@@@@@@@22') # Call the parent constructor super(PasswordForm, self).__init__(*args, **kwargs) # Set the initial value for the user field if user: self.fields['user'].initial = user This are the Models: secret_key = settings.SECRET_KEY f = settings.FERNET_INSTANCE salt = settings.SALT # Create your models here. class UserModel(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) def get_absolute_url(self): return reverse('password:user_detail', kwargs={'id': self.id}) def save(self, *args, **kwargs): self.password = bcrypt.hashpw(self.password.encode('utf-8'), salt).decode('utf-8') super().save(*args, **kwargs) class Platform(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name @staticmethod def initialize_platforms(): Platform.objects.all().delete() platforms= ['Facebook' , 'Instagram' , 'Twitter' ,'Google' … -
Why my deploy to railway of a django project is getting a error?
I am trying to do a deploy of a django project do railway and I am getting this error: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: --log-file-- I don't know why is showing the argument --log-file--, because in my file is in the correct form --log-file - Like this: web: gunicorn agenda.wsgi --log-file - If someone have this error too, could help me? I am expecting the railway deploy my website -
django order_by("datetime") does not work
I am trying to get all objects off "Chat" distinct by the fields phone_number (CharField) and agent (ForeignKey) and order by datetime DateTimeUTCField(default=datetime.now) chats = self.get_queryset().order_by('phone_number', "agent","-datetime").distinct("phone_number", "agent") for chat in chats: print(chat.datetime) but when I see the order of the chats, the chats are not sorted by datetime 2024-02-12 14:12:29.352192 2024-02-12 16:14:36.196964 2024-02-12 14:20:26.696088 2024-02-12 14:16:36.225550 2024-02-12 17:25:45.896345 2024-02-12 17:35:58.424937 2024-02-12 15:07:23.808822 2024-02-12 16:14:37.775311 2024-02-12 14:19:28.939897 2024-02-12 16:14:34.493954 2024-02-12 16:41:08.697777 Why? I think is because i have also order_by phone_number and agent , but if I remove then , django raises SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("lolo_agents_chat"."phone_number", "lolo... -
AttributeError: Got AttributeError when attempting to get a value for field `value` on serializer
I am trying to serialize the data in my ecommerce project with DRF. My db design is such that I have a Product which can have multiple ProductVariant and each ProductVariant can have multiple ProductVariantProperty associated with it. This is my models.py class ProductVariantProperty(models.Model): name = models.CharField(max_length = 255, null = True, blank = True) class ProductVariantPropertyValue(models.Model): value = models.CharField(max_length = 255, null = True, blank = True) property = models.ForeignKey( ProductVariantProperty, on_delete = models.CASCADE, null = True, blank = True, related_name = 'product_variant_property_values' ) class Product(models.Model): name = models.CharField(max_length = 255, unique = True, null = False, blank = False) ... class ProductVariant(models.Model): product = models.ForeignKey( Product, on_delete = models.CASCADE, null = False, blank = False, related_name = 'product_variants' ) name = models.CharField(max_length = 255, unique = True, null = False, blank = False) ... properties = models.ManyToManyField(ProductVariantProperty, blank = True, related_name = 'product_variants') This is my request body { "name": "Product 1", ... "product_variants": [ { "name": "Example Variant 1", ... "properties": [ { "name": "color", "value": "blue" }, { "name": "size", "value": "large" } ] }, {...} ] } This is the error i got when i tried to serialize. AttributeError: Got AttributeError when attempting to get … -
Django Logout Get method failed when attempting Post method
I am trying to build a simple login-logout mechanism with Django. The login is already working fine. Below are the relevant code snippets: project_name/main/urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ # ... path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), ] project_name/templates/registration/logged_out.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Logged out</title> </head> <body> <form method="post" action="{% url 'logout' %}"> {% csrf_token %} <p>Logged out!</p> <a href="{% url 'login' %}">Click here to login again.</a> </form> </body> </html> I have a href element on project_name/templates/profile.html that goes to logout: <p><a href="{% url 'logout' %}">Logout</a></p> But when I click it, I get the following error: Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/ I'm quite confused because the method attribute in the form element in logged_out.html is clearly "post". I looked at previous questions and none of them have this exact issue. Could anyone kindly tell me what is going on? Thanks in advance. -
Table & Django Templates
Consider the following models: Animal --> Pet (with foreign key to Animal) Both objects have an integer field - ordinal - that is supposed to control the order of their listing. Say we have 2 instantiations of animals: Dog, Cat And we have 5 Pets: Dog --> Fido, Scooter, Ralphie Cat --> Murphy, Winston Typically, I would represent them with unordered lists. But let's say we would want to pass in context for an HTML table instead... Dog...................Cat -------------- ------------------ Fido...................Murphy Scooter............Winston Ralphie The Animal models would be represented in the table headers, and their children of the Pet class instantiations would fall under them in the table rows. From there, the end-user would click on a hyperlink with the object name to drill down to that pet, with a slugfield providing the argument for the url. What this means is, I only need the Animal name for the table headers, but I need both name and slug for their Pets. Having all of that to consider, there is one more consideration... Note that there is an empty cell for cats, since there's one less cat. How would I create the context I would pass to the template, without (nothing) … -
Getting BAD REQUEST, while fetching address it's returning empty string
views.py: from django.shortcuts import render from geopy.geocoders import Nominatim from django.http import JsonResponse Create your views here. def single_address(request): if request.method == 'POST': #print(request) address = request.POST.get('address','') #print(type(address)) if address: # Initialize Nominatim geocoder geolocator = Nominatim(user_agent="my_geocoder") try: # Geocode the address location = geolocator.geocode(address) if location: # Extract latitude and longitude latitude = location.latitude longitude = location.longitude return JsonResponse({'latitude': latitude, 'longitude': longitude}) else: return JsonResponse({'error': 'Geocoding failed for the address'}, status=500) except Exception as e: return JsonResponse({'error': f'Error: {str(e)}'}, status=500) else: return JsonResponse({'error': 'Address not provided'}, status=400) else: # Render the HTML template for the form return render(request, 'address/single_address.html') single_address.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get Coordinates for Single Address</title> </head> <body> <h1>Get Coordinates for Single Address</h1> <form id="addressForm"> {% csrf_token %} <label for="address">Enter Address:</label> <input type="text" id="address" name="address" required> <button type="submit">Get Coordinates</button> </form> <div id="response"></div> <script> document.getElementById('addressForm').addEventListener('submit', function(event) { event.preventDefault(); // Prevent form submission var address = document.getElementById('address').value; // Make an AJAX request to the view fetch("{% url 'single_address' %}", { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'address': address }) }) .then(response => response.json()) .then(data => { // Display the response document.getElementById('response').innerText = JSON.stringify(data, null, …