Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What could be the possible reasons for encountering the error?
What could be the possible reasons for encountering the error 'OperationalError: no such table: auth_user' when running a Django application, and how can it be resolved? I am try to solves that error but I cant find solution on Internet related to this error please if you optimized and best solution kindly give me proper answer? 'OperationalError: no such table: auth_user' when running a Django application, and how can it be resolved? -
How to solve 'django.db.migrations.exceptions.InconsistentMigrationHistory' error?? (using powershell/VSCode)
I am making a web app (I am a student and this is my first attempt of building a project) using stack: Django, Vue and MySQL. Attaching link to git repo here: https://github.com/yeshapan/LearningDashboard (please refer ReadME for details) I completed initial setup and then created an app called dashboard where I defined models for the features. Edit: Here's the error message as text: Traceback (most recent call last): File "C:\Users\DELL\Desktop\LearningDashboard\manage.py", line 22, in <module> main() File "C:\Users\DELL\Desktop\LearningDashboard\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 121, in handle executor.loader.check_consistent_history(connection) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\db\migrations\loader.py", line 327, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency dashboard.0001_initial on database 'default'. However, it is raising error: Error message I tried asking ChatGPT for help. It said to delete everything in dashboard/migrations and delete db.sqlite3 file in root folder (Edit: I also deleted the table from MySQL and applied migrations again but it is still giving error) and apply … -
The dropdown menu is not expanding. CSS and JS are connected correctly
I am a beginner in web development. I need some help. The dropdown menu is not expanding. CSS and JS are connected correctly. What could be the reason? I checked the CSS/JS classes and connected files. Everything seems to be correct, I even used GPT, but no results. :( I can provide other project files if needed. Here is the code from the main file layout.html. {% load static %} <!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}Головна{% endblock %}</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.10.1/main.min.css"> </head> <body> <button class="btn btn-primary" id="sidebarToggle"> <i class="fas fa-bars"></i> </button> <div class="d-flex"> <aside class="flex-shrink-0 p-3 bg-dark text-white sidebar" id="sidebar"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <img src="{% static 'main/img/2.png' %}" alt="Logo" class="small-logo"> </a> <hr> <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="{% url 'layout' %}" class="nav-link text-white {% if request.resolver_match.url_name == 'layout' %}active{% endif %}" aria-current="page"> <i class="fas fa-heart"></i> Головна </a> </li> <li> <a href="{% url 'staff' %}" class="nav-link text-white {% if request.resolver_match.url_name == 'staff' %}active{% endif %}"> <i class="fas fa-users"></i> Особовий склад </a> </li> <li> <a href="{% url 'calendar' %}" … -
"C# PBKDF2 password hashing with Django-compatible format (pbkdf2_sha256), issues with password verification"
I am working on a C# application where I need to verify user passwords that were hashed using Django’s PBKDF2 algorithm (pbkdf2_sha256). The passwords are stored in the format: pbkdf2_sha256$iterations$salt$hash For example: pbkdf2_sha256$870000$wyEbTcPvbTOet9npIyftqZ$Xv274JNGq1ZMQQHzmZx8q5n+Nly/U5Wf1WYLRO4d8YY= I'm trying to replicate the same process in C# using Rfc2898DeriveBytes to verify the password. However, I am encountering an issue where the computed hash does not match the stored hash, even though the entered password is correct. Here's the C# code I’m using to verify the password: public static bool VerifyPassword(string enteredPassword, string storedPasswordHash) { var parts = storedPasswordHash.Split('$'); if (parts.Length != 4 || parts[0] != "pbkdf2_sha256") { Console.WriteLine("Invalid password format."); return false; } string iterationsStr = parts[1]; string salt = parts[2]; string storedHash = parts[3]; if (!int.TryParse(iterationsStr, out int iterations)) { Console.WriteLine("Invalid iterations count."); return false; } byte[] saltBytes = DecodeBase64Salt(salt); if (saltBytes == null) { return false; } byte[] passwordBytes = Encoding.UTF8.GetBytes(enteredPassword); byte[] computedHashBytes; using (var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, saltBytes, iterations, HashAlgorithmName.SHA256)) { computedHashBytes = pbkdf2.GetBytes(32); } string computedHash = Convert.ToBase64String(computedHashBytes); Console.WriteLine($"Computed Hash: {computedHash}"); return storedHash == computedHash; } private static byte[] DecodeBase64Salt(string salt) { switch (salt.Length % 4) { case 2: salt += "=="; break; case 3: salt += "="; break; } … -
my is the block content on django is displaying below the footer
this is the base.html the block content is between the header and the footer <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>header</h1> {% block content %} {% endblock content %} <h1>footer</h1> </body> </html> this is index that include the base html {% include "base.html" %} {% load static %} {% block content %} <p> body </p> {% endblock content %} the p tag boby should display in a middel expected output header body footer the outout header footer fghj the p tag should be in the middel right or is there something i missed? -
Join Our Exciting New Startup: Transform Business with Cutting-Edge IT Solutions
Are you a passionate developer looking to make an impact? We are a dynamic business consultation and implementation startup helping companies optimize their operations with customized software solutions, automation, and CRM tools. We’re looking for talented individuals to join our team on a profit-sharing basis, where your success is directly tied to the growth of the company. If you're looking for an opportunity to grow with a rapidly expanding startup and be part of innovative projects, this is the role for you! Positions Available: Frontend Developers Backend Developers Full Stack Developers Django Developers Custom Software Developers RPA Specialists CRM Specialists (Zoho, Salesforce, HubSpot) What We're Looking For: Frontend Developers: Expertise in HTML, CSS, JavaScript, and popular frameworks like React, Angular, or Vue.js. Backend Developers: Proficiency in Node.js, Python, Ruby, Java, or similar technologies. Full Stack Developers: A combination of both frontend and backend expertise with the ability to work on entire application stacks. Django Developers: Solid experience with Django for backend development, REST APIs, and integration with frontend frameworks. Custom Software Developers: Experience in creating bespoke solutions tailored to clients' needs, focusing on scalability and security. RPA Specialists: Expertise in automating business processes using tools like UiPath, Blue Prism, or … -
Django Function Update
I'm doing the update function but I get a message Page not found enter image description here views.py def detalle_tarea(request, tarea_id): if request.method == 'GET': tarea = get_object_or_404(Tarea, pk=tarea_id) form = TareaForm(instance=tarea) return render(request, 'tarea_detalles.html', {'tarea': tarea, 'form': form}) else: tarea = get_object_or_404(Tarea, pk=tarea_id) form = TareaForm(request.POST, instance=tarea) form.save() return redirect('tareas') url.py from django.contrib import admin from django.urls import path from tareas import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.inicio, name='inicio'), path('registrar/', views.registrar, name='registrar'), path('tareas/', views.tareas, name='tareas'), path('tareas/crear/', views.crear_tarea, name='crear_tarea'), path('tareas/<int:tarea_id>/', views.detalle_tarea, name='detalle_tarea') ] Any suggestion ??? -
How to get my favicon at `example.com/favicon.ico` in my Django project?
Google currently does not show my website's favicon in its search results and I learned that it is becuase it should be located at example.com/favicon.ico. I'm looking for a simple way to do this, hopefully without relying on redirects. I've used redirection to the version in my static folder but when I visit the url it redirects to example.com/static/favicon.ico, which I do not want. I want that if a user or a crawler visits example.com/favicon.ico they see my favicon. It is currently located at: my_project/ ├── my_project/ │ ├── ... │ ├── settings.py │ ├── ... ├── manage.py └── static/ └── img/ └── favicon.ico I use gunicorn as my web server and whitenoise as my http server. Here is my urls.py: from django.urls import path, include # new from django.contrib.sitemaps.views import sitemap # new from finder.views import ProcessorDetailSitemap, ArticleDetailSitemap, StaticViewSitemap # Correct import path #from django.conf import settings #from django.conf.urls.static import static sitemaps = { 'processor':ProcessorDetailSitemap, 'article': ArticleDetailSitemap, 'static': StaticViewSitemap, } urlpatterns = [ path('admin/', admin.site.urls), path('', include('finder.urls')), #new path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap",), ] It is also linked in my template usingn<link rel="icon" type="image/x-icon" href="{% static 'img/favicon.ico' %}"> -
Django view to PNG
I'm writing django webapp, and part of it is to generate view and convert it to png image. (any ideas other then below are appreciated). I've looked at some tools to convert "html to png", but there is mainly problem with {%static files and templates. Another approach is to render page using django templates in browser, and take screenshot. It can be done using "chromedriver" + selenium. I was able to do it in my local ubuntu. But on production - all I've got is remote (ssh) access to some linux bash, where my application is hosted. I've created venv, pip-installed selenium and (chromedriver-py or chromedriver-binary). For the second one - it looks like it is closer to start working, but I've got error message: SessionNotCreatedException Message: session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir Stackoverflow says, that I should somehow put there a path to my chrome installation's user dir, but is there any chrome installation in that console bash of mine? Any ideas how to move forward ? or any other ideas how to do it? My code: import chromedriver_binary def render_to_png(request ): … -
How to make Django's Browsable API Renderer generate correct URLs with an /api/ prefix when behind Nginx?
I'm deploying a Django application using the Django Rest Framework (DRF) on a server behind Nginx. The application is accessible via https://my-site.com/api/ where /api is routed to the Django application. However, when I access the API's browsable UI at https://my-site.com/api/locations, everything works fine. But when I try to click the "Get JSON" button from the UI, it generates an incorrect URL: /locations?format=json instead of the correct /api/locations?format=json. Or when i try to POST it posts to /locations instead of /api/locations The issue is that the DRF Browsable API Renderer seems to be constructing the URLs as if the app is running directly under the root path (/), but in reality, it's running under /api/ on the server due to Nginx routing. # Proxy requests to the Django backend (API) location /api/ { proxy_pass http://127.0.0.1:8000/; proxy_set_header X-Script-Name /api; # Tell Django it's running under /api proxy_set_header Host $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; } What I'm Looking For: A solution to make the Django Browsable API Renderer correctly generate URLs with the /api/ prefix when behind Nginx. -
SessionStore object has no attribute 'get_session_cookie_age'
I have a Django project, everything goes well, but when I tried to handle the expiration of the session I got confused In a test view print(request.session.get_session_cookie_age()) give me this error SessionStore' object has no attribute get_session_cookie_age According to the documentation it should returns the value of the setting SESSION_COOKIE_AGE Trying debugging with this code : from django.contrib.sessions.models import Session sk = request.session.session_key s = Session.objects.get(pk=sk) pprint(s.get_decoded()) >>> {'_auth_user_backend': 'django.contrib.auth.backends.ModelBackend', '_auth_user_hash': '055c9b751ffcc6f3530337321e98f9e5e4b8a623', '_auth_user_id': '6', '_session_expiry': 3600} Here is the config : Version Django = 2.0 Python 3.6.9 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'drf_yasg', 'wkhtmltopdf', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] Thank's in advance -
Javascript fetch return 403 on Apache Server
Struggling with this issue for a few days now so any help is greatly appreciated. I managed to deploy my django project on a Linux server and it works fine apart from the model form submit. On the local development server it work fine and here is the workflow: User fills the form; User clicks submit; Javascript catches the submit event, submits a "POST" request and gets a response back; On the server side, the form is checked and if all is good an email is sent; HTML is updated to add the confirmation of form registration; Here is my code: home.html <div class="col-lg-8 offset-lg-2"> <form method="POST" class="row mt-17" id="form" onsubmit="return false"> {% csrf_token %} {% for field in form %} {% if field.name not in "message" %} <div class="col-12 col-sm-6"> <div class=form-group> <label for={{field.name}} class="form-label">{{ field.label }}</label> {{ field }} </div> </div> {% else %} <div class="col-12"> <div class=form-group> <label for={{field.name}} class="form-label">{{ field.label }}</label> {{ field }} </div> </div> {% endif %} {% endfor %} <div class="form-group mb-0"> <button type="submit" class="btn btn-primary btn-lg">Submit</button> </div> </form> </div> main.js const form = document.getElementById('form'); form.addEventListener("submit", submitHandler); function submitHandler(e) { e.preventDefault(); fetch("{% url 'messages-api' %}", { credentials: "include", method: 'POST', headers: { 'Content-Type': … -
can i save changes in the value before redis key expires
I could not find better solution. I have IDs and ranks in my Redis. Is it possible for me to save the changed ranks to the database before the Redis key expires?. can I trigger some function before it expires x time earlier -
CVAT OpenID Connect login doesn't show on Login page
I am trying to set up CVAT to support login using a custom IdP with OpenID Connect. I tried to make changes to base.py and docker-compose.override.yml to configure the server, but once I build and launch CVAT, nothing happens. I followed this guide, which was directly linked in the code. Here are the base.py changes: INSTALLED_APPS += ['cvat.socialaccount.providers.openid_connect',] ... SOCIALACCOUNT_PROVIDERS = { "openid_connect": { # Optional PKCE defaults to False, but may be required by your provider # Can be set globally, or per app (settings). 'OAUTH_PKCE_ENABLED': True, 'EMAIL_AUTHENTICATION' : True, "APPS": [ { "provider_id": "NAME", "name": "Service Name", "client_id": "client_id", "secret": "secret", "settings": { "server_url": "https://server/cvat/.well-known/openid-configuration", # Optional token endpoint authentication method. # May be one of "client_secret_basic", "client_secret_post" # If omitted, a method from the the server's # token auth methods list is used "token_auth_method": "client_secret_basic", "oauth_pkce_enabled": True, }, }, ] } } SOCIAL_AUTH_OPENIDCONNECT_KEY = 'client_id' SOCIAL_AUTH_OPENIDCONNECT_SECRET = 'secret' SOCIAL_AUTH_OPENIDCONNECT_API_URL = 'https://server/cvat/.well-known/openid-configuration' SOCIALACCOUNT_ONLY = True And this is the added docker-compose.override.yml file: services: cvat_server: environment: USE_ALLAUTH_SOCIAL_ACCOUNTS : true Since none of this worked, I tried creating a auth_config.yml as follows: --- social_account: enabled: true openid_connect: client_id: client_id client_secret: secret domain: https://server.it/ and told CVAT to use it by … -
Django Rest Framework login failure
I'm trying to make DRF work without custom serializers, views and urls, just using the default ones, but there is an issue with my login. Whenever i create a user on /api/v1/auth/register (this happens successfully) and then try to log in on /api/v1/auth/login, I get this error message: { "non_field_errors": [ "Unable to log in with provided credentials." ] } On the admin panel I login successfully with the same credentials, a proof they are correct. Even when I set up to use just the email as credentials, I am still required a password. Here is my settings.py: ... ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'rest_framework_simplejwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', ] MIDDLEWARE = [ ... "allauth.account.middleware.AccountMiddleware", ] ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } REST_AUTH = { "USE_JWT": True, "JWT_AUTH_COOKIE": "_auth", "JWT_AUTH_REFRESH_COOKIE": "_refresh", "JWT_AUTH_HTTPONLY": False, } SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_CONFIRM_EMAIL_ON_GET = True LOGIN_URL = "/api/v1/auth/login" I've tried many other approaches like custom user model, views and serializers, but it never worked, even became worse. I suppose there is something to … -
How to use uv run with Django in a PyCharm Docker environment?
I am developing a Django application using a Docker environment in PyCharm. Until now, I have been using pip for package management, but I am considering using uv to potentially reduce container build times. I managed to install uv in the Docker container, but I am unsure how to configure PyCharm to start Django development using uv run. It seems that the screen where I typically configure run/debug settings does not have an option for this. How can I set up uv run in PyCharm for my Django project? If possible, I would like to know the best practices or any alternative solutions for this setup. Thank you in advance for your help! -
How to integrate a Stripe Terminal Reader to POS application using Django?
I am developing a POS system using Django. I have a Stripe account, and through the system I am developing, I can process payments using credit or debit cards, with the money being deposited into my Stripe account. This is done by typing card information such as the card number, CVV, and expiration date. Now, I have decided to use a Stripe Terminal Reader to simplify the process. Instead of manually entering card details, customers can swipe, insert, or tap their card on the Terminal Reader for payment. The model I have ordered is the BBPOS WisePOS E. I powered it on, and it generated a code that I entered into my Stripe account. The terminal's online or offline status is displayed in my Stripe account. The idea is that when I select 'Debit or Credit Card' as the payment method, the amount to be paid should be sent to the terminal. However, this process is not working. The terminal still shows the screen displayed in the attached image." Let me know if you'd like further refinements! I don't know if I miss some steps that need to be done in order for this to work. Bellow are my functions: … -
Will django ORM always return tz aware timestamps in UTC
I have a simple model: class ExampleModel(models.Model): ts = models.DateTimeField() my settings.TIME_ZONE is set to Europe/Berlin When I add a row to examplemodel with tz aware ts field (13:00) I see in postgresql 12:00 in UTC - which is correct. When I read the same value using the same ExampleModel.objects.filter model object I obtain ts field 12:00 in UTC. Is it correct? I supposed it should be converted back to Berlin time, no? P.S. USE_TZ = True enabled. I do my tests in django console (./manage.py shell) -
Django with S3Boto3Storage - After upload, bucket didn't change
I'm using these configuration: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = '*****' AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = '****' AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = False AWS_S3_ENDPOINT_URL = 'https://****' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_MEDIA_LOCATION = 'media' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'{AWS_S3_ENDPOINT_URL}/{AWS_MEDIA_LOCATION}/ I change the photo on ADMIN, the URL is created, but when I see the bucket, nothing show to me. The URL didn't work for read, of course. I tried put access configuration on Digital Ocean Space Objects, but.. nothing work. -
Django ConnectionResetError: [Errno 54] Connection reset by peer
I'm trying to setup a project to send email from my local machine(MacOS) using django. But I see this error File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do_handshake self._sslobj.do_handshake() ConnectionResetError: [Errno 54] Connection reset by peer This is code snippet that I have in my local. class EmailVerificationView(APIView): def post(self, request): smtp_server = "smtp-relay.brevo.com" smtp_port = 587 s = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=10) email = request.data.get('email') s.ehlo() s.login("login@email.com", "****") s.sendmail("test", email, 'Subject: verified') return Response({'message': 'Email sent successfully'}, status=status.HTTP_200_OK) I have tried few things as well, but nothing seems working. -
Getting Server Error (500) when setting debug to false due to manifest not including css files
I have an app that I've built using Django and React + Vite. Everything runs fine with Debug set to True, but once I set it to false I get a Server Error with the console output of: ValueError: Missing staticfiles manifest entry for 'reactjs/inspector-B1mMLMX5.css' The file reactjs/inspector-B1mMLMX5.css exists and is getting generated properly when running npm run build and the generated manifest file has an entry for it in the css property of the file that imports it: "Inspector/InspectorApp.jsx": { "file": "reactjs/inspector-FdX6WZL2.js", "name": "inspector", "src": "Inspector/InspectorApp.jsx", "isEntry": true, "imports": [ "_Loading-CnrJ4Xi6.js" ], "css": [ "reactjs/inspector-B1mMLMX5.css" ] }, It appears that with my current settings, running python manage.py collectstatic --noinput generates a separate manifest file called staticfiles.json, however this does not seem to be the issue as with some previous settings (i.e. not using WhiteNoise), I was getting the same error but referencing the correct Vite manifest file. Here is my current settings.py: """ Django settings for ChiroComp project. Generated by 'django-admin startproject' using Django 5.1.1. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ from pathlib import Path import os, sys, dj_database_url from dotenv import load_dotenv # Build … -
How can i solve? django - ValueError: ModelForm has no model class specified
i don't understand, what is the wrong. could you please let me know? which one do i need adjust? ValueError at /blog/15/ ModelForm has no model class specified. error messege picture which one do i need adjust? i want to know solve it blog/forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Mata: model = Comment fields = ("content", ) # exclude = ("post", "author", "created_at", "modified_at", ) blog/models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.author}::{self.content}" def get_absolute_url(self): return f"{self.post.get_absolute_url()}#comment-{self.pk}" blog/urls.py from django.urls import path from . import views urlpatterns = [ # FBV 방식의 패턴 # path('', views.index), # path('<int:pk>/', views.single_post_page) # CBV 방식의 패턴 path("", views.PostList.as_view()), path("<int:pk>/", views.PostDetail.as_view()), path("category/<str:slug>/", views.category_page), path("tag/<str:slug>/", views.tag_page), path("<int:pk>/new_comment/", views.new_comment), path("create_post/", views.PostCreate.as_view()), path("update_post/<int:pk>/", views.PostUpdate.as_view()) ] blog/views.py def new_comment(request, pk): if request.user.is_authenticated: post = get_object_or_404(Post, pk=pk) if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect(comment.get_absolute_url()) else: return redirect(post.get_absolute_url()) else: raise PermissionDenied -
How to extend a User's profile to save data in Django
I'm new to Django and I'm attempting to build a website where a user can view a DB of books and related authors and add any book to their 'favourites'. I've been searching lots and I can't find a satisfactory way of doing this - or indeed of saving any user data other than customising fields when you create a user. My current idea is to extend the UserModel to add an extra field which links their favourite book to the user. Tips on UserModel found here I can now see the UserProfile with some favourites by logging in to the Admin account, but I cannot link the View class/function with my bookfavs.html for the User to see their favourited books. The bookfavs.html states the username but not favourites. readable_project app_name = bookshelf #Models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Book, related_name='favourites') class Author(models.Model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) dob = models.DateField() bio = models.CharField(max_length=300) def __str__(self): return self.first_name + " " + self.last_name def get_absolute_url(self): return reverse('authorlist') class Book(models.Model): id = models.AutoField(primary_key=True) users = models.ManyToManyField(User) title = models.CharField(max_length=50) num_page = models.IntegerField() date_pub = models.DateField() tags = models.CharField(max_length=200) blurb = models.CharField(max_length=300) def get_absolute_url(self): return reverse('')` #views.py #Add favourite button...? def favorite(request, … -
invalid_client when trying to authenticate with client_id and client_secret using django oauth toolkit and rest framework
I’m running a Django service that exposes endpoints via Django REST Framework. I want to secure these endpoints using Django OAuth Toolkit for authentication. When I create an application from the admin panel, I use the following settings: As shown in the screenshot, I disable client_secret hashing. With this configuration, everything works perfectly, and I can obtain an access token without any issues. * Preparing request to http://localhost:8000/o/token/ * Current time is 2024-12-19T10:47:03.573Z * Enable automatic URL encoding * Using default HTTP version * Enable timeout of 30000ms * Enable SSL validation * Found bundle for host localhost: 0x159f21ed0 [serially] * Can not multiplex, even if we wanted to! * Re-using existing connection! (#106) with host localhost * Connected to localhost (127.0.0.1) port 8000 (#106) > POST /o/token/ HTTP/1.1 > Host: localhost:8000 > User-Agent: insomnia/0.2.2 > Content-Type: application/x-www-form-urlencoded > Accept: application/x-www-form-urlencoded, application/json > Authorization: Basic MkVDdzAwWkN1cm1CRFc4TEFrSmpjSGt1bnh1OW9WZlRpY09DaGU5bDpKVTl6SURzd0Zob09JMzJhRjhUMVI2WnhYZDVVTU84TWwwbHdiZldNWFNxcHVuTGdsaXBLT2xLTFBNMTBublV1TGp3WGFWOVBPR2ZxYUpURzF5Smx2VGRMWHVPRzN0SVg4bE9tQ1N6U09lbTV4Z2ExaWZrNWRUdjVOYWdFV2djQQ== > Content-Length: 29 | grant_type=client_credentials * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Thu, 19 Dec 2024 10:47:03 GMT < Server: WSGIServer/0.2 CPython/3.12.8 < Content-Type: application/json < Cache-Control: no-store < Pragma: no-cache < djdt-store-id: b377d48fbdae4db989aabb760af12619 < Server-Timing: TimerPanel_utime;dur=28.13699999999919;desc="User CPU time", TimerPanel_stime;dur=2.7200000000000557;desc="System CPU time", TimerPanel_total;dur=30.856999999999246;desc="Total CPU time", TimerPanel_total_time;dur=56.63733399705961;desc="Elapsed time", SQLPanel_sql_time;dur=5.738208987168036;desc="SQL … -
Reverse ForeignKey orm django
hi i am new to django orm , can some body help me i have data tables something like that class userprofile(models.model): foreignkey User related_name='fU' class A(models.model) foreignkey userprofile related_name='fa' Class b(models.model): forign key A related_name="fb" class C (models.model): foreignkey B related_name="fC" so what i am trying to achieve is , with User id i want to get information from all tables from top to bottom hierarchy .