Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms returning "False":
This is my form.py file: from django import forms class PostForm(forms.Form): title_name = forms.CharField(max_length=255) description = forms.CharField(max_length=10000) This is my view.py file: def createPost(request): if request.method == "POST": form = PostForm(request.POST) print(form.is_valid()) if form.is_valid(): # To extarct data from web page title = form.cleaned_data['title'] description = form.cleaned_data['description'] print(title) # To store Data PostData.objects.create(title_name=title, description=description) The if Condition is returning False. What's the problem behind it!? -
Single CSS file not loading on production DJANGO server (Nginx + Gunicorn)
I have a production Django server running on Debian 11, Nginx + Gunicorn that out of nowhere will only partially load one of the main css files for the site and then will timeout. All other static files (css and js) load correctly. File is a minified theme file approximately 686kb. I have tried, accessing the file directly from the browser - as expected the css file only partially loads. changing the location where the static files are served, uploading new copies of the same file. The file is fully readable on my local development server and github repository. Gnuicorn and nginx logs are not being helpful. If anyone can point me in a direction to start investigating that would be great. Pulling my hair out try and find where the issue is even occuring. -
Unable to save group or permission through Django admin interface
I'm new to using Django and have been using AI tools to create a web application and it has been going really well, I created a user registration form to create user and assign them to groups from a dropdown, I was able to create users and it reflected in Django admin. But a while later I noticed that the groups selected weren't being reflected, so I tested trying to add groups through Django admin and that too was not working, I also found out during this time that permissions weren't also being saved. I was able to select permissions from the available list and port it to chosen permissions list but after selecting save and refreshing it was back to default with the chosen permission field being empty, same for groups. Initially I was able to do it but now it seems to not work, I tried by creating new groups and new users through the admin interface and still no luck. I tried going through the code as I read custom code can also interfere with it but the code is too big and I'm not sure what could have caused this issue... -
Table Values not displaying after form submission using Django
I have created a simple app to keep track of stock trades. I have a value for each trade "entry" called pnl, which calculates the profit or loss based on the position size, openeing price and closing price. This function is all done within the Entry model. I have verified that the code does execute properly and save the correct value to the "Pnl" field in the database. But for some reason you only see the new entry added to the table (entries.html) if you click the 'back' arrow on the browser. Even manually refreshing the page doesn't do anything. In fact, none of the entries show unless I clikc 'Back'. entries.html: {% extends 'base.html' %} {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% block title %} Trading Journal {% endblock title %}Trading Journal {% block content %} <form method="POST" enctype="multipart/form-data" action="/"> {% csrf_token %} {{ form }} <button>Submit</button> </form> {% endblock content %} {% block table %} <table class="blueTable sortable"> <thead> <tr> <th>Date</th> <th>Ticker</th> <th>Strategy</th> <th>Result</th> <th>Open Price</th> <th>Position</th> <th>Closed Price</th> <th>P&L</th> <th>Comments</th> </tr> </thead> <tfoot> … -
Wagtail Django migration doesn't get applied when running `migrate`
When I run Django makemigrations on Wagtail I get a migration (pasted at the bottom) which doesn’t seem to migrate properly. Here you see me making the migration successfully, applying it without errors and then, after doing runserver, being told that I have migrations to run. (.venv) development ➜ app 🐟 manpy makemigrations /root/.cache/pypoetry/virtualenvs/.venv/lib/python3.10/site-packages/wagtail/utils/widgets.py:10: RemovedInWagtail70Warning: The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead. warn( System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'freetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'pagetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'sectiontag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace Migrations for 'core': modules/core/migrations/0019_whofundsyoupage_stream.py - Add field stream to whofundsyoupage (.venv) development ➜ app 🐟 manpy migrate /root/.cache/pypoetry/virtualenvs/.venv/lib/python3.10/site-packages/wagtail/utils/widgets.py:10: RemovedInWagtail70Warning: The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead. warn( System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'freetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'pagetag_chooser' isn't unique. You may not be able to reverse … -
how do I intergrate Django with fastapi
I'm trying to integrate FastAPI with Django ORM to perform async CRUD operations in my application. I want to take advantage of FastAPI's async capabilities while using Django's ORM for database operations. I've followed the steps outlined in the FastAPI documentation and managed to create a FastAPI app. However, I'm having trouble integrating it with Django ORM for async CRUD operations. Could someone provide a step-by-step guide or point me in the right direction on how to integrate FastAPI with Django ORM for async CRUD operations? Any help would be greatly appreciated. Thank you! -
Weight issue when streaming MP4 in Django when rewinding
I encountered a problem when rewinding a video that was streaming from another service. When rewinding on this service, everything works well and mp4 files are rewinded quickly. another service In my case, when using StreamingHttpResponse, the video starts loading again from the very beginning to the point where I rewinded. my streaming service Here is my Python code: from django.http import StreamingHttpResponse import requests def stream_file(request): video_url = "https://stream.voidboost.cc/bc1442336011256eb53bad59edce97f4:2024051610:SDM0cmRNelBMMHhqQitwTnlHSVVuUUVUOVhjRVJwZjJrV3RYMjRRMzZDcXR2SUtwbVp4T3BJMFJFUFNCRVNFdy9tZEJJdllFUzU1NklwMFpld0NIdFhqZ3FZQTdMR2oxR1dJNVplY3dpZXc9/4/4/1/2/3/v022a.mp4" response = requests.get(video_url, stream=True) def file_generator(): for chunk in response.iter_content(chunk_size=8192): yield chunk headers = { 'Content-Length': response.headers.get('Content-Length'), 'Accept-Ranges': 'bytes' } return StreamingHttpResponse(file_generator(), content_type=response.headers.get('Content-Type'), headers=headers) I have no experience with this. -
what method is responsible for retrieving the content of a template to translate it into django?
what method is responsible for retrieving the content of a template to translate it into django ? Because I have a template stored in a field of my db and in this database's field I have some translatable strings. And I would like them to be detected by the Django makemessages command -
How to access fields of a table that is a foreign key to another in django rest api
I am writing dhango rest api. I have ModelA with fields fldA1, fldA2 and fldA3 I have ModelB with fields fldB1, fldB2 and foreign key to ModelA Now I have to write an api to read fldB1, fldB2 and ModelA.fldA3 How to do -
Django Model : can't instantiate custom field in signal
I have the following model: class SrdRevisionWording(ModelDiff): srd_revision = models.ForeignKey(SrdRevision, on_delete=models.CASCADE) word = models.CharField(max_length=50, null=False) designation = models.CharField(max_length=200, null=False) is_list = models.BooleanField(null=False, default=False) parent_element = models.IntegerField(null=True) # ID of the Wording element in the previous SRD Revision __original_instance = None with_signal = True def get_revision_history_message(self, created=False, deleted=False, updated_field=None, check_history=False): if created: return 'Word "{}" added'.format(self.word) if deleted: return 'Word "{}" deleted'.format(self.word) match updated_field: case 'word': return 'Word {} changed to {}'.format(self.__original_instance.word, self.word) case 'designation' | 'is_list': return 'Word {} modified'.format(self.word) The attribute __original_instance is a custom model field (not in database). This attribute is instantiated during the pre_save signal : @receiver(pre_save, sender=SrdRevisionDocument) @receiver(pre_save, sender=SrdRevisionWording) def model_pre_save_handler(sender, instance, **kwargs): print('pre_save') if instance.srd_revision.revision != 'A': try: previous_srd_revision_state = sender.objects.get(pk=instance.parent_element) except sender.DoesNotExist: instance.__original_instance = None else: instance.__original_instance = previous_srd_revision_state print(instance.__original_instance) The print(instance.__original_instance) show me well the object SrdRevisionWording object (21). I can also print the object in the post_save signal : @receiver(post_save, sender=SrdRevisionDocument) @receiver(post_save, sender=SrdRevisionWording) def handle_revision_history_element_changed(sender, instance, **kwargs): print('signal') print(instance.__original_instance) if instance.with_signal is not False: message = instance.get_revision_history_message(created=True, check_history=True) The issue occurs on the last line when calling instance.get_revision_history_message(). I got the following error in the models.py file: return 'Word {} changed to {}'.format(self.__original_instance.word, self.word) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute … -
Django messaging functionality not working
So I'm trying to add messaging functionality to my e-commerce website, where buyers can message sellers and sellers can message buyers once the buyer has purchased something from them (haven't written the code for that yet, just want basic messaging functionality out of the way). So this is what I've tried. Now there are three problems with this. One is that when I am in my user_message.html, if I type in a message and I hit send, I get the error: Page not found (404) No Business matches the given query. When clearly I have a url for that. Secondly when I send a message, through the message_seller view, a message instance is created, it works but the recipient does not receive the message in his/her user_messages_view page, so kind of defeats the purpose. Thirdly I have tried to make counters work, but both counters do not work. The unread_message_counter is supposed to show the number of unread messages from different businesses/users, while the individual_business_message_counter is supposed to show the number of unread messages from that specific business. When I click on a message to go to detail view of the conversation, that is when the messages are supposed to … -
How can I write update method in a serializer in django?
I am new to django and I have this serializer class PersonHolidaysSerializer(serializers.ModelSerializer): person_name = serializers.ReadOnlyField() holiday_type_name = serializers.ReadOnlyField() person_full_name = serializers.ReadOnlyField( source="person.person_full_name") class Meta: model = PersonHoliday # fields = ('on_holidays', 'holidays_start_date', # 'holidays_end_date', 'comments', 'person_name', 'person') fields = '__all__' def get_date_ranges(self, start_date: date, end_date: date) -> list[date]: dt = (end_date - start_date).days return [start_date + timedelta(days=day) for day in range(dt+1)] def day_exists(self, values: QuerySet, requested_dates: list[date]) -> bool: delta_days_array = [] for value in values: existed_delta_days = self.get_date_ranges( value['holidays_start_date'], value['holidays_end_date'] ) delta_days_array.append(existed_delta_days) return any(x in y for x in requested_dates for y in delta_days_array) def create(self, validated_data): person = validated_data.get('person') start_date = validated_data.get('holidays_start_date') end_date = validated_data.get('holidays_end_date') holiday_type = validated_data.get('holiday_type') instance_holiday = PersonHoliday.objects.filter( Q(holidays_start_date__month=start_date.month) & Q(holidays_start_date__year=start_date.year) | Q(holidays_end_date__month=end_date.month) & Q(holidays_end_date__year=end_date.year), person=person, ) if not instance_holiday.exists(): return super(PersonHolidaysSerializer, self).create(validated_data) requested_delta_days = self.get_date_ranges(start_date, end_date) if self.day_exists(instance_holiday.values(), requested_delta_days): raise serializers.ValidationError('Holiday coincides with other holidays') if start_date>end_date: raise serializers.ValidationError("End date should be after start date") if not holiday_type: raise serializers.ValidationError("You should put a holiday type") return super(PersonHolidaysSerializer, self).create(validated_data) I want to write an update method with the same fields and the same validators. I tried to write something but didn't work. How can I write this? I want to prevent the user to put … -
Automatically route logout/ URL to Login/ in Django
I'm following a tutorial to built a To Do list in Python and Django, I've finished implementing authentication and User based access using built in views, Upon clicking "logout" button i'm correctly redirected to login page. However if I type http://localhost:8000/logout directly in url it shows 405 error. My goal is to redirect user if someone directly types the url to login page. How do I do that? Below if my url.py file from django.urls import path, reverse_lazy #from . import views # For Functions, thus but now it's class so from .views import TaskList, TaskDetail, TaskCreate, TaskUpdate, TaskDelete, CustomLoginView, RegisterPage # CLASSES FROM VIEWS FILES from django.contrib.auth.views import LogoutView urlpatterns = [ path('login/',CustomLoginView.as_view(),name='login'), path('logout/',LogoutView.as_view(next_page=reverse_lazy('login')),name='logout'), path('register/', RegisterPage.as_view(),name="register"), path('', TaskList.as_view(), name='tasks'), # root URL - #base url thus empty string, view name path('task/<int:pk>', TaskDetail.as_view(), name='task'), # when clicked on list item - sub url <int:pk> - pk - primary key path('create-task/', TaskCreate.as_view(), name='task-create'), # url accessed to create the task path('update-task/<int:pk>', TaskUpdate.as_view(), name='task-update'), # url accessed to update the task path('delete-task/<int:pk>', TaskDelete.as_view(), name='task-delete'), # url accessed to delete the task ] Below is my relevent view.py functions from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic.list import ListView from … -
Auto-Boot Django and Gunicorn
I'm running a Django app using Gunicorn and Django. It was running, but when I rebooted the instance, Django and Gunicorn does not auto start. I made adjustments (like below), now both are not running eventhough I have restarted the services. gunicorn.service [Unit] Description=My Django Application with Gunicorn Requires=gunicorn.socket After=network.target [Service] User=<user> Group=<user> WorkingDirectory=/opt/apps/django/myproject/<prjctname> ExecStart=/usr/bin/gunicorn <prjctname>.wsgi Restart=always [Install] WantedBy=multi-user.target gunicorn.socket [Unit] Description= Gunicorn socket [Socket] ListenStream=/run/gunicorn.sock SocketUser=<scktuser> [Install] WantedBy=sockets.target nginx.conf http { server { listen 80; listen [::]:80; server_name _; root /usr/share/nginx/html; } After enabling and starting the services, I checked the status and here are the results gunicorn.service Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; preset: disabled) Active: failed (Result: exit-code) TriggeredBy: × gunicorn.socket gunicorn.service: Start request repeated too quickly. gunicorn.service: Failed with result 'exit-code'. Failed to start gunicorn.service - My Django Application with Gunicorn. gunicorn.socket gunicorn.socket: Failed with result 'service-start-limit-hit' -
Background image not rendering in custom 404 page
I'm trying to set up a custom 404 error page in my Django project. The page renders correctly, but the background image is not showing up. I've ensured that the file name is correct and that it's located in the static folder. However, the image still doesn't display. Here's my code: Code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .error-page { background-image: url('{% static "404image10.jpeg" %}'); /* Add other background styling properties as needed */ } </style> </head> <body> <div class="container-fluid error-page"> <div class="row justify-content-center"> <div class="col-md-6 text-center"> <h1 class="display-1 text-white">Error 404</h1> <p class="lead text-white">Page not found</p> </div> </div> </div> </body> </html> I attempted to change the background image file to another one and verified that the file name and location are correct. However, the background image still does not render. Since the issue persists even after changing the file, I suspect that there might be an issue with the code itself. Could someone please help me identify and fix the problem? -
how do i do integrate the django with fastapi
i got an Mechine Test from reputed company integrate django with fastapi for CRUD Operation hear is assigment , how do i implimet this Assignment Create a CRUD (Create, Read, Update, Delete) API using FastAPI for storing key-value pairs, and then integrate it with Django to persist the data in a MySQL or PostgreSQL database Endpoint Creating a key-value pair. Retrieving the value by key. Updating the value by key. Deleting a key-value pair. -
Customizing the makemessages command to add a new data entry from a field in my database
I would like to know how to modify the makmessages command in order to be able to add a new input data source. Currently the command searches in the file tree for a file to translate but what I want to translate is stored in a field of my database (I store my template in my database) Currently if I generate the file with the django-admin makemessages -l es command I cannot generate the translatable strings found in my template stored in the database, however if I write the string directly in the file of character to translate + its translation. well the translation will be done in my template stored in the database and so what I want is not to enter the strings to translate manually. whether it is done dynamically -
Submissions List Disappears from Sidebar After Clicking a Link in Django
I am working on a Django project where I need to display a list of submissions in a sidebar. The sidebar is included in a base template (main.html), and all other templates extend this base template. The sidebar correctly shows the list of submissions when I navigate to the home page. However, when I click on a specific submission in the sidebar, the application navigates to the correct page, but the sidebar then only shows the clicked submission and all other submissions disappear. Here is the relevant part of my setup: Models.py: from django.db import models from users.models import UserProfile # Create your models here. class ResearchWork(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name class Assignment(models.Model): student = models.ForeignKey(UserProfile, related_name='student_assignment', on_delete=models.CASCADE) teacher = models.ForeignKey(UserProfile, related_name='teacher_assignment', on_delete=models.CASCADE) is_accepted = models.BooleanField(default=False) # charfield created_at = models.DateTimeField(auto_now_add=True) text = models.TextField(blank=True) def __str__(self): return f"Assignment for {self.student.user.username} with {self.teacher.user.username}" class Submission(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) SEMESTER_CHOICES = ( ('1', 'Semester 1'), ('2', 'Semester 2'), ('3', 'Semester 3'), ('4', 'Semester 4'), ('5', 'Semester 5'), ('6', 'Semester 6'), ('7', 'Semester 7'), ('8', 'Semester 8'), ) semester = models.CharField(max_length=100, null=True, choices=SEMESTER_CHOICES) research_work = models.ForeignKey(ResearchWork, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): research_work_name = … -
How to detect client disconnects on StreamingHttpResponse (Server Side Events) using Django/Django-Ninja?
We want to add Server Side Events in our application, but currently the while True loop runs indefinitely and client disconnect is not causing the task to stop. Reproducible example: @api.get("/events") async def get_events(request: ASGIRequest) -> StreamingHttpResponse: async def generate_message() -> AsyncGenerator[str, None]: while True: await asyncio.sleep(1) yield 'data: {"test": "testvalue"}\n\n' print("Working...") return StreamingHttpResponse( generate_message(), content_type="text/event-stream", headers={ "X-Accel-Buffering": "no", "Cache-Control": "no-cache", "Connection": "keep-alive", }, ) Above example will print Working... until server is closed (even if client closes connection and is not receiving the data). Any way to detect client disconnect to stop the while True loop? Already tried to return simple HttpResponse, putting code in try..except, creating def close, async def close methods on StreamingHttpResponse. django-ninja==0.22.2 django==4.2.13 uvicorn[standard]==0.29.0 -
How do I generate a PDF using pyppeteer in Django? Got error signal only works in main thread of the main interpreter
#urls.py path('pdf/', views.generate_pdf), #views.py from pyppeteer import launch import os import asyncio async def main(): browser = await launch() page = await browser.newPage() await page.goto("https://python.org") await page.waitFor(1000) await page.pdf({"path": "python.pdf"}) await browser.close() async def generate_pdf(request): print("Starting...") await main() print("PDF has been taken") return HttpResponse("PDF has been generated") I got an error: signal only works in main thread of the main interpreter. It works nicely while running in a standalone Python file but not inside Django. I got a runtime error This event loop is already running. while using async def generate_training_pdf(request): asyncio.get_event_loop().run_until_complete(main()) -
How to use LangChain to generate AI-based quiz questions in a specific JSON format in a Django application? [closed]
I'm new to LangChain and I'm working on creating a Django quiz generator app that uses AI to generate quiz questions. I want the generated questions to be in a specific JSON format as shown below: [ { "id": 1, "question": "What common aspect do physics and chemistry share?", "choices": { "a": "Laws of motion", "b": "Laws governing matter and energy", "c": "Laws of thermodynamics", "d": "Laws of electromagnetism" }, "answer": "b", "explanation": "Physics and chemistry share fundamental laws governing matter and energy, making it the correct choice." }, { "id": 2, "question": "What common aspect do physics and chemistry share?", "choices": { "a": "Laws of motion", "b": "Laws governing matter and energy", "c": "Laws of thermodynamics", "d": "Laws of electromagnetism" }, "answer": "b", "explanation": "Physics and chemistry share fundamental laws governing matter and energy, making it the correct choice." } ] Requirements: Input Parameters: The input to the model will have three parameters along with the text that the questions need to be generated from and I want it to return a response based on that. Output Format: The output should strictly be in the JSON format without any additional conversational text (e.g., no "Here are the questions you … -
Domain resolution fails for python requests-package in multithreading scenario
I am having a microservice hosted as an Azure Web App that sends outbound HTTP-POST calls based on various events. The calls have the characteristics of "fire-and-forget". Thus, I start a thread for each performed HTTP-request as follows: t = threading.Thread(target=self.perform_call, args=(target_url, notification_dto), daemon=True) t.name = f'notification_sending_{notification_dto.id}' t.start() The request itself is executed via the requests-package as follows (without any explicit session-management etc.): response = requests.post(target_url, timeout=5, headers=headers_dict, data=data_str) Sporadically, I see the following error in my log-file: Traceback (most recent call last): File "/agents/python/urllib3/connection.py", line 203, in _new_conn sock = connection.create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/agents/python/urllib3/util/connection.py", line 60, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/python/3.11.8/lib/python3.11/socket.py", line 962, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ socket.gaierror: [Errno -2] Name or service not known The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/agents/python/urllib3/connectionpool.py", line 790, in urlopen response = self._make_request( ^^^^^^^^^^^^^^^^^^^ File "/agents/python/urllib3/connectionpool.py", line 491, in _make_request raise new_e File "/agents/python/urllib3/connectionpool.py", line 467, in _make_request self._validate_conn(conn) File "/agents/python/urllib3/connectionpool.py", line 1096, in _validate_conn conn.connect() File "/agents/python/urllib3/connection.py", line 611, in connect self.sock = sock = self._new_conn() ^^^^^^^^^^^^^^^^ File "/agents/python/urllib3/connection.py", line 210, in _new_conn raise NameResolutionError(self.host, self, … -
Docker build . hangs indefinitely without feedback on MacOS Big Sur
I'm new to Docker, and following along a course. I went step by step creating some basic files to start a Django project on Docker, which are the following: My DockFile is this one: FROM python:3.9-alpine3.13 LABEL maintainer="user" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -n venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Then, my .dockerignore file is this: # Git .git .gitignore # Docker .docker #Python app/__pycache__/ app/*/__pycache__/ app/*/*/__pycache__/ app/*/*/*/__pycache__/ .env/ .venv/ venv/ Finally, the requirements reads: Django>=3.2.4,<3.3 djangorestframework>=3.12.4,<3.13 After that I'm supposed to run docker build ., but when I do it hangs and does nothing. I had to shut it down a couple of times. Any idea of what I am doing wrong or at least have some feedback? -
Template File Not Found in Django
So I have been trying to serve a template file in Django. My main issue is that the index.html page is found , but the static files (js,css,png) files are not found . They are all under the same directory as index.html file. Here are my configurations : Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, }, ] urls.py (Main) path('rest-framework/', include('rest_framework.urls')), path('api/', include('accounts.urls')), path('admin/', admin.site.urls), url(r'^rest-auth/', views.obtain_auth_token), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls.py (App) urlpatterns = [ path('homepage/', views.index, name='index'), ] views.py def index(request): return render(request, 'index.html') And here is the exact error I get: [15/May/2024 08:31:40] "GET /api/homepage/ HTTP/1.1" 200 1837 Not Found: /api/homepage/flutter.js [15/May/2024 08:31:40] "GET /api/homepage/flutter.js HTTP/1.1" 404 2674 Not Found: /api/homepage/manifest.json [15/May/2024 08:31:40] "GET /api/homepage/manifest.json HTTP/1.1" 404 2683 My template files directory is like this: accounts\ -migrations\ -templates\ server\ media\ static\ manage.py requirements.txt How can I solve this problem? -
I can't authenticate login
I have problem with login authentication. I have successfully registered an account via the register function. class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data=request.data) try: if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] display_name = serializer.validated_data['display_name'] user = User(username=username, password=make_password(password), display_name=display_name) user.save() return Response({'success': 'User created successfully'}, status=status.HTTP_201_CREATED) else: return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) enter image description here enter image description here But I can't authenticate my login information class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] print(f"Attempting login with username: {username} and password: {password}") user = authenticate(request, username=username, password=password) if user is not None: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) else: print("Authentication failed: Invalid credentials") return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) enter image description here I just learned django so here is the serializer file and model file if it is necessary for you from rest_framework import serializers from .models import User class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() class RegisterSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() display_name = serializers.CharField() from django.db import models import uuid class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) display_name = models.CharField(max_length=191) username …