Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't use UUID with DJ-STRIPE: DJStripe: Account has no field named 'uuid'
I am attempting to setup djstripe bit am encountering the following error. settings.py: DJSTRIPE_SUBSCRIBER_MODEL = 'auth_app.CustomUser DJSTRIPE_FOREIGN_KEY_TO_FIELD = 'uuid' AUTH_USER_MODEL = 'auth_app.CustomUser' This is my models.py. Note that I am using abstractcuser in order to use email as the username. from django.db import models from django.contrib.auth.models import AbstractUser import uuid from cuser.models import AbstractCUser class CustomUser(AbstractCUser): uuid = models.UUIDField(default=uuid.uuid4, unique=True) email = models.EmailField(unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email This is the error that I am facing: raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: Account has no field named 'uuid' I have tried to delete the migrations folder and the database file but the issue persists. Please let me know if you require any further information. Thank you. -
Django relation on two database columns
I am using django to interface with an existing database that I have no control over. The database frequently uses multiple columns for making relations and has uniqueness over all of those columns. The django inspectdb model generator correctly identified these as unique_together = (('foo', 'bar'), ('foo', 'bar'),), resulting in the following model: class A(models.Model): foo = models.IntegerField(db_column='FOO', primary_key=True) bar = models.IntegerField(db_column='BAR') class Meta: managed = False db_table = 'A' unique_together = (('foo', 'bar'), ('foo', 'bar'),) Now there is another table whose entries relate to that table on both columns. When querying using SQL I would relate them like this: SELECT * FROM A LEFT JOIN B ON A.foo = B.foo AND A.bar = B.bar However inspectdb failed to correctly map the two columns being used in a relating table: class B(models.Model): foo = models.OneToOneField(A, models.DO_NOTHING, db_column='A', primary_key=True) bar = models.ForeignKey(A, models.DO_NOTHING, db_column='A') The above is what it generated, however in reality it is a many-to-one relationship to table A. This then causes an error at runtime because the column bar in table A is not unique. Can I somehow define this relationship in a django model? And how do I query this efficiently so that django generates a JOIN … -
m2m_changed instance when in reverse
I have the following signal: @receiver(m2m_changed, sender=User.cars.through): def car_added_to_user(sender, instance, action, *kwargs): if action in ("post_add",): cache.delete(f"user-{instance.pk}") I can trigger it as expected when doing: User.cars.add(car) but if I also want to delete the user from the cache in this case, what do I do? Car.user_set.add(user) as in this case the instance is a Car object and not a User object. -
why "django-admin --version" command doesn't give any output?
I had install django successfully and I change script path also but still I didn't receive any answer for (django-admin --version) command i type django-admin --version I need the installed version as the output.But I didn't receive anything. -
django-tenant-schema migration issue: IntegrityError: insert or update on table "auth_permission" violates foreign key constraint
requirements.txt: Django==4.2.16 django-tenant-schemas==1.12.0` django-allauth==65.0.2 Added a new django model, then ran migrations: ./manage.py migrate_schemas --schema=public ./manage.py migrate_schemas --schema=myschema The first command runs fine. The second command gives this error: django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "auth_permission_content_type_id_2f476e4b_fk_django_co" DETAIL: Key (content_type_id)=(115) is not present in table "django_content_type". Indeed, the auth_permission table does not (yet) contain any permissions related to the new model. But actually, value '115' is present in the public.django_content_type table, with the right app_label and model info. So unclear why this error is raised. Maybe the migration is not looking in the public schema? But other migrations have been running for ages, only the new table creation seems to cause a problem now. -
How to get ckeditor5 link settings to work with Django project
I installed django-ckeditor-5 and I am using it as the editor for a django-machina forum. The editor displays on the forum and basically works correctly. However, I want links to open in a new tab when clicked and I want "https://" to be automatically inserted if the user does not add it to their link when using the link button. I can not get the link attributes to work. Here are my machina settings: MACHINA_MARKUP_LANGUAGE = None MACHINA_MARKUP_WIDGET = 'django_ckeditor_5.widgets.CKEditor5Widget' Here are my ckeditor config settings: CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ], }, 'link': { 'addTargetBlank': True, # Open links in a new tab 'defaultProtocol': 'https', # Default protocol for links is https 'plugins': ['AutoLink'], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', ], 'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'code','subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable',], 'image': { 'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter', ] }, # 'table': { # 'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells', … -
i have a problem with the importation of wagtail.contrib.settings.models import ModelSettings
from django.db import models from wagtail.admin.panels import FieldPanel, MultiFieldPanel from wagtail.contrib.settings.models import ModelSettings,register_setting @register_setting class SocialMediaSettings(ModelSettings): """Social media settings for our custom website.""" facebook = models.URLField(blank=True, null=True, help_text="Facebook URL") twitter = models.URLField(blank=True, null=True, help_text="Twitter URL") youtube = models.URLField(blank=True, null=True, help_text="YouTube Channel URL") panels = [ MultiFieldPanel([ FieldPanel("facebook"), FieldPanel("twitter"), FieldPanel("youtube"), ], heading="Social Media Settings") ] i have already upgrade to the latest version of wagtail but still rise the ImportError: cannot import name 'ModelSettings' from 'wagtail.contrib.settings.models -
simplejwt & allauth - auth cookie not sent from browser to django backend
I have a Django backend that uses allauth and simplejwt (both provided by dj-rest-auth) for authentication. When I make API requests using an API client (Bruno), my auth cookies containing JWT tokens are passed, and the server responds. But, I can't achieve the same thing in JS from the browser. The authentication cookies are received, but not passed in subsequent requests: minimal front-end JS: (async () => { console.log("logging in...") const loginResponse = await fetch('http://127.0.0.1:8000/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'test', password: 'securepassword123' }) }) const loginData = await loginResponse.json(); // response contains `set-cookie` headers // vv prints JSON containing "access", "refresh", "username", etc. console.log(loginData) if (!loginResponse.ok) { console.log('login failed :(') return } console.log("getting user info...") const userResponse = await fetch('http://127.0.0.1:8000/api/user', { credentials: 'include' }); const userData = await userResponse.json(); // vv prints `{detail: 'Authentication credentials were not provided.'}` console.log(userData) if (!userResponse.ok) { console.log("user data fetch failed :(") } })(); I've already set up CORS, allow-credentials, etc. in Django: # dj-rest-auth settings --------------------------------- # src: https://medium.com/@michal.drozdze/django-rest-apis-with-jwt-authentication-using-dj-rest-auth-781a536dfb49 SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ) } # djangorestframework-simplejwt SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } # dj-rest-auth REST_AUTH = … -
django-allauth with steam
as describe in this [issue on github][https://github.com/pennersr/django-allauth/issues/3516], my login method which is working by the way, seems to throw an exception everytime it is used: Missing required parameter in response from https://steamcommunity.com/openid/login: ('http://specs.openid.net/auth/2.0', 'assoc_type') Traceback (most recent call last): File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/message.py", line 481, in getArg return self.args[args_key] ~~~~~~~~~^^^^^^^^^^ KeyError: ('http://specs.openid.net/auth/2.0', 'assoc_type') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/consumer/consumer.py", line 1286, in _requestAssociation assoc = self._extractAssociation(response, assoc_session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/consumer/consumer.py", line 1402, in _extractAssociation assoc_type = assoc_response.getArg(OPENID_NS, 'assoc_type', no_default) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/negstek/.cache/pypoetry/virtualenvs/django-all-auth-to-steam-83qxtO4Z-py3.11/lib/python3.11/site-packages/openid/message.py", line 484, in getArg raise KeyError((namespace, key)) KeyError: ('http://specs.openid.net/auth/2.0', 'assoc_type') assoc_type is misssing from steam respone. These are my app settings: INSTALLED_APPS = [ ... # social providers "allauth.socialaccount.providers.openid", "allauth.socialaccount.providers.steam", ... ] MIDDLEWARE = [ ... "allauth.account.middleware.AccountMiddleware", # social providers ... ] AUTHENTICATION_BACKENDS = ( "allauth.account.auth_backends.AuthenticationBackend", "django.contrib.auth.backends.ModelBackend", ) SOCIALACCOUNT_PROVIDERS = { "steam": { "APP": { "client_id": STEAM_SECRET_KEY, "secret": STEAM_SECRET_KEY, } }, } Did I miss something in my implementation ? Is there a way to avoid the raising of this exception ? -
dj-rest-auth access token not sent from react font-end to django back-end
I'm making an SPA with a React front-end and a Django back-end. For user authentication, I'm using dj_rest_auth, which wraps allauth to provide a REST API interface. dj-rest-auth provides a "login" endpoint that sends back access and refresh cookies. It also privides a "user" endpoint that returns the username, email, first name and last name. Both work as expected in my API client (Bruno), BUT, I can't get the "user" api to work in my front-end code. My browser doesn't send cookies to the server. Here are screenshots from Bruno. Notice how the cookies are saved, and fetching the user's info works: Here's my login request from my React app and the set-cookie headers (aka response cookies): // ... fetch(BACKEND_URL + "/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: username, password: password, }), }) .then(async (response) => { //... study_stream_auth_cookie=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzM3MjM3MTEyLCJpYXQiOjE3MzcyMzM1MTIsImp0aSI6IjNjZDc4ZjI3ZWYyNTQwMzI4MmVmNjAwODRiMjcxYzU0IiwidXNlcl9pZCI6NDB9.JK-SKSGMWuTBFm4JFk4-T8RqNEf2vwANrS4-h7P9UMY; expires=Sat, 18 Jan 2025 21:51:52 GMT; Max-Age=3600; Path=/; SameSite=Lax study_stream_refresh_cookie=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTc0NTAwOTUxMiwiaWF0IjoxNzM3MjMzNTEyLCJqdGkiOiJhMTljYjg1ZDI5Zjk0NTQyOWUzMjM2ODdmY2IxYzQ0YiIsInVzZXJfaWQiOjQwfQ.xvfB61xkq9NUzQSZeAJmXSYaFrYcSfrsJ9QX2u635LU; expires=Fri, 18 Apr 2025 20:51:52 GMT; Max-Age=7776000; Path=/; SameSite=Lax sessionid=qt2yxaiitghqavr74xvvl8icjlckq6by; expires=Sat, 01 Feb 2025 20:51:52 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure And here's my "user" GET request. Notice that the only cookie sent here is csrftoken which is unrelated. const response = await fetch(BACKEND_URL + "/api/auth/user/", … -
Django AWS S3 JSPDF not loading image cors
I would appreciate some help. On my development I am able to create a PDF with an image without any problems, when i try the same page on my production I keep getting and error on my console and it gives me a pdf without the image. Access to image at 'https://example.s3.amazonaws.com/static/logos/example.png' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Error loading image https://example.s3.amazonaws.com/static/logos/example.png AWS settings: Block all public access: Off bucket policy: { "Version": "2012-10-17", "Id": "Policy1735675563626", "Statement": [ { "Sid": "Stmt1735675561227", "Effect": "Allow", "Principal": "*", "Action": [ "s3:DeleteObject", "s3:GetObject", "s3:GetObjectAcl", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::cabiunascompras/*" } ] } I have this as my CORS policy on AWS bucket [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] And this is my javascript to build pdf: function printOC() { $('#print-oc').show() const { jsPDF } = window.jspdf; const input = document.getElementById('print-oc'); const pdf = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'a4', compress: true, }); pdf .html(input, { margin: [10, 0, 10, 0], autoPaging: 'text', html2canvas: { scale: 595.26 / srcwidth, //595.26 is the width of A4 page … -
Office 365 (exchange) modifies email headers
In my application's backend (Django) I send emails to contacts. I sometimes expect contacts to reply those emails (helpdesk application). Using classic SMTP/IMAP-POP email server (hosted on OVH) everything works fine. I use References and Message-ID headers when sending emails, and use In-Reply-To as well as References to identify inbound messages and find the source ticket (I keep message-id on ticket and related messages). But when I added O365 Exchange support, whereas it's still able to send and read emails, everytime it was creating a new ticket instead of a new message in an existing ticket. I spent time troubleshooting the issue and found out that my custom References and Message-ID were renamed by respectively x-references and x-message-id, and their value was replaced by Microsoft ones. So of course, when replying I wasn't able to find back the values I expected. And furthermore, those x-references and x-message-id were not coming back with the reply. Whereas I found a trick to make it work again, with some extra code (I use an alias in Reply-To e.g.: support+ticket-12345@mydomain.com which enables me to find the ticket back), it is ugly and people might be tempted to use another idea and make a mess, … -
static assets not found in Django web application
I am new to Django. This is my first attempt to set up a project in Django. I have run this application before and all my static files were displaying as expected. But after some time and restarting my machine, the static files are no longer displaying. Here is the project structure And this is the error messages I get My settings.py is as follows: """ Django settings for DebbyrichCollections project. Generated by 'django-admin startproject' using Django 5.1.3. 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 from django.conf.urls.static import static import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%0!($(z=yfs)tik4630krj64)m+h7o12@bujz)v+lh5j+3z%7=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] 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', ] ROOT_URLCONF = 'DebbyrichCollections.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': … -
DjangoCodeError in Download?
Traceback (most recent call last): File "/Users/yavuzhanis/opt/anaconda3/lib/python3.9/wsgiref/handlers.py", line 138, in run self.finish_response() File "/Users/yavuzhanis/Desktop/fettucini/restaurant_management/venv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 173, in finish_response super().finish_response() File "/Users/yavuzhanis/opt/anaconda3/lib/python3.9/wsgiref/handlers.py", line 183, in finish_response for data in self.result: File "/Users/yavuzhanis/opt/anaconda3/lib/python3.9/wsgiref/util.py", line 37, in next data = self.filelike.read(self.blksize) ValueError: read of closed file How can I solve the error I encountered when trying to download the end of day report I created? -
ImportError: cannot import name 'Tensor' from 'torch' (unknown location)
I’m trying to import Tensor from PyTorch, but I keep getting this error: ImportError: cannot import name 'Tensor' from 'torch' (unknown location) Here’s the code causing the issue: from torch import Tensor What I’ve Tried: Checked that PyTorch is installed (pip show torch), and I’m using version 2.5.1. Reinstalled PyTorch: pip uninstall torch pip install torch Tested the import in a Python shell, but the error persists. Environment: Python version: 3.10 PyTorch version: 2.5.1 OS: Windows 10 Virtual environment: Yes How can I fix this issue? -
Can not load static files after wapping content with django, datatable and htmx
I have a django problem where I use Datatable to display my tables I also use htmx for CRUD but the concern is that once rendered the table content, DataTable and other JS or css frameworks do not initialize after the Swap. How can I solve this problem? I collect static with django commande Python manage.py collectstatic -
SMTP Error (gmail sending) Using Django with Railway in Deployment
I am getting the following error in Railway Deploy logs when it is trying to send Gmail. Internal Server Error: /register/ Traceback (most recent call last): File "/opt/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/opt/venv/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/hostel_app/views.py", line 43, in post CustomUserSerializer().send_verification_email(user, token) File "/app/hostel_app/serializers.py", line 56, in send_verification_email send_mail(subject, message, email_from, recipient_list) File "/opt/venv/lib/python3.11/site-packages/django/core/mail/__init__.py", line 88, in send_mail return mail.send() ^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/mail/message.py", line 301, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 128, in send_messages new_conn_created = self.open() ^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/mail/backends/smtp.py", line 95, in open self.connection.login(self.username, self.password) File "/root/.nix-profile/lib/python3.11/smtplib.py", line 750, in login raise last_exception File "/root/.nix-profile/lib/python3.11/smtplib.py", line 739, in login (code, resp) = self.auth( ^^^^^^^^^^ File "/root/.nix-profile/lib/python3.11/smtplib.py", line 662, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. For more information, … -
How to delete cookie with Django in Docker?
I'm working on my Django website, and I can't delete the JWT auth cookie upon logout. Here's my code for the logout view: `@api_view(['GET']) def LogoutUser(request): response = Response("logging out", status=status.HTTP_200_OK) response.delete_cookie("jwt_token", path="/") return response` It's supposed to delete the jwt_token cookie, which is the JWT auth cookie with the JWT, but for some reason it only works in my development environment (runsever), but not when it's running inside a Docker container. I tried setting a cookie with the same name but changing the expiry to 0, but that doesn't work. -
Django "You may need to add 'Server IP' to ALLOWED_HOSTS"
Hello i recongnize this question has been asked before but i havnt found a clear answer. Some Information: Im using nginx to proxy. Gunicorn for WSGI. I do have a domain name linked to my ip. Everything works fine. All my request sent through the domain name not ip. What i have tried: i tried to block requests with the IP address from nginx because initally i thought some bots are making requests using the IP address directly. But the request still got to django since this error is being thrown by django. so its either nginx didnt block them or something is converting the domain name to the Server IP address internally not sure. Preferred Requirements: Im looking for a solution AND a reason. I understand many people suggest to just add the IP to the allowed hosts. which is obvious but is there a valid reason to do so as in what is causing this issue to begin with and why is the solution adding the ip address rather than remving whats making the server ip requests which seems like the correct approach. Obviously i dont know the cause so i dont know if thats possible at all. … -
how can I modularize this code to reuse the AJAX in different HTML files without needing to rewrite it each time?
I separated my JavaScript code from the .html file and placed it in a static folder, then imported it. However, after this change, my AJAX stopped working. How can I make my ajax.js reusable across different pages without rewriting it? This was the working code that handled the editing of classes, receiving, and processing files. I should mention that I’m working on a Django project, and this is the first JS file I’m including in the project. The idea of separating it is so that the same AJAX functionality can be used for the adicionar_aula URL. Here is the code: ` Editar Aula Editar Aula {% csrf_token %} {{ form.as_p }} Arquivos já adicionados: {% for arquivo in arquivos_existentes %} {% if arquivo.arquivo %} {{ arquivo.arquivo.name }} {% else %} Arquivo não disponível {% endif %} Excluir {% empty %} Nenhum arquivo adicionado ainda. {% endfor %} Adicionar Arquivo Salvar Alterações $(document).ready(function() { // Enviar novos arquivos via AJAX $('#input-arquivo').on('change', function() { var formData = new FormData(); $.each($(this)[0].files, function(i, file) { formData.append('arquivo', file); }); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ url: '{% url "editar_aula" pk=plano.id %}', // URL para a view de edição type: 'POST', data: formData, processData: false, contentType: false, … -
Remove the mandatory field label 'This field is required.' and fix the bug with 'clean_email'
I use the built-in Django, 'UserCreationForm' to create a registration form, but there are unnecessary instructions 'This field is required.' that these fields are required, I want to remove them, please help, or at least translate into Russian, so that the inscription is in Russian, if you can, also help fix clean_email in forms, so that it does not always throw out this inscription after 1 test entry of an existing email here is a screenshot of the result RegisterUserForm views.py: class RegisterUser(CreateView): form_class = RegisterUserForm template_name = 'users/register.html' extra_context = {'title': 'Регистрация'} get_success_url = reverse_lazy('users:login') forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"})) password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"})) password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"})) class Meta: model = get_user_model() fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'} labels = { 'username': 'Логин:', 'email': 'E-mail:', 'first_name': 'Имя:', 'last_name': 'Фамилия:', 'password1': 'Пароль:', 'password2': 'Повторить пароль:', } widgets = { 'username': forms.TextInput(attrs={'class': "form-input"}), 'first_name': forms.TextInput(attrs={'class': "form-input"}), 'last_name': forms.TextInput(attrs={'class': "form-input"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2']) def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError(("E-mail должен быть уникальным!"), code="invalid") return email users/register.html: {% extends 'users/base.html' %} {% block title %}Регистрация{% endblock %} {% block content %} … -
Question about creating a CRUD API for a project
how’s it going? This isn’t a coding question, but if anyone can help, it would be great. I’m new to this and I want to create an API that does a CRUD as a project. I’ve seen it’s recommended to do this, but of course, creating a public API allows anyone to modify the database. My question is: when recommending to create an API as a project, are they referring to a FakeAPI? I mean, should actions like DELETE or PUT only be temporary while the session is active? I’ve been trying to understand this so I can get started on the project. Thanks for your attention. -
Cant show 5 by 5 with paginator of Django
I'm using paginator of Django 5.1, the paginator work well but cant show dat 4 by 4 I want to show data 4 by 4 views.py def tipomaterial(request): tipomaterial = TipoMaterial.objects.all().order_by('nombre') #paginador de 4 en 4 paginator = Paginator(tipomaterial, 4) page_number = request.GET.get('page', 1) pgtm = paginator.get_page(page_number) return render(request, 'tipomaterial.html', { 'tipomaterial': tipomaterial, 'pgtm': pgtm }) tipomaterial.html <main class="container py-5"> <br/><br/> <hr> <span class="step-links"> {% if pgtm.has_previous %} <a href="?page={{ pgtm.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ pgtm.number }} of {{ pgtm.paginator.num_pages }}. </span> {% if pgtm.has_next %} <a href="?page={{ pgtm.next_page_number }}">Next</a> {% endif %} </span> image enter image description here Help please -
Error Deploying Python Backend to Railway.app: HDF5 Not Found During netCDF4 Installation
I'm normally deploying my Python Backend to Railway.app for easy hosting. Today I pushed som new features, but it did not finish because of an error. First look for me, it looks like there is something wrong with dockerfile. I hope there are somebody that knows how to fix it. #10 26.41 Downloading netCDF4-1.6.3.tar.gz (777 kB) #10 26.42 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 777.5/777.5 kB 480.2 MB/s eta 0:00:00 #10 26.46 Installing build dependencies: started #10 32.07 Installing build dependencies: finished with status 'done' #10 32.07 Getting requirements to build wheel: started #10 32.26 Getting requirements to build wheel: finished with status 'error' #10 32.27 error: subprocess-exited-with-error #10 32.27 #10 32.27 × Getting requirements to build wheel did not run successfully. #10 32.27 │ exit code: 1 #10 32.27 ╰─> [40 lines of output] #10 32.27 reading from setup.cfg... #10 32.27 Package hdf5 was not found in the pkg-config search path. #10 32.27 Perhaps you should add the directory containing `hdf5.pc' #10 32.27 to the PKG_CONFIG_PATH environment variable #10 32.27 No package 'hdf5' found #10 32.27 #10 32.27 HDF5_DIR environment variable not set, checking some standard locations .. #10 32.27 checking /root/include ... #10 32.27 hdf5 headers not found in /root/include #10 32.27 checking … -
Cpanel Django SMTP Problem: Mails Dont Show Up
Im sending mails in my Django project though my mail hosting with SSL settings. Eventhough I cant detect any problems with the SMTP code and mails are seem to sent in the cpanels tracking page, the mails dont show up in the inbox. I tried it for gmail and outlook it didnt work. Settings: EMAIL_HOST = '<server_name>' EMAIL_PORT = 465 EMAIL_HOST_USER = 'info@my_mail.com' EMAIL_HOST_PASSWORD = '********' View class SendMailTest(APIView): def post(self, request): recipient_email = 'recipient@mail.com' msg = MIMEMultipart() msg['From'] = settings.EMAIL_HOST_USER msg['To'] = recipient_email msg['Subject'] = 'SMTP Test Mail' html_content = "<h1>This is a test email</h1><p>Sent via Django.</p>" msg.attach(MIMEText(html_content, 'html')) context = ssl.create_default_context() with smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT, context=context) as server: server.set_debuglevel(1) server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) server.sendmail(settings.EMAIL_HOST_USER, recipient_email, msg.as_string()) return Response({'status': 'success'}) Debug Log Summary: reply: b'235 Authentication succeeded\r\n' reply: retcode (235); Msg: b'Authentication succeeded' send: 'mail FROM:<info@my_mail.com> size=412\r\n' reply: b'250 OK\r\n' reply: retcode (250); Msg: b'OK' send: 'rcpt TO:<'recipient@mail.com'>\r\n' reply: b'250 Accepted\r\n' reply: retcode (250); Msg: b'Accepted' send: 'data\r\n' reply: b'354 Enter message, ending with "." on a line by itself\r\n' reply: retcode (354); Msg: b'Enter message, ending with "." on a line by itself' data: (354, b'Enter message, ending with "." on a line by itself') send: b'Content-Type: multipart/mixed;.... reply: b'250 OK …