Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: static files not served locally
I know this question was previously asked and I already tried many different configurations to fix this. I had no problem serving my static files locally when developing but, if I remember correctly (don't know exactly because of the browser cache), I ran python manage.py collectstatic and then all static files were nowhere to be found: [15/May/2023 08:55:59] "GET /static/js/script.js HTTP/1.1" 404 179 [15/May/2023 08:55:59] "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 ... Here is my settings.py: DEBUG = ENV.bool("DEBUG") # set to True INSTALLED_APPS = [ "django.contrib.staticfiles", ... ] STATIC_URL = "static/" STATIC_ROOT = BASE_DIR / STATIC_PATH # I have checked that the path is correct STATICFILES_DIRS = [ # I tried with and without STATICFILES_DIRS BASE_DIR / "vhsapp" / "static" ] urls.py ... if settings.DEBUG: urlpatterns += [ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT), ] base_site.html {% extends "admin/base_site.html" %} {# TEMPLATE EXTENSION FOR THE DEFAULT ADMIN INTERFACE #} {% load static %} {% block extrahead %} {{ block.super }} <link rel="icon" type="image/x-icon" href="{% static 'img/favicon.png' %}"> <!-- 404 error --> <script> const APP_NAME = "{{ APP_NAME }}"; // variable defined correctly </script> {% endblock %} Project arborescence project_root/ ├── staticfiles/ # all static files are inside this directory ├── templates/ │ └── admin/ … -
How to change UUID field representation globally in Django?
I have defined various models with UUID ids in a Django DRF project: id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) However, the default to_representation implementation of rest_framework.serializers.UUIDField is: valid_formats = ('hex_verbose', 'hex', 'int', 'urn') def to_representation(self, value): if self.uuid_format == 'hex_verbose': return str(value) else: return getattr(value, self.uuid_format) So the output of all API routes in the project render the UUID output as a string, divided by dashes: "id": "86582c7d-a10e-4e2e-be42-8e045ca0fa00", what I want to do is to change the global representation of UUIDs in all the project serializers/routes to hex (removing the dashes), "id": "86582c7da10e4e2ebe428e045ca0fa00". Does anyone know how can I address rest-framework to change the output for all UUIDs? I don't want to change any pre-defiend model, serializer or view! -
Implement reset password link for certain time or for one time use only in django
I am new to Django, I am working on a project and want that their password should be destroyed after certain time. Here is my reset password code if request.method == "POST": user_email = request.POST.get('email') domain_name=get_current_site(request).domain token=str(random.random()).split('.')[1] link=f'http://{domain_name}/resetpassword/{token}' if not Registered_user.objects.filter(email=user_email).first(): messages.error(request, "No user found with this email") return redirect('/confirmemail/') data = Registered_user.objects.get(email=user_email) data.token = token data.save() subject = 'Reset password' email_template = get_template('admin/email.html').render({'link': link}) from_email = 'service@example.co' message = EmailMessage(subject, email_template, from_email, [user_email]) message.content_subtype='html' message.send() messages.success(request, f'Shared reset password link at {user_email}') return render(request,'admin/forgotpassword.html',{'title':title}) Thanks for your help requirement Need this reset link should be valid for one time use or for certain hours -
Show popup when user is not authenticated Django
I'm using django allauth. But I want to implement django allauth inside a popup instead of a new login page. Here is the code: contact_entry_form = ContactEntryForm() if request.user.is_authenticated: if request.method == "POST": contact_entry_form = ContactEntryForm(request.POST) if contact_entry_form.is_valid(): ContactEntry.objects.create( name = contact_entry_form.cleaned_data["name"], email = contact_entry_form.cleaned_data["email"], subject = contact_entry_form.cleaned_data["subject"], message = contact_entry_form.cleaned_data["message"]) return redirect("mainpage") else: # I want to change this, showing a popup error on the same page instead of redirecting the user return redirect("account_login") The question is: How to return a popup to the current page instead of redirecting the user when the user is not logged in yet? -
selenium.common.exceptions.ElementNotInteractableException:
selenium.common.exceptions.ElementNotInteractableException: Message: >Element name="Description"> is not reachable by keyboard I developed the python source code: # Fill out and submit the new message form wait.until(EC.presence_of_element_located((By.ID, "Title"))).send_keys("Test Title") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "SupportId"))).send_keys("بخش مالی (فاکتور/پیش فاکتور/بازگشت وجه)") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "DegreeId"))).send_keys("کم") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "File"))).send_keys("test.txt") sleep(1) wait.until(EC.presence_of_element_located((By.NAME, "Description"))).send_keys("Test Message ") sleep(1) wait.until(EC.presence_of_element_located((By.XPATH, '//span[text()="ارسال"]'))).click() sleep(1) This python source code is for filling the fields of this form: <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <p class="modal-title">ارسال پیام جدید</p> </div> <div class="modal-body"> <form action="/fa/Account/SendTicket" autocomplete="off" data-ajax="true" data-ajax-complete="onSendTicketComplete" data-ajax-method="POST" id="form2" method="post" novalidate="novalidate"><input name="__RequestVerificationToken" type="hidden" value="rworgZ7wuRPEkDBjIanQ1WslPXlcnV64qDkPCY2HB-M0WbXYSZjUKcZSEEYChpXPWS2XRi5MGGtu_6CLGIJElF2JTRnCGOMGPg-gCSeZalEpMkPl0"> <div class="row"> <div class="col-xs-12"> <label class="form-label" for="Title">عنوان<span class="label-required">*</span></label> <div class="formElement"> <i class="fa fa-font"></i> <input class="form-control" data-val="true" data-val-required="عنوان را وارد نمایید." id="Title" name="Title" type="text" value=""> <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span> </div> </div> <div class="col-xs-12"> <label class="form-label" for="SupportId">بخش<span class="label-required">*</span></label> <div class="formElement"> <select class="form-control" data-val="true" data-val-number="The field بخش must be a number." data-val-required="بخش را وارد نمایید." id="SupportId" name="SupportId"><option value="">-- بخش --</option> <option value="10164">بخش مالی (فاکتور/پیش فاکتور/بازگشت وجه)</option> <option value="10163">خدمات پس از فروش (بازکشت کالا)</option> <option value="10162">پشتیبانی</option> </select> <span class="field-validation-valid" data-valmsg-for="SupportId" data-valmsg-replace="true"></span> </div> </div> <div class="col-xs-12"> <label class="form-label" for="DegreeId">اهمیت<span class="label-required">*</span></label> <div class="formElement"> <select class="form-control" data-val="true" data-val-number="The field اهمیت must be a number." data-val-required="اهمیت را وارد نمایید." id="DegreeId" name="DegreeId"><option value="">-- اهمیت --</option> <option value="0">کم</option> <option value="1">متوسط</option> <option value="2">فوری</option> … -
403 Forbiden. CSRF failed - ONLY FOR ONE USER randomly. Works ok after cleaning cash on the computer, but after day or 2 its same error again
One mac user randomly gets "CSRF verification failed" error when submiting a form. When he cleans the cache, its working good for a day or two, and then gets same error again. Cleaning the cache solves problem. But does not hold for long. only one user, others are fine. for 3 years was working fine. Any hints what can be the reason? -
wagtail cms: how to sort users by last login
I(and my customer) want to sort users in the backend(menu > settings > users)by last login. By default I'm obly able to sort by name and by username. What is the best practice to solve that? Also in version 5 I did not found this function. -
selenium.common.exceptions.ElementNotInteractableException
selenium.common.exceptions.ElementNotInteractableException: Message: Element is not reachable by keyboard Stacktrace: RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8 WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:183:5 ElementNotInteractableError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:293:5 webdriverSendKeysToElement@chrome://remote/content/marionette/interaction.sys.mjs:624:13 interaction.sendKeysToElement@chrome://remote/content/marionette/interaction.sys.mjs:598:11 sendKeysToElement@chrome://remote/content/marionette/actors/MarionetteCommandsChild.sys.mjs:546:29 receiveMessage@chrome://remote/content/marionette/actors/MarionetteCommandsChild.sys.mjs:163:31 I developed the python source code: # Fill out and submit the new message form wait.until(EC.presence_of_element_located((By.ID, "Title"))).send_keys("Test Title") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "SupportId"))).send_keys("بخش مالی (فاکتور/پیش فاکتور/بازگشت وجه)") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "DegreeId"))).send_keys("کم") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "File"))).send_keys("test.txt") sleep(1) wait.until(EC.presence_of_element_located((By.ID, "Description"))).send_keys("Test Message ") sleep(1) wait.until(EC.presence_of_element_located((By.XPATH, '//span[text()="ارسال"]'))).click() sleep(1) This python source code is for filling the fields of this form: <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <p class="modal-title">ارسال پیام جدید</p> </div> <div class="modal-body"> <form action="/fa/Account/SendTicket" autocomplete="off" data-ajax="true" data-ajax-complete="onSendTicketComplete" data-ajax-method="POST" id="form2" method="post" novalidate="novalidate"><input name="__RequestVerificationToken" type="hidden" value="rworgZ7wuRPEkDBjIanQ1WslPXlcnV64qDkPCY2HB-M0WbXYSZjUKcZSEEYChpXPWS2XRi5MGGtu_6CLGIJElF2JTRnCGOMGPg-gCSeZalEpMkPl0"> <div class="row"> <div class="col-xs-12"> <label class="form-label" for="Title">عنوان<span class="label-required">*</span></label> <div class="formElement"> <i class="fa fa-font"></i> <input class="form-control" data-val="true" data-val-required="عنوان را وارد نمایید." id="Title" name="Title" type="text" value=""> <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span> </div> </div> <div class="col-xs-12"> <label class="form-label" for="SupportId">بخش<span class="label-required">*</span></label> <div class="formElement"> <select class="form-control" data-val="true" data-val-number="The field بخش must be a number." data-val-required="بخش را وارد نمایید." id="SupportId" name="SupportId"><option value="">-- بخش --</option> <option value="10164">بخش مالی (فاکتور/پیش فاکتور/بازگشت وجه)</option> <option value="10163">خدمات پس از فروش (بازکشت کالا)</option> <option value="10162">پشتیبانی</option> </select> <span class="field-validation-valid" data-valmsg-for="SupportId" data-valmsg-replace="true"></span> </div> </div> <div class="col-xs-12"> <label class="form-label" for="DegreeId">اهمیت<span class="label-required">*</span></label> <div class="formElement"> <select class="form-control" data-val="true" data-val-number="The field اهمیت must be a number." data-val-required="اهمیت را وارد نمایید." id="DegreeId" name="DegreeId"><option value="">-- اهمیت … -
I have tried to run the project but i can't
File "C:\Users\\AppData\Local\Programs\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\M\AppData\Local\Programs\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Mabel Aboagye\Downloads\Курсовая\myvenv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Mabel Aboagye\Downloads\Курсовая\myvenv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Mabel Aboagye\Downloads\Курсовая\myvenv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Mabel Aboagye\Downloads\Курсовая\myvenv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\\Downloads\Курсовая\myvenv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\\Downloads\Курсовая\myvenv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\\Downloads\Курсовая\myvenv\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\\Downloads\Курсовая\myvenv\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\Mabel Aboagye\AppData\Local\Programs\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 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'modeltranslation' how can i make to work? -
NoReverseMatch at error using Django/Python
I am a beginner using django and python and I can't see any error in my code. Can you help me with my error. the process was to add a new data and will display in table after add. Urls.py from django.urls import path, re_path from django.conf import settings from . import views from django.conf.urls.static import static urlpatterns =[ path('',views.index, name='index'), re_path('<int:am_ast>', views.view_asset, name='view_asset'), path('add/', views.add_asset, name='add_asset',) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import asset from .forms import assetform # Create your views here. def index(request): return render(request, 'assetmanagement/index.html', { 'assets': asset.objects.all() }) def view_asset(request, am_ast): ast = asset.objects.get(pk=am_ast) return HttpResponseRedirect(reverse('index')) def add_asset(request): if request.method == 'POST': form = assetform(request.POST) if form.is_valid(): new_category = form.cleaned_data['category'] new_am_ast = form.cleaned_data['am_ast'] new_sn = form.cleaned_data['sn'] new_desc = form.cleaned_data['desc'] new_acq_date = form.cleaned_data['acq_date'] new_iss_date = form.cleaned_data['iss_date'] new_emp_name = form.cleaned_data['emp_name'] new_emp_dept = form.cleaned_data['emp_dept'] new_scrp_name = form.cleaned_data['scrp_name'] new_scrp_date = form.cleaned_data['scrp_date'] new_loc = form.cleaned_data['loc'] new_stat = form.cleaned_data['stat'] new_rmks = form.cleaned_data['rmks'] # new_img = form.cleaned_data['img'] new_asset = asset( category= new_category, am_ast = new_am_ast, sn = new_sn, desc = new_desc, acq_date = new_acq_date, iss_date = new_iss_date, emp_name = new_emp_name, emp_dept = new_emp_dept, scrp_name = new_scrp_name, … -
How can I serialize related fields and keep the HTML form a dropdown for foreign key fields?
I apologize if my question is confusing. I have defined my serializers like this: class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = "__all__" class ConventionSerializer(serializers.ModelSerializer): venue = VenueSerializer(read_only=False, many=False) class Meta: model = Convention fields = "__all__" I do get the desired JSON raw data: { "venue": { "name": "", "address_1": "", "address_2": "", "city": "", "state_province": "", "postal_code": "", "country": "", "webpage": "" }, "name": "", "description": "", "webpage": "", "start_date": null, "end_date": null } However in the HTML form, instead of a dropdown for the venue (it is a foreign key), it gives the entire form for Venue. Desired HTML form: Resulting HTML form: Is there a way to set up the serializer so that I can return the JSON raw data above while also keeping the dropdown menu in the desired HTML form? Also, when I completely remove the line venue = VenueSerializer(read_only=False, many=False) from ConventionSerializer, the dropdown menu will show in the HTML form, but my JSON data will return: { "name": "", "description": "", "webpage": "", "start_date": null, "end_date": null, "venue": null } and if I set read_only=True for the VenueSerializer, it keeps the same JSON raw data, but it completely removes the venue … -
In a Django project, given a Page and a Reading model, how do I create a functionality for the user to click on words to select and save them?
In a Django project, I have a Page model (fields = ['book', 'page_number', 'text']) and a Reading model (fields = ['group', 'pages', 'due_date']). How can we display the text of these pages so that when we click on a word, that word gets added to a dictionary of words with the key being the word and the values being the page_number where the word is and the word's starting index? I don't know what's the right combination of model, form, view, and JavaScript script to get this done. The following is basically the extent of my knowledge. So that's why I'm stuck. model.py class ReadingPerformance(models.Model): student = models.ForeignKey('Student', on_delete=models.CASCADE) reading = models.ForeignKey('Reading', on_delete=models.CASCADE) mistakes = models.JSONField() # First time using this, not sure what it does. def __str__(self): return f"{self.student} {self.reading}" form.py: class ReadingPerformanceForm(forms.ModelForm): class Meta: model = ReadingPerformance fields = ['student', 'reading', 'mistakes'] view.py: def add_reading_performance(request): form = ReadingPerformanceForm() if request.method == 'POST': form = ReadingPerformanceForm(request.POST) if form.is_valid(): form.save() return redirect('reading_performance_list') return render(request, 'add_reading_performance.html', {'form': form}) def reading_performance_list(request): reading_performances = ReadingPerformance.objects.all() return render(request, 'reading_performance_list.html', {'reading_performances': reading_performances}) add_reading_performance.html {% extends 'base.html' %} {% block content %} <h1>Add a new reading performance</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button … -
What is the difference between “my_app” and “my_app.apps.My_appConfig in the installed INSTALLED_APPS in settings.py?
Im new in Django and I would like to know what is the difference between “my_app” and “my_app.apps.My_appConfig in the installed INSTALLED_APPS in settings.py? -
How to connect Flutter backend with Django server?
So, I have a Django server running on my computer on local host, port 8000 (http://127.0.0.1:8000) and I'm creating a Flutter application. I want to connect my Flutter app backend with the Django server but I don't know how. Here is what I tried: First, I tried connecting to the computer's private ip address and it's not working: Future<void> test() async { print('1'); final url = Uri.parse('http://192.168.1.42:8000/users/'); final response = await http.get(url); print(response); print('2'); } Second, I tried connecting to local host: Future<void> test() async { print('1'); final url = Uri.parse('http://localhost:8000/users/'); final response = await http.get(url); print(response); print('2'); } and I got this error: E/flutter (27014): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused Finally I tried the local host adress equivalent, and I got the same error above: Future<void> test() async { print('1'); final url = Uri.parse('http://127.0.0.1:8000/users/'); final response = await http.get(url); print(response); print('2'); } -
Pass varaibles from context in an already made pdf
I am trying to make printable reports using xhtml2pdf library. But it seems very complicated to design and cutomize it according to my needs, also it does not support many css properties. I am thinking of a solution where I make my pdf templates in word and store them in my project and when I need to make a report I somehow access the pdfs and pass my dynamic data in it. Is this possible? or will I have to do it the hard way desgining the reports using xhtml2pdf? -
Issue in the requirements.txt file when trying to deploy to Vercel
I'm trying to deploy my Django web app, however, vercel is giving me this error when it failed to deploy: Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/workout_log/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/workout_log/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-q1jqann4/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` Here is my requirments.txt file: asgiref==3.6.0 beautifulsoup4==4.12.0 certifi==2022.12.7 charset-normalizer==3.1.0 dj-database-url==1.2.0 Django==4.1.4 django-bootstrap4==22.3 django-environ==0.10.0 django-heroku==0.3.1 gunicorn==20.1.0 heroku==0.1.4 idna==3.4 psycopg2==2.9.5 psycopg2-binary==2.9.6 python-dateutil==1.5 requests==2.28.2 soupsieve==2.4 sqlparse==0.4.3 tzdata==2022.7 urllib3==1.26.15 whitenoise==6.4.0 I tried to use Python 3.9 to fix the problem. I also tried to run this command on my local environment, but it said that pip3.9 is not a recognized command. -
Can I implement django's user authentication with Neo4j?
I am currently in the very early stage of a new project, which uses django for the backend. I am using Neo4j (neomodel) as a graph DB for all the relations between users etc. One thing I am struggling with at the moment is implementing the user authentication. Is it possible to use django's user auth system together with neomodel (Neo4j)? And if yes, how would I do that? If not, how would I implement the auth system? This is what my user profile model looks like right now. class Profile(StructuredNode): GENDERS = {"M": "Male", "F": "Female", "O": "Other"} # Properties uid = UniqueIdProperty() email = EmailProperty(required=True) password = StringProperty(required=True) username = StringProperty(unique_index=True, required=True) name = StringProperty() age = IntegerProperty() gender = StringProperty(choices=GENDERS) date_of_birth = DateProperty() creation_date = DateTimeProperty(default_now=True) I would appreciate any help! Thanks :) -
Extra blank lines in markdown file after submitting and saving in Django
I have a problem with saving information submitted by the user. One of my website's pages should have a textarea for markdown text. Data entered by the user in this area should be saved in a separate file after submitting. But when I open saved file after submitting, there are extra blank lines. Functions from views.py and HTML form are presented below. from django.shortcuts import render from django.core.files.base import ContentFile from django.core.files.storage import default_storage def index(request): if request.method == "POST": save_data(request.POST.get("title"), request.POST.get("content")) return render(request, "my_app/page.html") def save_data(title, content): filename = f"files/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) <form method="post"> {% csrf_token %} <label for="title">Enter a title:</label><br> <input id="title" type="text" name="title"> <br><br><label for="textarea">Enter the information:</label><br> <textarea id="textarea" name="content"></textarea><br><br> <input type="submit" value="Save Page"> </form> If I try, for example, to type in the textarea the following text: # My file This is markdown file. This file was created as an example for my question. I see this after submitting: # My file This is markdown file. This file was created as an example for my question. Could you help me solve this problem, please? Thank you in advance! Problem solution: OK, the essence of the problem becomes clear if you try to use … -
How to write a Group by clause in Django from two tables having one-to-many relationship
I am new to Django and stuck in following problem. I have two tables say user table and transactions table. I want to get Result by user with sum of their transactions. I have tried many queries, among them all the following query help up to some extent but not solving my problem. data = Transaction.objects.values('uname', 'tran_type').order_by().annotate(Total=Sum('tran_amount')) Primary Key Table (Users) Primary Key Table (Users) and Foreign Key Table (Transactions) Foreign Key Table (Transactions) Expected Result [{'uname': 'newton', 'tran_type': 'withdraw', 'Total': 38.256299999999996, 'tran_type': 'rakeback', 'Total': 25.365, 'tran_type': 'deposit', 'Total': 63.25}, {'uname': 'hajra', 'tran_type': 'withdraw', 'Total': 0.0, 'tran_type': 'rakeback', 'Total': 0.0, 'tran_type': 'deposit', 'Total': 39.46}] Or [{'newton', 'withdraw', 38.256299999999996, rakeback', 25.365, 'deposit', 63.25}, {'hajra', 'withdraw', 0.0, 'rakeback', 0.0, 'deposit', 39.46}] -
ImportError: cannot import name 'urlpatterns' from 'django'
I am trying to run my first Django application and when I run server I get the following error: ImportError: cannot import name 'urlpatterns' from 'django' (C:\Users\Chris\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py) Why is the following command that I use in views.py giving me errors: from django import urlpatterns As far as I know it should work? I have tried searching the web for an answer but I couldn't find anything. -
'score' value in the form always return as 0
in my school project we created a basic Django app which uses questionnaire and video to calculate depression. but at the final result page questionnaire 'score' always return as 0.why is that? i can use the 'score' in the depression_questionnaire function, it works normaly but the 'score' in the detect_emotion function alwyas return as 0 here is my view.py from django.contrib import messages, auth from django.contrib.auth.models import User from django.shortcuts import render, redirect import os import numpy as np from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from tensorflow.python.keras.models import load_model # from tensorflow.keras.preprocessing import image import cv2 from .forms import DepressionQuestionnaireForm from .models import DepressionQuestionnaire def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('depression_questionnaire') else: messages.info("invalid credentials") return redirect('/') return render(request, "login.html") def register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] confirmpass = request.POST['password2'] if password == confirmpass: if User.objects.filter(username=username).exists(): messages.info(request, "Username Taken") return redirect('register') else: user = User.objects.create_user(username=username, password=password) user.save(); messages.info(request, "user created") # print("user created") return render(request, "login.html") else: messages.info(request, "password not matched") return render(request, "register.html") return render(request, "register.html") def logout(request): auth.logout(request) return redirect('/') … -
how to aply ckeditor in django board site articleapp
[[enter image description here](https://i.stack.imgur.com/dhysZ.png)](https://i.stack.imgur.com/QhtR6.png) I tried to add ckeditor to my articleapp following a tutorial, but I'm having issues with image files not loading and the articleapp's upload function not working at all... -
My custom User Model is showing "Integrity Error - Foreign Key Constraint Failed" error
I have been trying to create a 'User' model that will take some fields. So, I have added these fields and modified the User model like that shown below: from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class MyUserManager(BaseUserManager): def create_user(self, name, email, is_analyst ,DOB, gender, city_code, password=None, password2=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( name=name, email=self.normalize_email(email), is_analyst = is_analyst, DOB = DOB, gender = gender, city_code = city_code ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, email, is_analyst, DOB, gender, city_code, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( name=name, email=email, is_analyst = is_analyst, DOB = DOB, gender = gender, city_code = city_code, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractUser): username = '' name = models.CharField(max_length=255) email = models.EmailField( verbose_name='Email', max_length=255, unique=True, ) is_analyst = models.BooleanField(default=False) DOB = models.DateField() gender_choices = ( ('M', 'Male'), ('F', 'Female') ) gender = models.CharField(max_length=1, choices=gender_choices) city_code = models.CharField(max_length=2) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_admin = … -
Login dans un projet python join Django
I always receice 'mauvaise authentification' I want to authenificate without using the User of Django and I didn't know how to do it all the steps fail -
django plugin system - Extend root urlpatterns with installed app urlpatterns
I'm working on a small plugin system using the existing Django features. I have managed to install plugins/apps based on the tenant(Multi-tenant model). The problem I'm currently facing is that I want the plugins to have the option to add additional URLs, which works when directly added to the urls.py file. But this won't help me because the plugins will reside in the respective tenant directories. I would really appreciate it if anyone could suggest how can we update/add more URLs to the current root URL. Please find the relevant codes below: raw_plugin_url_patterns = [] for app in apps.get_app_configs(): if hasattr(app, 'PluginMeta'): if importlib.util.find_spec(app.name + '.urls'): urlmod = importlib.import_module(app.name + '.urls') if hasattr(urlmod, 'urlpatterns'): raw_plugin_url_patterns.append( path('%s' % app.label, include((urlmod.urlpatterns, app.label))) ) PLUGIN_URL_PATTERS = [] if raw_plugin_url_patterns: PLUGIN_URL_PATTERS = [path('plugins/', include((raw_plugin_url_patterns, 'plugins')))] We can update the URL config, which I'm anyway doing for other logic in a middleware. public_schema_name = get_public_schema_name() if has_multi_type_tenants(): tenant_types = get_tenant_types() if (not hasattr(request, 'tenant') or ((request.tenant.schema_name == get_public_schema_name()) and 'URLCONF' in tenant_types[public_schema_name])): request.urlconf = get_public_schema_urlconf() else: tenant_type = request.tenant.get_tenant_type() request.urlconf = tenant_types[tenant_type]['URLCONF'] path = request.get_full_path() if path.startswith('/api'): tenant_type = request.tenant.get_tenant_type() request.urlconf = tenant_types[tenant_type]['API_URLCONF'] set_urlconf(request.urlconf) If there were some options which will allow us to change …