Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django IntegrityError: Unique Constraint Violation
I'm working on a Django project using Django Rest Framework (DRF) and PostgreSQL, with a Scan model that tracks different phases of a label scan. I've set a unique constraint on the combination of label_id and phase fields to prevent duplicate scans for the same label in the same phase. Here’s my Scan model: class Scan(models.Model): user = models.ForeignKey("accounts.User", on_delete=models.CASCADE) label = models.ForeignKey("labels.Label", on_delete=models.CASCADE) phase = models.IntegerField( choices=ScanPhaseChoice.choices, default=ScanPhaseChoice.unknown.value, ) distribution = models.ForeignKey("factories.Distribution", null=True, blank=True, on_delete=models.CASCADE) store = models.ForeignKey("factories.Store", null=True, blank=True, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: unique_together = ["label", "phase"] When I try to create a new scan, I get this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "labels_scan_label_id_phase_81ec6788_uniq" DETAIL: Key (label_id, phase)=(413, 1) already exists. I’ve verified that the combination of label_id and phase already exists in the database, but I’m not sure why this error is raised when I've used full_clean() to validate data in the save() method. What I’ve Tried Ensuring the constraint is defined in both the database and the model’s Meta class. Adding validate_unique in the clean and save methods, but it didn’t prevent the error. Using full_clean() in the save method, expecting it to check for unique constraints. Questions … -
(failed)net::ERR_BLOCKED_BY_ORB and (canceled) error while using gcp as backend for django app
i have a django application to write articles and upload images i used to store my media files in local now i want to change it to GCS bucket while doing it after creating a gcloud.py and changing the media_url and default_file_storage all these options to use GCP bucket i am still facing an error while uploading of an image in the django logs i am getting 200 status but i cant see the images in my bucket when i check the inspect tabs network i found that at the status column there are 2 errors beside my image (failed)net::ERR_BLOCKED_BY_ORB and (canceled) I was trying to change my django applications media storage from local to GCP bucket -
send post but treated as GET?? rest-framework-bundle
I have api with django rest framework bundle My api is like this, only accepts POST. @api_view(["POST"]) @authentication_classes([]) @permission_classes([]) def myapi_v1_result(request): then I sent to this api with POST button However it gets , Method Not allowed why does this happen? INFO: 127.0.0.1:49305 - "POST /myapi/v1/result HTTP/1.1" 200 OK Method Not Allowed: /myapi/v1/result WARNING:django.request:Method Not Allowed: /myapi/v1/result -
Formatting F Strings in Python - Using For Loop in F String in Python
I am Working With Django Email Templates To Send PNR Details, Now I Wanted to Share PNR Details in Text Format. For This I Used Serializer to Send Data But Nested Passenger Details are not specific they are dynamic some pnr have 2 passengers while some have 6 passengers. Now, When I Serialize the Data i Get {'id': 8, 'pnr': pnr_number, 'train_number': '12916', 'train_name': 'ASHRAM EXPRESS', 'boarding_date': '2023-19-12T00:00:00+05:30', 'boarding_point': 'ADI', 'reserved_from': 'JP', 'reserved_to': 'JP', 'reserved_class': 'SL', 'fare': '350.00', 'remark': None, 'status': 1, 'modified': '2024-05-00T17:06:13.065600+05:30', 'train_status': '', 'charting_status': 'Chart Not Prepared', 'passengers_details': [{'id': 7, 'name': 'Passenger 1', 'booking_status': 'RLWL/76/GN', 'current_status': 'RLWL/62'}, {'id': 8, 'name': 'Passenger 2', 'booking_status': 'RLWL/77/GN', 'current_status': 'RLWL/63'}]} And I Wanted to Use Fstring to Format This Text Hi {username}, Exciting news! Your PNR details for your upcoming journey are ready. PNR Number: {pnr} Here's a quick summary of your booking: PNR Details: PNR Number: {pnr} Train Number: {train_number} Train Name: {train_name} Reservation Class: {reservation_class} Boarding Date: {boarding_date}} Reserved From: {reserved_from} Reserved To: {reserved_to}} Boarding From: {boarding_from} Passenger Details: Name: {passenger.name} Booking: {passenger.booking_status} Current: {passenger.current_status} Other Details: Fare: {fare} Remark: {remark} Status: {train_status} Charting: {charting_status} Have a safe and pleasant journey! Note: This uses scrapping of PNR status from … -
Filter by date yields empty queryset
Django version 4.2.x The user picks a date, and I am trying to compare that to entries in the TeacherAvailability model. The model: class TeacherAvailability(models.Model): teacher = models.ForeignKey(TeacherProfile, on_delete=models.CASCADE) student = models.ForeignKey( StudentProfile, on_delete=models.CASCADE, default=None, blank=True, null=True) timeslot_start = models.DateTimeField(auto_now_add=False) with the function: def get_dayagenda(self, selectedDate): year = int(selectedDate[:4]) month = int(selectedDate[5:7]) day = int(selectedDate[8:10]) And I have tried to return both of the following: TeacherAvailability.objects.filter(student_id=None).filter(timeslot_start__year=year, timeslot_start__month=month, timeslot_start__day=day).values_list('id', 'timeslot_start', 'student_id', 'teacher_id') and TeacherAvailability.objects.filter(student_id=None).filter(timeslot_start__date=datetime.date(year, month, day)) Both are yielding an empty queryset, however if I try just to filter by year I get some results. -
Unable handle the Csrf-Token for GET request in Django
In Django framework, When it was a POST request, if you modify the Cookie CSRF token, its throws the 403 error. But when it was a GET request, I tried to modify the Cookie CSRF-token, and it returned a 200 OK status code. I also want to validate the token for the GET request. I mentioned {% csrf_token %} in the Forms templates , but it could not handle this issue for GET request. I tried @csrf_protect in the view , it did not helpful. -
Wagtail(django) and Nginx Static files not being served
I am deploying a wagtail site with nginx on rocky linux however, I cannot get the static files to be served by nginx. My nginx site config is as follows: server { listen 80; server_name 10.4.0.189; root /home/wagtail/apps/my_site; charset UTF-8; error_log /home/wagtail/apps/my_site/nginx-error.log; location = /favicon.ico {access_log off; log_not_found off;} location static/ { root /home/wagtail/apps/my_site/; } location / { proxy_set_header Host $http_host; 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_pass http://unix:/run/gunicorn.sock; } } I have tried multiple block location configurations including alias. I have checked read/write permissions to the directory where the application resides: drwxrwxr-x. 6 wagtail nginx 4096 Nov 7 08:27 . drwxrwxr-x. 4 wagtail nginx 4096 Nov 6 14:41 .. -rwxrwxr-x. 1 wagtail nginx 2029 Nov 6 14:41 Dockerfile -rwxrwxr-x. 1 wagtail nginx 376 Nov 6 14:41 .dockerignore drwxrwxr-x. 6 wagtail nginx 4096 Nov 6 14:44 home drwxrwxr-x. 6 wagtail nginx 4096 Nov 7 08:34 my_site -rwxrwxr-x. 1 wagtail nginx 256 Nov 6 14:41 manage.py -rwxrwxr-x. 1 wagtail nginx 56199 Nov 7 13:31 nginx-error.log -rwxrwxr-x. 1 wagtail nginx 35 Nov 6 14:41 requirements.txt drwxrwxr-x. 4 wagtail nginx 4096 Nov 6 14:44 search drwxrwxr-x. 11 wagtail nginx 4096 Nov 7 13:07 static wagtail : wagtail nginx Nginx is … -
Problem with user authentication in django
For a reason unknown to me, when authenticating a user, I enter the following data: email and password, as a result, super users are authenticated, but ordinary users are not. What can be done about this? Has anyone encountered such a problem? Please help me solve this, I'm completely new to Django. Here are the files in the project (if you need any other files, write): views.py from django.contrib.auth import authenticate, login from django.http import HttpResponse from django.shortcuts import render, redirect from users.models import User def register(request): if request.method == "POST": username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") # password2 = request.POST.get("password2") phone_number = request.POST.get("phone_number") user = User ( username = username, email = email, password = password, phone_number = phone_number ) user.save() return redirect('main:index') return render(request, 'users/register.html') def user_login(request): if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") user = authenticate(email=email, password=password) if user and user.is_active: login(request, user) return HttpResponse('Authenticate!') else: return HttpResponse('No Login!') return render(request, 'users/login.html') models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractUser from users.managers import CustomUserManager class User (AbstractUser): username = models.CharField(max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(null=True, blank=False, max_length=30) phone_number = PhoneNumberField(region="IN", unique=True, null=True, blank=False) USERNAME_FIELD … -
Django parse url differently
I have an url, that contains a semicolon: /?a=3;4. I want to make request.GET['a'] output 3;4, right now it is 3. Is it possible? Thank you. -
Django Ninja Pagination: Next page exists?
Out of the box pagination Django Ninja's PageNumberPagination serializes response in the following way: { "items": [ {...}, ... ], "count": 172 } The question is how to determine if next page object exists? Sure, one can try to retrieve it from page size by the length of items list, but this will not work if count is aliquot to the page size, so the next page will be empty list. Is there a convenient way or workaround to get this information on the frontend? For the sake of simplisity, let's just consider example from the docs: from ninja.pagination import paginate, PageNumberPagination @api.get('/users', response=List[UserSchema]) @paginate(PageNumberPagination) def list_users(request): return User.objects.all() -
Django UpdateView doesn't save a new value
I have a forum app, its structure is "forum-subforum-topic-comment". Topics are exclusive for their subforum, comments are exclusive for their topic and displayed only inside the topic. Views are implemented mostly via class-based-views. While creating a new Topic, you have to define not only the field subject, but also the initial comment, first_comment. It is pretty similar to the objects of the Comment model, but is effectively a part of the Topic model. So, the problem is that while my UpdateView for comments (UpdateComment) works well, and comments are edited without any issues, the UpdateView for a first_comment of Topic objects, though returning no error, doesn't edit the field. And that's sad. You know it's very sad, when you do it the way it must work, it seems like it must work, you waste lots of time to make it work, but it refuses to work by any reason. models.py (Topic and Comment models only): class Topic(models.Model): subject = models.CharField(verbose_name='Заголовок', max_length=255, unique=True) first_comment = models.TextField(verbose_name='Сообщение', max_length=2000, default='') slug = models.SlugField(default='', unique=True, max_length=25, editable=False) subforum = models.ForeignKey('Subforum', verbose_name='Раздел', on_delete=models.CASCADE, related_name='subforum') creator = models.ForeignKey(User, verbose_name='Создатель темы', on_delete=models.SET('deleted'), related_name='creator') created = models.DateTimeField(auto_now_add=True) closed = models.BooleanField(default=False) #votes = GenericRelation(LikeDislike, related_query_name="topics_votes") objects = models.Manager() class … -
Mock a ManyToMany method add
I need help. I want to test an exception case in my test, so I have to mock 'add()' method. How can I test it? my model: class CourseGroup(models.Model): students = models.ManyToManyField( "users.User", blank=True, related_name="course_groups_students", ) my method: def add_student_to_group(student: User): course_groups = CourseGroup.objects.all() for group in course_groups: try: group.students.add(student) except Exception as ex: sentry_message( title="some title", message="some message", ) my test I'm trying to do it like this, but it's not working. class AddStudentToGroupTestCase(TestCase): @classmethod def setUp(cls): cls.course_group_1 = CourseGroupFactory() cls.course_group_2 = CourseGroupFactory() cls.course_group_3 = CourseGroupFactory() cls.student = StudentFactory() @patch("users.service.sentry_message") @patch("users.models.CourseGroup.students.add") def test_add_student_with_exception(self, mock_add, mock_sentry_message): mock_add.side_effect = Exception("ERROR") # call with self.assertRaises(Exception): add_student_to_group(student=self.student) mock_sentry_message.assert_called() I get an error: AttributeError: <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x7f643f2afd10> does not have the attribute 'add' Has anyone encountered something like this? -
how to make dynamic choicefields based on models in django forms?
I have a Group Model that I want to use it's objects in my form. I would like to have a dynamic choices tuple based on Group model objects! How can I do this? I used the code below : class Employee_Form(forms.Form): GROUPS = () try: GROUPS = ( ) for i in Group.objects.all(): GROUPS += ((i.name , i.name),) except: pass phone = forms.CharField(max_length=12) name = forms.CharField(max_length=50) position = forms.CharField(max_length=30) group = forms.ChoiceField(choices=GROUPS) This code have a problem . every time you add a new object to your model you have to restart the server after that But it does not recommended! and one important thing is I want to use forms.Form not the modelForm. -
Filter Related Objects in DRF Serializer Based on User's Permission
I’m working with Django Rest Framework and need to filter related objects in a serializer based on custom user permissions. Specifically, I want to conditionally include or exclude certain related objects (in this case, comments) in the serialized response depending on the user's relationship to the primary object (a blog post). For example, a user should see all comments if they have special permissions (such as being the owner or a designated collaborator on the blog post). Otherwise, they should only see comments that meet certain criteria (e.g., approved comments). I've come up with this solution for now, but I'm unsure if it's the most efficient approach. How should I address this issue? # models.py from django.db import models from django.contrib.auth.models import User class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() owner = models.ForeignKey(User, related_name="owned_posts", on_delete=models.CASCADE) writers = models.ManyToManyField(User, related_name="written_posts") class Comment(models.Model): post = models.ForeignKey(Blog, related_name="comments", on_delete=models.CASCADE) approved = models.BooleanField(default=False) text = models.TextField() # serializers.py from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class BlogSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField() class Meta: model = Blog fields = '__all__' def get_comments(self, obj): user = self.context['request'].user if obj.owner == user or user in obj.writers.all(): # Show all comments … -
add chart with charjs to django application
Hi my goal is to display a chart using chartjs with plain html/css/js I am not using any framework. I have my method backend side that returns a context with the following elements: context = {'client_id' : client_id, 'year' : year, 'spending' : monthly_spending} The goal is on my frontend to display a bar chart with the spending for each month in a year. I tried many things but nothing load I get error. What I did basically / {% block body %} <section> <div> <canvas id="spendingChart" width="500" height="500"></canvas> </div> </section> </main> {% endblock body %} {% block script %} <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.min.js"></script> <script> const spendingData= {{ monthly_spending | safe }} const myChart = new Chart(document.getElementById('spendingChart').getContext("2d"), { type: 'line', data: { datasets: [{ label: 'spending Over Time', data: spendingData, borderColor: 'rgba(75, 192, 192, 1)', backgroundColor: 'rgba(75, 192, 192, 0.2)', fill: true, }] }, options: { responsive: true, scales: { x: { type: 'time', title: { display: true, text: 'Date' } }, y: { title: { display: true, text: 'spending' } } } } }); </script> {% endblock %} Nothing loads and I have 2 errors in my console but I am not sure what to do: Uncaught SyntaxError: Cannot use import … -
Django Crispy Form {% crispy form %} does not show errors while {{ form|crispy }} does not work with FormHelper
How do I get both layout helper and display error messages working in crispy forms. I created a simple form just one field to upload a file. # forms.py class FileUploadForm(forms.Form): file = forms.FileField(label='File', validators=[FileExtensionValidator(allowed_extensions=ALLOWED_EXTENSIONS)]) def __init__(self, *args, **kwargs): print ("==== FileUploadForm:__init__ ====") super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_class = 'form-horizontal' self.helper.form_style = 'inline' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Field('file', css_class='form-control-sm') # Apply Bootstrap's small form-control ) I noticed the layout helper works when using {% crispy form %}. However it will not show errors such as when I leave the input blank or upload an invalid file extension. {% crispy form %} example If I used {{ form|crispy }}, the layout helper does not work but the errors are displayed. {{ form|crispy }} example Relevant information django-crispy-forms==2.1 Django==5.0.6 crispy-bootstrap5==2024.2 Python 3.12.5 # html <!-- Bootstrap 5.3.3 --> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <!-- Javascript Bootstrap --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script> # settings.py INSTALLED_APPS = [ 'crispy_forms', # package: crispy form for bootstrap 'crispy_bootstrap5', # bootstrap 5 ] CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" -
Database constraint on latitude and longitude of a PointField with MySQL backend
I have a following Django model: class Place(models.Model): location = models.PointField(geography=True) The location field seems to happily accept any arbitrary number for latitude and longitude. Even past the limits of +-180 and +-90. My research says this is due to SRID not being set in the database column, even though the database was generated by Django. I do belive the MySQL backend just does not support properly setting the SRID on database level. To prevent any issues from arising, I'm trying to write constraints on the field. However, I do not seem to be able to generate a working constraint object. Perfect outcome would be checking the lat & lng are in range of the PointField object's extent field, but I'd be happy to settle for a hardcoded limits also. Alternatively, a solution to make the database respect the proper lat & lng limitations without any extra Django constraints would be greatly appreciated. I've tried many iterations of something like this. I have not found a combination that would make both python and MySQL happy. class GeometryPointFunc(Func): template = "%(function)s(%(expressions)s::geometry)" def __init__(self, expression: any) -> None: super().__init__(expression, output_field=FloatField()) class Latitude(GeometryPointFunc): function = "ST_Y" class Longitude(GeometryPointFunc): function = "ST_X" ... class … -
Django Channels direct messages over channels
I have a basic setup where a user connects to server I save the channel_name into DB. And later on I try to send the message to connected users. class CommandConsumer(WebsocketConsumer): def connect(self): Client.objects.create(user=self.scope['user'],channel_name=self.channel_name) self.accept() def disconnect(self, close_code): # Leave room group #self.channel_layer.group_discard(self.room_group_name, self.channel_name) Client.objects.filter(channel_name=self.channel_name).delete() # Receive message from WebSocket def receive(self, text_data): destination_clients=Client.objects.filter(user_id__in=userstatuse_userids) print(destination_clients) /****self.send(text_data=json.dumps({"type": "chat.message","command":command,"request":request,"response":clubs_data})) This line works as message is sent to the owner of that channel, the person who sent the message *****// for each_user in destination_clients: /*this line however does not send the message to anyone*/ self.channel_layer.send(each_user.channel_name, {"type": "chat.message","text":"test"}) def chat_message(self, event): # Send message to WebSocket print("Chat message") self.send(text_data=json.dumps(event)) I have checked the channel names by printing them out and they match so I am not sending to wrong channels. chat message function is never called. does the whole consumer have to be async ? I do not want to implement this using groups. Their website has an example but I could not get it to work. https://channels.readthedocs.io/en/stable/topics/channel_layers.html -
Cannot Upload File to One Drive via Python
I have tried to upload file to one drive by using python code: Please my upload script below for reference: url = f'https://graph.microsoft.com/v1.0/users/{user_id}/drive/root:/{local_file_path}:/createUploadSession' headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json' } session_data = { "item": { "@microsoft.graph.conflictBehavior": "replace", # Action on conflict (replace, fail, etc.) "name": "2.txt" # The file name in OneDrive } } upload_session = requests.post(url=url, headers=headers,json=session_data).json() Error Message: {"error": {"code": "Request_BadRequest", "message": "Specified HTTP method is not allowed for the request target.", "innerError": {"date": "2024-11-07T04:21:05", "request-id": "7be5355c-381a-4ea8-9d89-0b0a99208bb4", "client-request-id": "7be5355c-381a-4ea8-9d89-0b0a99208bb4"}}} -
How to create a Foreign Key for a table for a table that is not part of SQLAlchemy ORM?
I'm trying to have a FK to a table that is managed by Django ORM however SQLA Doesn't seem to like it. class SomeSAModel(DeclarativeBase): user_id: Mapped[int] = mapped_column( sa.ForeignKey("users_customuser.id") # this is a reference to a Django table ) And this is the error I get when I run alembic revision --autogenerate File "/home/dev/Desktop/t5hob/Backend/alembic/env.py", line 137, in run_migrations_online context.run_migrations() File "<string>", line 8, in run_migrations File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/runtime/environment.py", line 946, in run_migrations self.get_context().run_migrations(**kw) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/runtime/migration.py", line 616, in run_migrations for step in self._migrations_fn(heads, self): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/command.py", line 212, in retrieve_migrations revision_context.run_autogenerate(rev, context) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/api.py", line 570, in run_autogenerate self._run_environment(rev, migration_context, True) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/api.py", line 617, in _run_environment compare._populate_migration_script( File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/compare.py", line 65, in _populate_migration_script _produce_net_changes(autogen_context, upgrade_ops) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/compare.py", line 98, in _produce_net_changes comparators.dispatch("schema", autogen_context.dialect.name)( File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/util/langhelpers.py", line 310, in go fn(*arg, **kw) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/compare.py", line 134, in _autogen_for_tables [(table.schema, table.name) for table in autogen_context.sorted_tables] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py", line 1141, in __get__ obj.__dict__[self.__name__] = result = self.fget(obj) ^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/api.py", line 482, in sorted_tables result.extend(m.sorted_tables) ^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py", line 5626, in sorted_tables return ddl.sort_tables( ^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py", line 1252, in sort_tables for (t, fkcs) in sort_tables_and_constraints( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py", line 1328, in sort_tables_and_constraints dependent_on = fkc.referred_table ^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py", line 4753, … -
How to make a Django `url` case insensitive?
For example, if I visit http://localhost:8000/detail/PayPal I get a Page not found error 404 with the following message: Using the URLconf ... Django tried these URL patterns, in this order: ... detail/<slug:slug> [name='processor_detail'] The current path, detail/PayPal, matched the last one. Here is my code: views.py: class ProcessorDetailView(DetailView): model = Processor template_name = 'finder/processor_detail.html' slug_field = 'slug' # Tell DetailView to use the `slug` model field as the DetailView slug slug_url_kwarg = 'slug' # Match the URL parameter name models.py: class Processor(models.Model): #the newly created database model and below are the fields name = models.CharField(max_length=250, blank=True, null=True) #textField used for larger strings, CharField, smaller slug = models.SlugField(max_length=250, blank=True) ... def __str__(self): #displays some of the template information instead of 'Processot object' if self.name: return self.name[0:20] else: return '--no processor name listed--' def get_absolute_url(self): # new return reverse("processor_detail", args=[str(self.slug)]) def save(self, *args, **kwargs): #`save` model a certain way(detailed in rest of function below) if not self.slug: #if there is no value in `slug` field then... self.slug = slugify(self.name) #...save a slugified `name` field value as the value in `slug` field super().save(*args, **kwargs) urls.py: path("detail/<slug:slug>", views.ProcessorDetailView.as_view(), name='processor_detail') I want that if I follow a link it either 1. doesn't matter what case … -
When I add project in python manager for my django website displaying me : Project startup failed, please check the project Logs
When I add project in python manager for my django website displaying me : Project startup failed, please check the project Logs and the status is suspended as you can see in the image below.enter image description here I followed these steps : The "logs" that are mentioned do not seem to be working but I do see these errors while executing: The dependencies needed to install the project, please wait... ERROR: Could not find a version that satisfies the requirement uvicom (from versions: none) ERROR: No matching distribution found for uvicom 2024-11-06 15:16:38 Start installing dependencies Looking in indexes: pypi.org ERROR: Could not find a version that satisfies the requirement asgiref=3.8.1 (from versions: none) ERROR: No matching distribution found for asgiret-381 and (myenv) root@vps-X:/www/wwwroot/myproject# gunicorn myproject.wsgi:application [2024-11-06 14:07:13 +0100] [203739] [INFO] Starting gunicorn 23.0.0 [2024-11-06 14:07:13 +0100] [203739] [ERROR] Connection in use: ('0.0.0.0', 8000) [2024-11-06 14:07:13 +0100] [203739] [ERROR] connection to ('0.0.0.0', 8000) failed: [Errno 98] Here are the steps I followed: Step 1: Connect to Your Server Use SSH to connect to your server securely. Replace <your-server-ip> with the IP of your server. ssh root@<your-server-ip> Step 2: Set Up Your Project Directory and Python Environment Create the Project … -
Django `The current path, detail/PayPal, matched the last one` error
I'm using Django's DetailView to display detailed information in my web app. I've set up a Processor model with a name and a slug field, and I'm using the slug field in the URL pattern and the DetailView. However, I'm running into an issue where the DetailView is not able to find the Processor object if the capitalization of the URL slug doesn't exactly match the slug field in the database. For example if I visit localhost:8000/detail/paypal I get the following error: Using the URLconf ... Django tried these URL patterns, in this order: ... detail/<slug:slug> [name='processor_detail'] The current path, detail/PayPal, matched the last one. In addition the url I entered in the url field changes to localhost:8000/detail/PayPal, capitalizing the letters. Finally, the url only works if I first visit it by clicking on a link to it from another page. After that it works perfectly normally whether I go incognito mode or not and no matter the capitalization I use in the slug. But if I go incognito mode and visit the url directly(ie, after not having visit it by clicking on a link to it from another page) it doesn't load at all whether I capitalize the slug … -
How to inject css from vue into a django template?
I have django as backend, vue as frontend - using boilerplate from https://github.com/ilikerobots/cookiecutter-vue-django I want to integrate quasar for my frontend. This is my setup in main.js: import './assets/main.css' import { createApp } from 'vue' import { createPinia } from 'pinia' import { Quasar } from 'quasar' import App from './App.vue' import 'quasar/dist/quasar.css' import '@quasar/extras/material-icons/material-icons.css' import '@quasar/extras/material-icons-outlined/material-icons-outlined.css' import '@quasar/extras/material-icons-round/material-icons-round.css' import '@quasar/extras/material-icons-sharp/material-icons-sharp.css' import '@quasar/extras/material-symbols-outlined/material-symbols-outlined.css' import '@quasar/extras/bootstrap-icons/bootstrap-icons.css' const app = createApp(App) app.use(createPinia()).use(Quasar, { plugins: {} // Add Quasar plugins here if needed }) app.mount('#app') I am injecting this in my django template header.html: {% extends "base.html" %} {% load vue_utils %} {% block content %} <div id="#app"></div> {% endblock %} {% block inline_javascript %} <script type="module" crossorigin src="{% vue_bundle_url 'main' %}"></script> {% endblock inline_javascript %} This is my vue component - App.vue: <template> <q-layout view="hHh lpR fFf"> <q-header elevated class="bg-primary text-white" height-hint="98"> <q-toolbar> <q-btn dense flat round icon="menu" @click="toggleLeftDrawer" /> <q-toolbar-title> <q-avatar> <img src="https://cdn.quasar.dev/logo-v2/svg/logo-mono-white.svg"> </q-avatar> Title </q-toolbar-title> </q-toolbar> <q-tabs align="left"> <q-route-tab to="/page1" label="Page One" /> <q-route-tab to="/page2" label="Page Two" /> <q-route-tab to="/page3" label="Page Three" /> </q-tabs> </q-header> <q-drawer show-if-above v-model="leftDrawerOpen" side="left" behavior="desktop" elevated> <!-- drawer content --> </q-drawer> <q-page-container> <router-view /> </q-page-container> </q-layout> </template> <script> import { ref } from 'vue' console.log("HERE") … -
Django Search Query to Match Names With and Without Accents in PostgreSQL
I'm using Django with a PostgreSQL database. In my database, I have a Users table with a name column that stores names with special characters, such as accents and the letter "Ñ". When performing a search, I want the results to include entries with and without accents. For example, if I have users with the names "lúlú" and "lulu", I would like both to appear in the search results, regardless of whether the search term includes accents. Here's my current code for the search functionality: def autocomplete(request): result = [] try: if request.user.is_staff and request.user.is_active: columns = request.GET.get("column_name").split(",") value = request.GET.get("column_value") columns = [ ("{}__icontains".format(column), request.GET.get("term")) for column in columns ] filters = request.GET.get("filters", []) if filters: filters = filters.split(",") filters = [tuple(x.split("=")) for x in filters] queryset = Filter( app_label=request.GET.get("app_label"), model_name=request.GET.get("model"), ).filter_by_list(columns, operator.or_, filters) for q in queryset: result.append( {"obj": q.to_json(), "label": str(q), "value": q.to_json()[value]} ) except AttributeError: pass return HttpResponse(json.dumps(result, cls=Codec), content_type="application/json") How can I modify my search to ignore accents and special characters so that a search for "lulu" also matches "lúlú" and vice versa? Are there any recommendations for handling accent-insensitive searches in Django with PostgreSQL?