Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Importing data from MYSQL to Django
I using the inspectdb in Django because im trying to get the data from my localhost(MYSQL) now if i add or edit a data into my Mysql does also update automatically the changes into my django? or any reccomendation would really appreciate. #newbie I tried the InspectDb and i thought if i made changes into Mysql the django also update -
No such column: 'wagtailcore_page.latest_revision_id' post upgrade from wagtail 3 to wagtail 4.2.4
I have recently upgraded my Wagtail version from v3 to v4.2.4 In this upgrade, the wagtailcore_page creates a new column latest_revision_id through one of its migrations under the library. When I am trying to run my test cases, it is giving me an error with this column saying that it does not exist. During deployment too I faced the same issue but running migrations in a specific order worked and issue was resolved. During test cases, the internal test database is newly created and looks for that column before the migration that creates the column runs due to which this issue arise. Please find below screenshot for reference. screenshot -
How do I pass the current logged in user to a field in a django and another model via an automic transaction?
I have a model form and can fulfill this requirement by setting the form field equal to request.user in the form view. My problem is I need to create whats basically a join table during the form save and can't figure out how to get the request.user to the form field then do a final validation and form save in the view. I'm pretty new to django and web dev in general. Any help is greatly appreciated. class LocationCreateForm(forms.ModelForm): class Meta: model = Organization fields = ("name", "email", "address", "addressline2", "city", "state", "about", "payment") def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(LocationCreateForm, self).__init__(*args, **kwargs) @transaction.atomic def save(self): data = super().save(commit=False) if self.user is not None: data.created_by = self.user data.save() OrganizationTeam.objects.create( organization=data, practitioner=self.user, is_admin=True, ) return data HttpResponse("Didn't work.") -
Django+Html: Convert a working project from manual html forms to Django forms
In this 100% fully functional project, i would like to replace the manually created html forms with the classic Django forms. Can you show me how I can convert this little project to Django forms? Thank you **CODE PYTHON ** models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class FullRecord(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) city_departure = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_departure") city_destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_destination") @property def departure_destination(self): return f"{self.city_departure}-{self.city_destination}" def __str__(self): return self.country.name views.py **from django.shortcuts import render from .models import FullRecord, Country def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries})** urls.py **from django.urls import path from . import views urlpatterns = [ path("", views.trip_selector, name="trips") ]** admin.py from django.contrib import admin # Register your models here. from .models import Country, … -
Django - How to delete an object from a button in a table
Objective: I want to delete an object from a table using a button in Django, but it's not working as expected. I've provided relevant parts of my code below. Can someone please guide me on what to add to urls.py and views.py to make this work? Database Attributes: _id: ObjectId response: string contact_id: string status: string views.py: def delete(request, id): try: excel_data = get_object_or_404(ExcelData, id=id) excel_data.delete() return redirect('web_services_app:tables') except ExcelData.DoesNotExist: # Handle the case where the object doesn't exist return HttpResponse("The object you're trying to delete doesn't exist.") **urls.py:** path('delete/<int:id>/', views.delete, name='delete'), **HTML Table in tables.html:** <div class="table-responsive"> <table class="table table-striped" id="data-table"> <thead> <tr> <th scope="col" style="font-weight: bold; color: black;">Response</th> <th scope="col" style="font-weight: bold; color: black;">Contact ID</th> <th scope="col" style="font-weight: bold; color: black;">Status</th> <th scope="col" style="font-weight: bold; color: black;">Actions</th> </tr> </thead> <tbody> {% for data in excel_data %} <tr class="table-row"> <td class="table-data">{{ data.response }}</td> <td class="table-data">{{ data.contact_id }}</td> <td class="table-data">{{ data.status }}</td> <td> <a class="btn btn-danger" href="/web_services_app/delete/{{ data.id }}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div> I appreciate any help you can provide. Thank you! ❤️ -
Django and react images don't appear with media folder
I use django rest framework and react where I am trying to show a user's profile picture by fetching them with axios in react. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/build/static') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'frontend/build/static/media') When I save a user's profile picture from admin panel the image is added in media folder. React is inside django. I use build in react and the structure looks like this. build static media images src public In the django rest framework page the image looks like this /media/images/Photo.jpg The problem is that even when I open the image from the admin panel it doesn't show and instead shows this Also in the frontend it doesn't appear. const profiles = friends.map(friend => { return ( <> <img src={friend.profile.profile_pic} /> </> ) }) -
How to update where the files are stored in Django app
I have a Django app that contains multiple models with FileField. I am saving by default every file directly in the Media folder. But as the app grew larger also Media folder became bigger. Now my idea is to move the files into separate folders split by models. So I am wondering what is the best practice when it comes to this? Shall I move the files to separate folders, then manually update every file location in the Database and then update Filefield path for every model? Or is there better approach? -
How to trigger a file download on click using Django and Javascript
I'm trying to produce a file download on click using Django and Javascript. I've nearly figured it out but I'm confused as to how to prevent Django from automaticall downloading the file once processing is complete. Here is my code: views.py: def translateFile(request) : if request.method == 'POST': source_language = request.POST.get('source_language') target_language = request.POST.get('target_language') form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path, source_language, target_language))#translates file file_location = uploaded_file_path with open(file_location, 'rb') as f: file_data = f.read() response = HttpResponse(file_data, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response Javascript: const formData = new FormData(form); const xhr = new XMLHttpRequest(); xhr.open('POST', form.getAttribute('action'), true); xhr.onreadystatechange = function () { console.log("Ready state: ", xhr.readyState); console.log("Status: ", xhr.status); if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { loaderDiv.style.display = 'none'; const downloadArrowDiv = document.querySelector('#download-btn'); downloadArrowDiv.style.display = 'flex'; const responseText = document.querySelector('#response_text') responseText.textContent = 'Click to download' // File was successfully translated, you can update UI here const downloadLink = document.querySelector('#response_text_anchor'); downloadLink.href = URL.createObjectURL(xhr.response); downloadLink.download = formData.get('file').name; downloadLink.click(); } else { // Handle error case console.error('Error translating file'); } } }; xhr.responseType = 'blob'; xhr.send(formData); }); HTML: <button … -
Django Heroku deployment errors
I am trying to deploy a web application and came across this issue where it says that it could not build wheels for myproject and that the runner is empty. I am just confused because I did not name it myproject on Heroku or VSCode. Is there something I might have done that made it register in this way? Regardless, I am trying to get over this roadblock so i can deploy it. remote: Building wheel for myapp (setup.py): finished with status 'done' remote: Created wheel for myapp: filename=myapp-0.1.dev0-py3-none-any.whl size=1166 sha256=ec655f854ab6a2c0ba6b36dda552a60e1b54af84d93a82785eda9229258b686c remote: Stored in directory: /tmp/pip-ephem-wheel-cache-7q7p2y16/wheels/8b/36/8b/cb810ee2b64417af5f91d361665839bd04414f112ecafcb1e0 remote: Building wheel for myproject (setup.py): started remote: Building wheel for myproject (setup.py): finished with status 'error' remote: error: subprocess-exited-with-error remote: remote: × python setup.py bdist_wheel did not run successfully. remote: │ exit code: 1 remote: ╰─> [3 lines of output] remote: warning: build_scripts: runner is an empty file (skipping) remote: remote: error: [Errno 2] No such file or directory: 'build/scripts-3.9/runner' remote: [end of output] remote: remote: note: This error originates from a subprocess, and is likely not a problem with pip. remote: ERROR: Failed building wheel for myproject remote: Running setup.py clean for myproject remote: Building wheel for mysqlclient (setup.py): started remote: Building … -
Why/when does Django makemigrations ignore a field and then do an Add field or Alter
This is the order Django created the migration - Create model MedicalTest - Create model MedicalTestGroup - Add field test_group to medicaltest - Alter unique_together for medicaltest (1 constraint(s)) This is the order I was expecting - Create model MedicalTestGroup - Create model MedicalTest Under what circumstances would it do what I am expecting? Why does it only get some of the ordering wrong some of the time? I understand and acknowledge that the outcome of both may be the same. I am asking what might cause Django to treat the order of one model differently from another because I'd like to get it right in my own code. -
Displaying HTML Body of an email
I am building a website using Python Django and would like to display emails. The emails are processed in the backend and are retrieved by ajax in JSON format. How can I safely display the html body of an email without destroying my main theme? I thought of implementing the email with iframes <iframe sandbox=""> . Are there other (better) ways to implement the html body without running into danger to compromise my website? -
whitenoise dosen't seem to work in Django
I want to check my web app in DEBUG = False and use whitenoise to do the static stuff. I have followed documentation and different blog post, I have also used the tool before, but this time it just does not work. Things I've tried: reinstalling whitenoise changing the location of whitenoise middleware collected statics many times and also changed its name restart the local web server settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "static" urls.py: urlpatterns = [ path('', include('bella_beauty_shop_web_store.urls')), path('123321/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here you can see that I have collected statics: Errors: When I put the DEBUG to FALSE, there is an error in the console: I really don't know what's wrong here. I am quit new to Django, but I have built some web apps and also used whitenoise before. As you know, I expect my html to render with style when the DEBUG is set to FALSE using whitenoise. -
Set API Data(JSON) Dynamically in Database views.py in Django using model when NUmber of columns of each tables are different
Set API Data(JSON) Dynamically in Database views.py in Django using model when NUmber of columns of each tables are different. I mean i am sending data from desktop software to web using api... in web I am getting that json data using request , Now i have alot of model classes that have different number of columns , i have tried alot of things but in knownledge nothing seem to be working ... I can add the data statically but would take alot of time to write the code, i have list of table_names so, Is there any way that code will automatically read the json data. Fetch Rows and columns from it and than add the numbers of rows to database . and vice versa -
DJANGO count number of records with raw MYSQL query and use result in html template
I'm trying to get the total number of records of my database using raw Mysql query and render it in a html template with something like {{ number_of_rec }} So far I have tried : view.py def number_of_rec(request): locate = Record.objects.raw("SELECT count(*) FROM mydb ") number_of_rec = len(locate.fetchall) return render(request, 'test.html', {'number_of_rec': number_of_rec}) But it's not working as {{ number_of_rec }} in the template html return nothing. I also tried number_of_rec = len(locate.fetchall)[0] but no changes. What am I doing wrong ? -
django database sqlite3 "no such a column" error
time to time i am facing "no such a column" error during django backend, django-admin development. when i face this issue, i cannot solve it. so that; i detele db.sqllite3 database file in my project location. i delete migrations files in application folder /djangioapp/migrations/ i run makemigrations, migrate and createsuperuser commands. i face with this error when i make changes on my Model. even more, i updated my model, i run makemigrations and migrate commands and i got this error no such a column when i try to access /admin in my djnago project. actually, after making migrations with makemigrations and migrate; i see the changes in 0001_initial.py file but it does not apply in database. is there any practical solution for "no such a column" error? i face with this error when i make changes on my Model. even more, i updated my model, i run makemigrations and migrate commands and i got this error no such a column when i try to access /admin in my djnago project. actually, after making migrations with makemigrations and migrate; i see the changes in 0001_initial.py file but it does not apply in database. -
Django keeps running migrations without changes made
I am creating a custom model field. It basically a one-level dictionary field which allows you to store model-subfields in a JSON manner in the database so fields which wont be queried upon will not take up an extra column. The issue is, whenever I predefine the default value for the field, the migrations keep thinking there's changes in the default values, and thus makes a new migration. The default values don't change across migration files, but maybe I am missing something about Django's internals. The custom field: class JSONStructField(models.JSONField): def __init__(self, fields=None, fieldrows=None, *args, **kwargs): self.fields = self.process_fields(fields) if fields else None self.fieldrows = self.process_fieldrows(fieldrows) if fieldrows else None kwargs["default"] = self.generate_default super().__init__(*args, **kwargs) @staticmethod def process_fields(fields): return [FieldType(**field[2]) if isinstance(field, tuple) else field for field in fields] @staticmethod def process_fieldrows(fieldrows): return [ [FieldType(**field[2]) if isinstance(field, tuple) else field for field in row] for row in fieldrows ] def generate_default(self): default = {} if self.fields: for field in self.fields: default[field.name] = field.default elif self.fieldrows: for row in self.fieldrows: for field in row: default[field.name] = field.default else: default = None return default def formfield(self, **kwargs): return super().formfield(**{ "widget": JsonInputWidget(fields=self.fields, fieldrows=self.fieldrows), **kwargs }) def deconstruct(self): name, path, args, kwargs = super().deconstruct() … -
Django: websockets for dynamic updates in real time to a django template (only this way, no Ajax etc.)
Can you please help me with dynamic update in template. I've found a lot of tutorials, but all of them are so different. It would be better to get an advice for my specific situation. So, that's the part of my template: <th scope="row"> <div class="player-date" data-toggle="modal" data-target="#playerDataEditModal"> <h2><i class="fa fa-bolt" aria-hidden="true"></i> <span class='total'>{{player.leavel.first.leavel|add:player.power.first.power}}</span></h2> <p><i class="fa fa-line-chart" aria-hidden="true"></i> <span class='level'>{{player.get_leavel}}</span> / <i class="fa fa-gavel" aria-hidden="true"></i> <span class='power'>{{player.get_power}}</span></p> </div> </th> I gotta dynamically change the class="total" tag. So what do I need to do that? I can't even decide what library to install, because they are different in these tutorials (django-channels, channels, channels[redis], channel-layers etc.). -
How can I return different field foreign key for two models related it
I want to retrieve the field full name for the field author in book creation, and the nickname to retrieve in article creation. models.py : class Author(models.Model): full_name = models.CharField( verbose_name="First Name", null=False, blank=False, max_length=20, ) nick_name = models.CharField( verbose_name="Nick Name", null=False, blank=False, max_length=20, ) def __str__(self): return f"{self.full_name}" class Book(models.Model): author = models.ForeignKey( Author, on_delete=models.PROTECT, related_name="book_author", null=False, blank=False, ) class Article(models.Model): author = models.ForeignKey( Author, on_delete=models.PROTECT, related_name="article_author", null=False, blank=False, ) How can I do it? -
Testing Django user and group permissions with a simple test fails
I've created a simple test with Django for testing permissions on class Reminder. ... class ReminderPermissionsTestCase(TestCase): def setUp(self): call_command('migrate') # Create content type for Reminder model content_type = ContentType.objects.get_for_model(Reminder) # Create permissions for Reminder model add_perm = Permission.objects.create( codename="add_reminder", name="Can add reminder", content_type=content_type ) view_perm = Permission.objects.create( codename="view_reminder", name="Can view reminder", content_type=content_type ) change_perm = Permission.objects.create( codename="change_reminder", name="Can change reminder", content_type=content_type ) delete_perm = Permission.objects.create( codename="delete_reminder", name="Can delete reminder", content_type=content_type ) # Create a Location location = Location.objects.create( name="Test Location", location_number="LOC-001", slug="test-location" ) # Create a Project associated with the Location project = Project.objects.create( date_last_budget_calculate="2023-09-03 12:00:00", slug="test-project", location=location ) # Create user groups editor_group = Group.objects.create(name=f"{project.slug}-editor") user_group = Group.objects.create(name=f"{project.slug}-user") # Create users and assign them to groups editor_user = get_user_model().objects.create(username="editor_user") editor_user.groups.add(editor_group) user_user = get_user_model().objects.create(username="user_user") user_user.groups.add(user_group) # Create a Reminder with CRUD permissions reminder_crud = Reminder.objects.create( open=True, reminder_date="2023-09-03 12:00:00", subject="Reminder with CRUD permissions", project=project, created_by=editor_user, reminder_text="This is a reminder with CRUD permissions." ) assign_perm("change_reminder", editor_user, reminder_crud) assign_perm("delete_reminder", editor_user, reminder_crud) # Create a Reminder with READ permissions reminder_read = Reminder.objects.create( open=True, reminder_date="2023-09-04 12:00:00", subject="Reminder with READ permissions", project=project, created_by=editor_user, reminder_text="This is a reminder with READ permissions." ) assign_perm("view_reminder", editor_user, reminder_read) def test_editor_has_crud_permissions(self): editor_user = get_user_model().objects.get(username="editor_user") reminder_crud = Reminder.objects.get(subject="Reminder with CRUD permissions") # … -
I installed 'mysqlclient' with pipenv but python doesn't recegnize it and gives "Did you install mysqlclient" error
I installed mysqlclient inside my python virtual enviorment to connect to a mysql database. But when I change the settings.py database engine settings from sqllite to mysql: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': BASE_DIR / 'db.sqlite3', } } I get this weird error telling me I havn't installed 'mysqlclient' package Exception in thread django-main-thread: Traceback (most recent call last): File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: libmysqlclient.so.21: cannot open shared object file: No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/reza/.local/share/virtualenvs/store-api-wAMLFNlP/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, … -
mongoDB django _id field instead of id using djongo
trying to learn Django and decided to go with MongoDB and djongo as the connector now, when I insert a document for mongoDB it is automatically received the _id which is ObjectId from mongodb I want that when I query all items to get also this _id and I want that when I insert it will not generate the "id" field because I have already the _id, and one more thing when I get one item by id or make a put/delete request I want to check if the id on params is equals to this ObjectId so this is what I've tried on serialzer.py from rest_framework import serializers from .models import Drink class DrinkSerialzer(serializers.ModelSerializer): class Meta: model = Drink fields = ['_id','name', 'desc'] model.py from djongo import models class Drink(models.Model): _id = models.ObjectIdField() name = models.CharField(max_length=200) desc = models.CharField(max_length=500) and on the requests for example get one by id from bson import ObjectId @api_view(['GET', 'PUT', 'DELETE']) def drink_detail(request, id): try: drink = Drink.objects.get(_id=ObjectId(id)) except Drink.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = DrinkSerialzer(drink) return Response(serializer.data) It is not working, with a lot of errors for example on model: the _id cannot be null on the request it is … -
I was creating a database for a Django project I'm working on and I ran into some errors in MySQL
I am currently following freeCodeCamp's tutorial on Django but I ran into errors. I typed "python mydb.py" in my Git Bash here's the error that occured. $ python mydb.py Traceback (most recent call last): File "C:\dcrm\dcrm\mydb.py", line 10, in <module> dataBase = mysql.connector.connect( ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\__init__.py", line 179, in connect return MySQLConnection(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\connection.py", line 95, in __init__ self.connect(**kwargs) File "C:\dcrm\virt\Lib\site-packages\mysql\connector\abstracts.py", line 716, in connect self._open_connection() File "C:\dcrm\virt\Lib\site-packages\mysql\connector\connection.py", line 208, in _open_connection self._do_auth(self._user, self._password, File "C:\dcrm\virt\Lib\site-packages\mysql\connector\connection.py", line 137, in _do_auth packet = self._protocol.make_auth( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\protocol.py", line 99, in make_auth packet += self._auth_response(client_flags, username, password, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\protocol.py", line 58, in _auth_response auth = get_auth_plugin(auth_plugin)( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dcrm\virt\Lib\site-packages\mysql\connector\authentication.py", line 190, in get_auth_plugin raise errors.NotSupportedError( mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported I am not yet good in either using Django and MySQL that's why I'm learning, can someone help me? Here is my code in my mydb.py # Install MySQL on your computer # https://dev.mysql.com/downloads/installer/ # pip install mysql # pip install mysql-connector # pip install mysql-connector-python import mysql.connector dataBase = mysql.connector.connect( host = 'localhost', user = 'root', passwd = 'cyrine18!datascience', ) # prepare a cursor object cursorObject = dataBase.cursor() # create a database cursorObject.execute("CREATE DATABASE zachyne") print("All … -
Django CMS cms_plugin setup for a message form to send an email is not working
I've setup a django cms site for a friend so that he can easily swap pictures out and do much of the work from the front-end. It's a very simple site and working great, but I have a page called 'contacts' using it's own cms template with a placeholder for the contact_form with the key component being a message form that sends the content as an email, this functionality is the reason I need to pull the form in as a plugin from the utilities app. It works great as a standalone django page, if the form is valid, it sends the email and a success message pops up as a bootstrap 5 alert advising it was sent; if the form isn't valid, an error message pops up instead. In the cms plugin however, I can add it in and it looks fine on the page but none of the functionality provided by the utilities/views/contact_form works and it doesn't appear to use the view functionality at all apart from drawing the template location from it. I've tested this with including print() at a few places in the utilities/views.py file. Any advice on how to ensure the full functionality of the … -
Django annotation across multiple models
I am looking to annotate to each BonusCustomer the Sum of billable_amount from the load table. class BonusCustomer(models.Model): customer = models.CharField(max_length=150, blank=True, null=True) dispatcher = models.ForeignKey(Dispatcher, on_delete=models.DO_NOTHING, blank=True, null=True) pick_city = models.CharField(max_length=150, blank=True, null=True) class Load(models.Model): load_id = models.CharField(max_length=20, unique=True) sales_agent = models.ForeignKey(Dispatcher, on_delete=models.DO_NOTHING, to_field='name', blank=True, null=True) total_miles = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True, editable=False) billable_amount_after_accessorial = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) class Dispatcher(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) I tried bonus_customers=BonusCustomer.objects.annotate(revenue=Sum('dispatcher__load__billable_amount')) but this gives me the total load revenue for each dispatcher, not BonusCustomer. Any help is appreciated. -
Transalting from English to Chinese on Python Django
I'm trying to convert my web-app to a couple of different languages in Python Django. I have managed to do so for English and French but the problem comes in when I add the zh hans or zh-cn. I get the following error: enter image description here Here's my settings.py from pathlib import Path import cloudinary import os from django.utils.translation import gettext_lazy as _ BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # 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', 'go', 'crispy_forms', 'cloudinary_storage', 'cloudinary', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'core.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, …