Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', }, … -
CORS Error when I use django api with reactjs
I'm using ReactJS on the front end and Django API on the back end. I'm currently testing some functionality by connecting my localhost(backend) to a ngrok URL and hitting that ngrok URL with my ReactJS frontend that is already in its own test environment in PROD. The POST requests work just fine, but when there is a GET request, in the developer tools in chrome, I get the following: Access to fetch at 'https://'{NGROK URL} from origin 'https://{PROD URL}.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I've included the necessary CORS_ALLOWED_ORIGINS and even CORS_ALLOW_ALL_ORIGINS. When I test this from frontend(localhost) to backend(localhost), it works normally. Does anyone know why this wouldn't work? -
How to Integrate WebSocket with Django API Views for Messaging
I am new to Djnago and new to WebSockets so I am a little unsure on the proper integration to use when working with messaging. I have an API view to send a message to a user which adds that message to the database and also create a websocket message. I also have an API view to get the conversation between 2 users. My logic is that when a user opens their conversation on the front-end, the get_conversation api view will run to get their previous texts and then on the front-end the WebSocket will be used to dynamically update their screen with new texts they are currently sending using the send_message API view. Is my current logic/implementation the correct approach that is normally used or is there something that could be done differently? This is the API view I am using to send a message: @api_view(['POST']) @permission_classes([IsAuthenticated]) def send_message(request, receiver_id): sender = request.user content = request.data.get('content') # Ensures there is content within the message if not content: return Response({"error": "Message content is required"}, status=status.HTTP_400_BAD_REQUEST) # Ensures the receiving user exists try: receiver = User.objects.get(id=receiver_id) except User.DoesNotExist: return Response({"error": "Receiver not found"}, status=status.HTTP_404_NOT_FOUND) # Ensures the user is not sending … -
what am i doing wrong in Pagseguro API
I trying to use Pagseguro API sandbox on Django but it doesnt work I know that im passing the encryptedCard but the API cannot read it "charges": [ { "reference_id": "referencia da cobranca", "description": "descricao da cobranca", "amount": { "value": 500, "currency": "BRL" }, "payment_method": { "soft_descriptor": "WEBDESIGN", "type": "CREDIT_CARD", "installments": 1, "capture": True, "card": { "encrypted": request.POST['encriptedCard'], "security_code": "123", "holder": { "name": "Jose da Silva" }, "store": True } } } ] }) it returns {"error_messages":[{"code":"40002","description":"invalid_parameter","parameter_name":"charges[0].payment_method.card.encrypted"}]} Ive printed in terminal to see if it are be passing by post and it is but i cant figured out why the json dont reads -
Django: SUM of COUNT in annotations
I have the following simple models: class Member(models.Model): name = models.CharField(max_length=100) class Booking(models.Model): date = models.DateField(default=now) price = models.DecimalField(max_digits=7, decimal_places=2) organizer = models.ForeignKey(Member, on_delete=models.CASCADE) booked_for = models.ManyToManyField(Member, related_name="booking_claims") Now, in a view, I want to annotate my Members with infomation about the total spendings of a member (i.e. the sum of all prices of bookings where this member is the organizer) and the total claims from this member (i.e. the sum of all proportional costs of bookings where the member takes part in). Ideally, this would work as follows: members = Member.objects.annotate( total_spending=Sum("booking__price", default=0), total_claims=Sum(F("booking_claims__price") / Count("booking_claims")), ) However, I get an error that Count is an aggregate and I cannot use Sum on an aggregate. I know, there exist some related questions and I have already tried a lot of different things, including subqueries and custom Count functions but I can't get it to work. Is there someone that knows how to solve this? -
How to dumps Python object to JSON without "" using json.dumps()?
I need to request post a 36-digit id with other things to a url. This code should be sent as json. But when I try to json.dumps() it, the initial and final quotes are also counted and as you can see I reach 38 characters and get error. merchant_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' merchand_id_json = json.dumps(merchant_id) #check len of merchat id and merchant id in json format print('len merchant_id is', len(merchant_id)) print('len merchand_id_json is', len(merchand_id_json)) # Set header request_header = { 'accept': 'application/json', 'content_type': 'application/json', } # Send request res = requests.post( url=request_url, data= { "merchant_id": merchand_id_json, }, headers=request_header) # Check res content in terminal print('res =', res) # Check res.text in terminal print('res.text =', res.text) in Terminal: len merchant_id befor json is 36 len merchand_id after json is 38 res = <Response [200]> res.text = {"data":[],"errors":{"code":-9,"message":"The input params invalid, validation error.","validations":[{"merchant_id":"The merchant id may not be greater than 36 characters."},{"merchant_id":"string is not a valid uuid."}]}} How can I convert this 36-digit id to json format without increasing the number of characters? -
Why am I getting MultiValueDictKeyError when using requst.files in Django?
I am trying to upload a file to my Django Server using HTML input type file. HTML Code <form action="csv/upload" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="file" name="csvFile" accept=".csv"> <button type="submit">submit</button> </form> views.py def upstud(request): var = "0sdfs" my_uploaded_file = request.FILES["csvFile"] num = type(my_uploaded_file) return render(request, "signup.html", {"var": num}) On Submitting the file I get MultiValueDictKeyError at:- my_uploaded_file = request.FILES["csvFile"] I have tried using my_uploaded_file = request.FILES.get("csvFile"]) This simply returns none What is the issue? -
Staff user is getting by default all permission in Django Admin Site - Custom User Model (AbstractBaseUser)
I am using Django custom user model inheriting from AbstractBaseUser & PermissionsMixin. When I make a staff user, the user gets all the permission by default, means staff has superuser privileges of 'view', 'change', 'add', & 'delete' on all the apps and models in django admin site, But when I use Django's built-in User model it works perfectly fine, when a staff user login it says 'you don't have permission' and when I assign the permission I want to give the staff has the only permission in django admin site. my model has both methods with True has_perm() has_module_perms() Do I need to update something which is commonly made mistake? I tried changing has_perm and has_module_perms to return False but it restrict superuser also. -
How to locate django logs in nginx docker setup?
I have my website build using below technology stack, Django GraphQL Postgres Nginx Docker Below is how my docker-compose file looked like, version: "3.9" services: web: extra_hosts: - "host.docker.internal:host-gateway" build: context: . dockerfile: Dockerfile.prod command: gunicorn sports_league.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/code - static_volume:/code/staticfiles - media_volume:/code/mediafiles environment: - PRODUCTION=true env_file: - ./config/.env.prod expose: - 8000 nginx: build: ./nginx ports: - "80:80" depends_on: - web volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles volumes: pgdata: static_volume: media_volume: When I run the django app locally, I can see the logs (print statements) on terminal. However when I run it using Docker as a service, I don't see those in the container logs. It looks like nginx is causing this to happen. I check nginx container logs as well, but I cannot find the logs there as well. Below is how my nginx configuration file looks like, upstream sports_league { server web:8000; } server { listen 80; location / { proxy_pass http://sports_league; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 100M; } location /static/ { alias /code/staticfiles/; } location /media/ { alias /code/mediafiles/; } } Please help me to locate the logs or those print statements. -
TypeError at /cart/add_cart/7/ _cart_id() takes 0 positional arguments but 1 was given
from urllib import request from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Cart, CartItem from store.models import Product Create your views here. def _cart_id(): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) #get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 #cart_item.quantity = cart_item.quantity + 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return HttpResponse(cart_item.product) exit() return redirect('cart') def cart(request,): return render(request, 'store/cart.html') Hey, so basically when I'm running the server to test the "Add to cart" button I get this error. enter image description here -
Django missing underscore in models name from admin
I'm working on a project using Django cookie cutter I have an issue with adding a through model (EventCompetitor) to my app for additional info related to a many to many relationship (competitors). I can see in the db that the through table is called: "events_event_competitor" but Django throws an error in the admin because its trying to query: "events_eventcompetitor". django.db.utils.ProgrammingError: relation "events_eventcompetitor" does not exist what would cause this issue? models.py class EventCompetitor(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) competitor = models.ForeignKey(Competitor, on_delete=models.CASCADE) order = models.IntegerField(default=0) class Meta: unique_together = ('event', 'competitor') class Event(models.Model): """ Default custom evens model for oddsx. """ # Choices for the status field STATUS_CHOICES = [ ('CANCELLED', 'Cancelled'), ('LIVE', 'Live'), ('SCHEDULED', 'Scheduled'), ('POSTPONED', 'Postponed'), ('FINISHED', 'Finished'), ] name = models.CharField(verbose_name="Event name", max_length=30) slug = models.SlugField(verbose_name="Slug", max_length=30) sport = models.ForeignKey(Sport, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="events") competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name="events", null=True) competitors = models.ManyToManyField(Competitor, through='EventCompetitor', through_fields=('event', 'competitor')) status = models.CharField(verbose_name="Status", max_length=10, choices=STATUS_CHOICES, default='SCHEDULED') start_date = models.DateTimeField(verbose_name="Start date", null=True, blank=True) venue = models.CharField(verbose_name="Venue", max_length=60, blank=True, null=True) city = models.CharField(verbose_name="City", max_length=80, blank=True, null=True) class Meta: verbose_name_plural = "Events" def __str__(self): return self.name admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} list_display = ("name", "slug", "country", "sport") list_filter = …