Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to overide the CSS of Django UserCreationForm and AuthenticationForm without losing in built functionality?
I'm using the AuthenticationForm class to log users in, and the UserCreationForm to allow users to create accounts. Everything worked when I was just rendering the default form (using {{ form.as_p }} in my HTML files. However, I wanted to make the forms look nicer so I've over ridden the forms as so: class LoginForm(AuthenticationForm): username = forms.CharField(required=True, widget=TextInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "username", "placeholder": "Username"})) password = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password", "placeholder": "Password"})) class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True, widget=EmailInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "email", "placeholder": "Email"})) password1 = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password1", "placeholder": "Password"})) password2 = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password2", "placeholder": "Confirm password"})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] widgets = { 'username': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "username", "placeholder": "Username"}), 'first_name': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "first_name", "placeholder": "First Name"}), 'last_name': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "last_name", "placeholder": "Last Name"}), } However, … -
Use one docker container's URL into another container settings file
I have a docker compose file in which I am running two services: one is for django and another one is for keycloak. However, I want to access the keycloak through URL inside django settings file which I am trying to do by getting the IPAdress of the keycloak (docker inspect keycloak | grep IPAdress) container, but this does not work. Also I tried with http://localhost:8080/ (8080 is keycloak port) which also didn't work as well. Any suggestions or idea will be appreciated. -
ctrl+c in VSCode
I am working on a Django project at the moment and usually to stop the local server from running I press ctrl+c. However, a few days ago this stopped working. I think an extension or a VSCode update has caused this. Does anyone know how I can reset this keyboard shortcut in VSCode? -
Can´t Produce to topic in Kafka using docker and python
So I'm facing an odd situation where I can connect to my kafka broker but can´t produce to the topic I created. I have three images running on same network: zookeeper,kafka and my app. I have a simple producer in my app that goes like this: import json from kafka import KafkaProducer from loguru import logger producer = KafkaProducer( bootstrap_servers=["kafka:9092"], api_version=(0, 10, 21), ) def on_send_error(excp): logger.error(f"I am an errback {excp}", exc_info=excp) # handle exception def on_send_success(record_metadata): print(record_metadata.topic) print(record_metadata.partition) print(record_metadata.offset) def produce_to_kafka(): print(producer.bootstrap_connected()) data = json.dumps({"message": f"Produzindo para o Kafka mensagem 1"}) producer.send("test_producer", value=data.encode()).add_callback( on_send_success ).add_errback(on_send_error) producer.flush() When I try to run this code segment inside my app it prints True in the bootstrap_connected function but then gives me the following error when calling send(): ERROR | apps.my_app.producer:on_send_error:12 I am an errback KafkaTimeoutError: Batch for TopicPartition(topic='test_producer', partition=0) containing 1 record(s) expired: 30 seconds have passed since batch creation plus linger time My compose setup is the following: services: myapp: image: <my_app:latest> build: context: .. dockerfile: docker/Dockerfile args: DEPLOYMENT_MODE: develop stop_signal: SIGINT environment: ports: - "8000:8000" zookeeper: image: wurstmeister/zookeeper:3.4.6 ports: - "2181:2181" kafka: image: wurstmeister/kafka ports: - "9092:9092" expose: - "9093" environment: KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_ZOOKEEPER_CONNECT: … -
ImportError: cannot import name 'contact_view' from 'SCcontact' (app) in Django
I am new to Django. I'm trying to create a web contact form in Django that confirms by email the receipt of the enquiry to the enquirer and notifies the site owner of the enquiry details. When I do this I am getting the following error message File "C:\Users\mikec\OneDrive\Documents\Conted\Web Applications with Python JavaScript and SQL\Sophie Canniffe Costume Design\myproject\myproject\urls.py", line 19, in from SCcontact import contact_view ImportError: cannot import name 'contact_view' from 'SCcontact' (C:\Users\mikec\OneDrive\Documents\Conted\Web Applications with Python JavaScript and SQL\Sophie Canniffe Costume Design\myproject\SCcontact_init_.py) I have a views.py form in my app (SCcontacts) as follows: from django.shortcuts import render from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.urls import reverse def contact_view(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') # Send email to the user user_subject = "Thank you for your enquiry" user_message = f"Dear {name},\n\nThank you for contacting us. I have received your message and will get back to you soon.\n\nBest regards,\nSophie" send_mail(user_subject, user_message, 'noreply@sophiecanniffecostumes.co.uk', [email]) # Send email to yourself admin_subject = "New Sophie Canniffe Costumes website enquiry" admin_message = f"You have received a new contact enquiry from:\n\nName: {name}\nEmail: {email}\nMessage: {message}" send_mail(admin_subject, admin_message, 'noreply@ophiecanniffecostumes.co.uk', ['sophie_canniffe@yahoo.co.uk']) return HttpResponseRedirect(reverse('contact')) return render(request, 'contact.html') and the urls.py … -
Django import ignores sys.path
A unit test module stored in /tmp is imported in my Django project. The unit test module begins like this: import tempfile import sys sys.path.insert(0, tempfile.gettempdir()) # /tmp is first in sys.path from name_like_app import foo # foo is the function to test # name_like_app.py is in /tmp # The import looks in the app instead of /tmp! The module containing foo is stored in /tmp, but happens to be named like one of the apps in my Django project. For some reason, Django looks in the app and ignores sys.path. Why does this happen? -
Django-Admin with models from external database not saving or filtering
I have a problem with a simple Django project i'm creating. What I aim with this project is administrating a database i already have with the tooling Django Admin offers. I proceed to explain what I already did and doesn't work as expected. This is my external model, generated with the inspectdb command: class Paises(models.Model): id_country = models.IntegerField(db_column='ID_COUNTRY', primary_key=True) country_name = models.TextField(db_column='COUNTRY_NAME', blank=True, null=True) country_phone_code = models.IntegerField(db_column='COUNTRY_PHONE_CODE', blank=True, null=True) class Meta: managed = False db_table = 'PAISES' verbose_name_plural = "Paises" def __str__(self): return self.country_name Then this is the admin class to register the model (as suggested at the documentation): class PaisesAdminModel(admin.ModelAdmin): using = "external" list_display = ['id_country', 'country_name', 'country_phone_code'] search_fields = ("country_name",) list_display_links = ('id_country', 'country_name') def save_model(self, request, obj, form, change): obj.save(using=self.using) def delete_model(self, request, obj): obj.delete(using=self.using) def get_queryset(self, request): return super().get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): return super().formfield_for_foreignkey( db_field, request, using=self.using, **kwargs ) def formfield_for_manytomany(self, db_field, request, **kwargs): return super().formfield_for_manytomany( db_field, request, using=self.using, **kwargs ) admin.site.register(Paises, PaisesAdminModel) I then ran python manage.py makemigrations and python manage.py migrate, everything seems to be OK, but then I find the following behavior: The model is listed correctly, all the columns and information are okay, i can even see the name of … -
Django RelatedObjectDoesNotExist User has no faculty. python (im getting this error i have also posted the screenshot of error) below code
`HI im new to python i got a project from github when i run it it says RelatedObjectDoesNotExist GitHub link = https://github.com/venugopalkadamba/Face_Verification_based_Attendance_system @login_required(login_url = 'login') def takeAttendence(request): if request.method == 'POST': details = { 'branch':request.POST['branch'], 'year': request.POST['year'], 'section':request.POST['section'], 'period':request.POST['period'], 'faculty':request.user.faculty } if Attendence.objects.filter(date = str(date.today()),branch = details['branch'], year = details['year'], section = details['section'],period = details['period']).count() != 0 : messages.error(request, "Attendence already recorded.") return redirect('home') else: students = Student.objects.filter(branch = details['branch'], year = details['year'], section = details['section']) names = Recognizer(details) for student in students: if str(student.registration_id) in names: attendence = Attendence(Faculty_Name = request.user.faculty, Student_ID = str(student.registration_id), period = details['period'], branch = details['branch'], year = details['year'], section = details['section'], status = 'Present') attendence.save() else: attendence = Attendence(Faculty_Name = request.user.faculty, Student_ID = str(student.registration_id), period = details['period'], branch = details['branch'], year = details['year'], section = details['section']) attendence.save() attendences = Attendence.objects.filter(date = str(date.today()),branch = details['branch'], year = details['year'], section = details['section'],period = details['period']) context = {"attendences":attendences, "ta":True} messages.success(request, "Attendence taking Success") return render(request, 'attendence_sys/attendence.html', context) context = {} return render(request, 'attendence_sys/home.html', context) def searchAttendence(request): attendences = Attendence.objects.all() myFilter = AttendenceFilter(request.GET, queryset=attendences) attendences = myFilter.qs context = {'myFilter':myFilter, 'attendences': attendences, 'ta':False} return render(request, 'attendence_sys/attendence.html', context) def facultyProfile(request): faculty = request.user.faculty form = FacultyForm(instance = faculty) context … -
Django Rest Framework - Custom serializer field does not appear in attrs dict when using "create" method
I created a ModelSerializer and want to add a custom field which does not belong to my model but is shown as part of serialized data when retrieving it and behave as writeable field when create method is called. I have a problem with validate method used on data passed in POST method. The field that does not belong to my model does not appear in attr dict when passed to validate method. The field I want is teams and when model instance already exists, I want this field to use method to retrieve result data (this works fine) and when the create method is called I want it to be a writeable field. Is this possible in any way? class MatchDaySerializer(serializers.ModelSerializer): #Validate if teams field exists in POST data to avoid creating Matchdays with no Players def validate(self, ): if not "teams" in attrs: raise serializers.ValidationError({"teams": "This field is required"}) return attrs #Serializer Fields matches = serializers.SerializerMethodField() teams = serializers.SerializerMethodField() class Meta: model = MatchDay fields = [ 'id', 'date', 'matches', 'teams', ] #Returns match counter def get_matches(self, obj): if not hasattr(obj, 'id'): return None if not isinstance(obj, MatchDay): return None return obj.match_counter #Return teams with list of players … -
How can I create in Django an custom absolute url for a predefined class
I need to make a blog in Django and I have a blog class declared as follows: models.py class Blog(models.Model): name = models.CharField(max_length=200, help_text='Enter name') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) The User class is a predefined Django class. As you can see for Blogger I don't create a class but I use a default one from Django class User. In the template blog-list.html I use the following line to display the blog author with a link to the author page: <a href="/blog/blogger/{{ blog.author.id }}">{{blog.author.first_name}} {{blog.author.last_name}}</a> wiews.py class BlogListView(generic.ListView): model = Blog ordering = ['-date'] paginate_by = 5 class BloggerDetailView(generic.DetailView): model = User urls.py urlpatterns = [ path('', views.index, name='index'), path('blog/<int:pk>', views.BlogDetailView.as_view(), name='blog-detail'), path('blogs/', views.BlogListView.as_view(), name='blogs'), path('blogger/<int:pk>', views.BloggerDetailView.as_view(), name='blogger-detail'), ] My question is how can I declare a get_absolute_url for blog.author to NOT use the manual constructed /blog/blogger/{{ blog.author.id }}? -
Django - "Not found" in log
I've got django app and some problem I can't understand/resolve. So, in my application, there is a view called: MyNotifyURL URLs.py file is ok. The view is called from outside, by payment integration api. When the payment is processed, the view is called, and it does its logic, and everything works fine. But, ... about 10 times per day (random hours), in my log files I can find: 2023-06-30 04:18:47 [WARNING ] (/home/myuser/myDevEnv/lib/python3.9/site-packages/django/utils/log.py:log.log_response 241) Not Found: /djangoapp/MyNotifyURL/ Is there any idea why is it so, or how to track the problem? -
PythonAnywere to connect postgres
**how to use postgres remotely in my pythonanywhere I need to make this kind of connection to postgres database in Anywhere but it is not supported ** ''' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'fontenariaguivala', 'USER': 'postgres', 'PASSWORD': '**********', 'HOST': 'mayhoste.com', 'PORT': '5432', } } ''' -
How'd I create filter feature that works with multiple model on Django?
So I have 2 models : from django.db import models class Profil(models.Model): nik = models.IntegerField() nama = models.CharField(max_length=40) tgl = models.DateField() kelamin = models.CharField(max_length=10) namaibu = models.CharField(max_length=40) nikibu = models.IntegerField() dusun = models.CharField(max_length=30, default='Sumberejo') def __str__(self): return f"{self.nik}, {self.nama}, {self.namaibu}" class Posyandu(models.Model): bulan = models.CharField(max_length=20, default='Januari') nik = models.ForeignKey(Profil, on_delete=models.CASCADE) tb = models.IntegerField() bb = models.IntegerField() ll = models.IntegerField() lk = models.IntegerField() ket = models.CharField(max_length=20,) def __str__(self): return f"{self.nik.nama}, {self.bulan}, {self.tb}, {self.bb}" and display them as a table with this html <table> <thead> <tr> <th>NIK</th> <th>Nama</th> <th>Tanggal Lahir</th> <th>Kelamin</th> <th>Nama Ibu</th> <th>Bulan</th> <th>TB</th> <th>BB</th> <th>LL</th> <th>LK</th> <th>Keterangan</th> </tr> </thead> <tbody> {% for profil in profils %} {% for posyandu in profil.posyandu_set.all %} <tr> <td>{{ profil.nik }}</td> <td>{{ profil.nama }}</td> <td>{{ profil.tgl }}</td> <td>{{ profil.kelamin }}</td> <td>{{ profil.namaibu }}</td> <td>{{ posyandu.bulan }}</td> <td>{{ posyandu.tb }}</td> <td>{{ posyandu.bb }}</td> <td>{{ posyandu.ll }}</td> <td>{{ posyandu.lk }}</td> <td>{{ posyandu.ket }}</td> </tr> {% endfor %} {% empty %} <tr> <td colspan="11">No data available</td> </tr> {% endfor %} </tbody> </table> aside from that I try to build a filter feature that able to filter what's displayed on the table based on months field (bulan field on Posyandu) with this views.py this views.py def riwayat(response): profils = … -
Count .docx pages Python Django
I have an application in DJango. I want to create a tool that will tell you the number of pages each file has. With PDF, excel and PPT files it works fine, but with ".docx" files it doesn't count exactly. I want you to tell me exactly how many pages that file has. I don't know, maybe by commands or by converting it to PDF but I want to have the exact number of pages. I have tried to do it by segments but it does not tell me exactly. This is my function: def count_pages(file_content, filename): file_extension = os.path.splitext(filename)[1] if filename else "" if file_extension.lower() == ".pdf": pdf_reader = PyPDF2.PdfReader(file_content) num_pages = len(pdf_reader.pages) file_type = "PDF" elif file_extension.lower() == ".docx": elif file_extension.lower() == ".pptx": prs = Presentation(file_content) num_pages = len(prs.slides) file_type = "PowerPoint" elif file_extension.lower() == ".xlsx" or file_extension.lower() == ".xlsm": wb = load_workbook(file_content) num_pages = len(wb.sheetnames) file_type = "Excel" else: num_pages = 0 file_type = "Unknown" return num_pages, file_type -
Python: ValueError: source code string cannot contain null bytes
I tried to start server and caught this: python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 936, in exec_module File "<frozen importlib._bootstrap_external>", line 1074, in get_code File "<frozen importlib._bootstrap_external>", line 1004, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Just started learn django and hard to my with error like this, because i can't understand anything from text like this ** … -
Seeking for Faster PDF/A Verification Tool in Django
I am currently working on a Django project that involves PDF file uploading and checking whether the uploaded file is PDF/A compliant. To accomplish this, I have been using an external module, VeraPDF. However, the verification process with VeraPDF takes around 3 seconds, which I find to be quite long. Therefore, I'm reaching out to the community for suggestions on any other free external modules or libraries that could potentially speed up this PDF/A verification process in a Django environment. Any advice would be greatly appreciated. Thank you in advance. Asynchronous Batch Processing for PDF/A Verification in Django -
how to create a modified table in python to download from django site
I have a django website with a database. On the site, you can add, change, delete information from the database. I made a button that, when clicked, downloads a .csv file. I open it in excel and it looks something like this: The data set does not matter, I have a different one, I took this one on the Internet for an example. I want that when I click on the "download report" button, I would create a table at least like in this example: Is it possible? At the moment, my views.py contains the following code to get data from the database and download it to an excel spreadsheet: def export_racks_view(request, id): response = HttpResponse(content_type='text/csv') response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=';', dialect='excel') writer.writerow([ 'Rack number', 'Name', 'Amount', 'Vendor', 'Model', 'Describe', 'numbering', 'responsible', 'financially responsible person', 'inventory number', 'row', 'place', 'height', 'width', 'depth', 'unit width', 'unit depth', 'rack type', 'place type', 'max load', 'power sockets', 'power sockets UPS', 'external ups', 'cooler', 'updated by', 'updated at', 'room name', 'building name', 'site name', 'department name', 'region name', ]) raw_report = Rack.objects.raw("""select rack.id as id, rack.rack_name, rack.rack_amount, rack.rack_vendor, rack.rack_model, rack.rack_description, rack.numbering_from_bottom_to_top, rack.responsible, rack.rack_financially_responsible_person, rack.rack_inventory_number, rack.row, rack.place, rack.rack_height, rack.rack_width, rack.rack_depth, rack.rack_unit_width, rack.rack_unit_depth, rack.rack_type, rack.rack_place_type, rack.max_load, … -
Django using same APIView for both logged in and non logged in users
How can we use the same Django rest APIView for both logged in and logged out (Public) users. If the authentication token is passed, the view should be able to give the request.user and if the authentication token is not passed, the request.user can be anonymous. Please let me know if this is possible or not? I tried to remove authentication_classes = [] permission_classes = [] from the view, but by default the authentication is applied for all the users. -
How can I get python to understand my commands such as python manage.py shell. Error code: python bash: command not found
What are the details of your problem? I am trying to run the command python manage.py shell. I am in the directory that has manage.py but python is acting like I don't have the file or the command ability for shell. I am using visual studio code and I ran the echo$PATH command and got this output: /Users/andrewstribling/Desktop/mike_mysite/project_env/bin:/Users/andrewstribling/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/andrewstribling/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin i had installed anaconda but went back to visual studio code. is this tied to it? Also, my director has my project env folder inside of my project folder. What did you try and what were you expecting? I have tried deleting the project_env folder for my enviornment and creating another one. I have reached out to the discord community for django and have not gotten a response. I looked up venv errors on stack overflow and I am not understanding the Path Variable really is or how to change it. I have read stack over flow articles but I do not believe their situation applies to me. https://python.land/virtual-environments/virtualenv#How_a_Python_venv_works I expect that there is a way to change how my project is seeing this. -
How to solve Django Rest API Import "drf_yasg" could not be resolved
from drf_yasg.views import get_schema_view from drf_yasg import openapi In the settings.py file, I add 'drf_yasg', Im Using the Vscode... Here I'm trying to add Swagger but I got an unexpected problem Import "drf_yasg.views" could not be resolved Screenshot Image -
Django ImportError at /user/login d doesn't look like a module path
I am trying to create a simple login page using th LoginView from django.contrib.auth. Whenever I try to login a user a receive the following error: ImportError at /user/login d doesn't look like a module path This is my code for activating the view in the url: from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path("register", views.register_request, name="register"), path("login", auth_views.LoginView.as_view(template_name="user/login.html"), name="login"), path("logout", auth_views.LogoutView.as_view(template_name="user/logout.html"), name="logout") ] This is my html file user.login.html: {% extends "base/base.html" %} {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small><br> <small class="text-muted"> <a href="/">Forgot password?</a> </small> </div> </div> {% endblock content %} #Just as a comment, the logout view works perfectly fine, the error jusr occurs when I hit submit in the login.html. I have tried adding these lines to the settings.py fileÑ AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend' ) LOGIN_URL = 'user/login' -
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Django-rest-auth
I'm doing the Django password reset but this error always happens and I don't know why Here are the urls: from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', views.login, name="login"), path('registrar/', views.registrar, name="registrar"), path('logout/', views.logout, name="logout"), path('reset/password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('reset/password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Here are my custom pages: my custom pages: And these are the project urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), path('', include('home.urls')), path('turmas/', include('turmas.urls')), path('calendario/', include('calendario.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
I it possible to integrate python with CSS, Javascript, and HTML?
I have a frontend web application built with JavaScript, HTML, and CSS. I would like to incorporate the output of a Python script into my frontend without using a server or a full backend solution. The Python script is a simple neural network, and I want to display its output in the frontend, such as showing the result as a header or plotting a graph generated by the script. I have already tried printing the output to the console from the Python script, but I need assistance with transferring that output to the frontend. Is it possible to achieve this without a server? I am open to suggestions and starting with a simpler solution, like plotting a graph generated by the Python script in the frontend. I appreciate any guidance or code examples on how to accomplish this. Thank you! I have looked into Django but I feel as if that seems too complex and more server focused for the simple task I require. -
Why does the matching query does not exist error occur?
There is a model: class ProductRating(models.Model): class Meta: indexes = [ UniqueIndex(fields=['user', 'product']), ] user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) grade = models.BooleanField() created_time = models.DateTimeField(auto_now_add=True, verbose_name='created_time') I want to create a row in the database with a post request class PostRatingFromUser(generics.CreateAPIView): queryset = ProductRating.objects.all() permission_classes = [IsAdminOrAuthenticatedUser, ] serializer_class = ProductRatingSerializer def post(self, request, *args, **kwargs): rating_from_db = ProductRating.objects.get(product_id=kwargs['pk'], user=request.user) if rating_from_db: rating_from_db.grade = kwargs['grade'] rating_from_db.save() else: ProductRating.objects.create(product_id=kwargs['pk'], grade=kwargs['grade']).save() return Response(status=200) But before adding, I check if there is such a database, if there is, then I just change the value of 'grade' but it gives me an error: product.models.ProductRating.DoesNotExist: ProductRating matching query does not exist. -
In Django, how can I select an object from the database and pass the parameters not to the url, but in some other better way?
I'm new to Django, in a page i have a combobox which is populated by fields from a database (simply city names). I select an object from the database with parameters which I pass to the url. I know this isn't the cleanest approach and that there is a better way. Is there a better way to populate the combobox without passing database parameters to the url? Then passing the parameters in a different and better way. How could my code take a different approach? models.py from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name forms.py from .models import City class SelectCityForm(forms.Form): city = forms.ModelChoiceField(queryset=City.objects.all()) class Meta: model = City fields = ('name') views.py def city_detail(request): form = CitySelectForm() object = None if request.method == "POST": form = CitySelectForm(request.POST) if form.is_valid(): city_id = form.cleaned_data['city'] object = City.objects.get(id=city_id) context = {'form': form, 'object': object} return render(request, 'app1/home.html', context) home.html <form action="/url-to-city_detail-view/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), #Aggiunto per combobox path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views.home, …