Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading BLOB from ts through django API to DB
I'm trying to upload some logData but in my database the informationfield is always empty, everything else gets uploaded correctly. I've tried two differnt ways, neither of them seem to work. I uploaded everything packed in a formdata with the logData as blob/string/... nothing worked The other way was creating an Object based on an interface and adding all the information (here aswell i tried string and blob) both didn't work, the field on the Database is always empty. I'm curios if i did something wrong cause the data should be in the database saved as log.csv with the hexstring in it i get the data as an UInt8Array ATM it looks like this: const test = new Blob([locAdjustmentBlob]) const formData = new FormData(); formData.append("log_user", locUser) formData.append("log_adjustment_blob", test) await store.state.apiHandler.postForm("/raw/logs/", formData) And in the the API: class Log(models.Model): log_id = models.AutoField(primary_key=True) log_user = models.CharField(max_length=50) log_adjustment_blob = models.BinaryField() If you need more information just ask Thanks! -
Django double User check
I’m aiming to establish a warehouse inventory manage system. Now I want to achieve that, when warehouse manager give the material to the worker for producing, I want the warehouse manager create a record(name, time, and manager name and so on) first, and then worker log in to his/her own site and check the record then confirm it. Which achieve double check. Is there any way to achieve it. Thank you for help. -
django admin styling is corrupted
I have just started learning Django and when I got to the admin page it appears to be corrupted, no style. I tried collectstatic which gave me an error, I tried to alter static_root but my settings.py does not have it. I tried to reload the page several times with Fn F5 but it did not help. I found some suggestions on the internet but they seem to be a bit too advanced for me, I don't want to make things worse. Is there something not too advanced you could recommend? Thank you! -
'method' object is not subscriptable in the browser
views.py def signup(request): if request.method == "POST": username = request.POST.get['username', False] firstname = request.POST.get['firstname', False] lastname = request.POST.get['lastname', False] email = request.POST.get['email', False] pass1 = request.POST.get['pass1', False] pass2 = request.POST.get['pass2', False] myuser = User.objects.create_user(username, email, pass1) myuser.firstname = firstname myuser.lastname = lastname myuser.save() messages.success(request, "Your Account has been succesfully created.") return redirect('signin') return render(request, "authentication/signup.html") when i click the signup button it says TypeError at /signup 'method' object is not subscriptable could you please help me to solve this? -
Using getStaticProps and getServerSideProps to make authenticated requests to django api
I have a next js application for the frontend and a django REST framework api on the backend. I am using jwt token authentication for my backend using django Simple JWT. Most of my api views are protected by authorization bearer header required. When my user logs in and is authenticated, my django backend responds with an access and refresh token with http only cookies. As I build this app I have a question. If I am making some requests to my backend protected routes with getServerSideProps or getStaticProps which don't run on the client, then is it actually necessary to protect some of my backend routes? If getServerSideProps or getStaticProps dont run on the client, then I don't run the risk of anyone making requests to my backend, considering I have CORS_ALLOWED_ORIGINS in my django settings to only allow requests from my frontend. -
Django Admin and Forms. BaseInlineFormSet. def clean( )
I need to implement a prohibition on removing the last ingredient from a recipe. So that the recipe is not left empty without ingredients, or make the recipe deleted when the last ingredient is deleted. I need to use BaseInlineFormset and method def clean( ), but i dont understand this class RecipeAdmin(admin.ModelAdmin): list_display = ('name', 'author', ) list_filter = ('name', 'author', ('tags', admin.RelatedOnlyFieldListFilter),) inlines = (IngredientRecipeInline, TagRecipeInline) class IngredientRecipeInline(admin.TabularInline): model = IngredientRecipe min_num = 1 class Recipe(models.Model): name = models.CharField( max_length=200 ) author = models.ForeignKey( User, related_name='recipes', on_delete=models.CASCADE, null=True, ) text = models.TextField( ) ingredients = models.ManyToManyField( Ingredient, related_name='recipes', through='IngredientRecipe' ) I"ve tried this but dont work class FormSet(BaseInlineFormSet): def clean(self): super(FormSet, self).clean() for form in self.forms: if not hasattr(form, 'cleaned_data'): continue data = form.cleaned_data if (data.get('DELETE') and form.instance.ingredients == 1): raise ValidationError('You cannot delete') -
Django does not seem to work with DigitalOcean Spaces
I have followed multiple tutorials on how to use the DigitalOcean object storage known as DigitalOcean Spaces on my Django project but I'm not able to do it. Actually, I was using it before and it was working, after that I moved the static files to Contabo Object Storage, and apparently their CDN is pretty slow so when I decided to go back to DO, it does not work anymore, I even went to the commit where I had it working and copied the exact same code. Here is the code I have on my settings.py: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): bucket_name = "XXXX" class StaticStorage(S3Boto3Storage): bucket_name = "XXXX" DEFAULT_FILE_STORAGE = "nafssi.settings.MediaStorage" STATICFILES_STORAGE = "nafssi.settings.StaticStorage" AWS_ACCESS_KEY_ID = "XXXX" AWS_SECRET_ACCESS_KEY = "XXX/XXXX/XXXXX" AWS_S3_ENDPOINT_URL = "https://XXXX.fra1.digitaloceanspaces.com" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/media/" STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/static/" When I try python manage.py collectstatic I have the following error: You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "D:\Data\Dropbox\D Drive\Toubib\Nafssi\Code\manage.py", line 22, in <module> main() File … -
Can't get Django to use Postgres
I am trying to switch a local Django project from the default sqlite3 database to a postgres database. I've been through several tutorials but nothing seems to work and I'm not sure what I'm doing wrong. Steps I've performed: In my postgres shell I can see there is a database called testdb. I've created a psql user bb with password foobar I ran the following command to grant bb access: GRANT ALL PRIVILEGES ON DATABASE testdb TO bb; Back in my virtual environment I run brew services start postgresql which prints: ==> Successfully started `postgresql@14` (label: homebrew.mxcl.postgresql@14) In my Django project's settings.py I have the following database configuration: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "testdb", "USER": "bb", "PASSWORD": "foobar", "HOST": "127.0.0.1", "PORT": "5432", } } Running python manage.py makemigrations produces the following error: /opt/miniconda3/envs/django-db/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:158: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "bb" warnings.warn( No changes detected Is there a step I've missed somewhere? No idea why there's no connection to the server available. -
Django cannot cast type integer to smallint when attempting to filter a queryset
I have an IntegerChoices Genre: from django.db import models # ... class Genre(models.IntegerChoices): fantasy = 0, scifi = 1, real = 2, #... and a book model that uses an ArrayField of PositiveSmallIntegerField with Genre as choices: from django.contrib.postgre.fields import ArrayField #... class Book(models.Model): #... genres = ArrayField(models.PositiveSmallIntegerField(choices=Genre.choices), null=True, blank=True)) #... When I try to filter by the genres field using values from the Genre choices I get an error that Django (or psycopg2) cannot cast an integer to a smallint: # traceback psycopg2.errors.CannotCoerce: cannot cast type integer to smallint[] LINE 1: ..."book" WHERE "book"."genres" @> 1::smallint... ^ The above exception was the direct cause of the following exception: # traceback django.db.utils.ProgrammingError: cannot cast type integer to smallint[] LINE 1: ..."book" WHERE "book"."genres" @> 1::smallint... ^ All of these attempts to filter trigger the above error: genre = Genre.scifi print(genre) # >>> 1 Book.objects.filter(genres__contains=genre) # error Book.objects.filter(genres=genre) # error However if I try to create a book instance with the genre everything works. book = Book.objects.create( #... genres=[genre] ) # no error print(book.genres) # >>> [1] Is the problem the PositiveSmallIntegerField? I couldn't find any "SmallIntegerChoices" as a replacement for the IntegerChoices. Or is it the way the filtering is/should … -
Django and Python Error: CustomUserAdmin has no attribute '_meta'
I am working on Django for Beginners and I have the following error message. Traceback message: (.venv) andrewstribling@Andrews-MBP news % python manage.py makemigrations accounts Traceback (most recent call last): File "/Users/andrewstribling/Desktop/code/news/manage.py", line 22, in <module> main() File "/Users/andrewstribling/Desktop/code/news/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/contrib/admin/__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/andrewstribling/Desktop/code/news/accounts/admin.py", line 27, in <module> admin.site.register((CustomUser, CustomUserAdmin)) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/contrib/admin/sites.py", line 118, in register if model._meta.abstract: AttributeError: type object 'CustomUserAdmin' has no attribute '_meta' So the last line there in the traceback that says my class customuser admin says attribute has no meta. I think that makes since because there isn't a … -
Why does an empty Django queryset truthy value not equal None?
I have an empty queryset type Foo which I expected to be None returning False when checked. Here is what my code looks like: >>> queryset = Foo.objects.all() >>> queryset <FooQuerySet []> >>> queryset is None False I'd hoped for True since its an actual empty queryset. -
MySQL server won't connect to PythonAnywhere Django website
Despite all of my efforts, I consistently get this message in the error logs when I try to open my site: django.db.utils.OperationalError: (1045, "Access denied for user '<myusername>'@'10.0.0.116' (using password: YES)"). My database connection code in Django is this: DATABASES = { "default": { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<myusername>$<mydatabasename>', 'USER': '<myusername>', 'PASSWORD': password, #This links to a password variable that was * imported in from another file 'HOST': '<myusername>.mysql.pythonanywhere-services.com', } } I have attempted to change the 'PORT' numerous times. It hasn't worked with a default '3306' port, an empty '' port, or in the current form with excluding the 'PORT' altogether. I have also included the password in the file natively, rather than importing it, but that also changed nothing. I'm very confused here as everything I've seen online appears to state that what I'm doing is correct, but it is still not working. -
Select2 responsiveness with DAL (Django Autocomplete Light) - Width 100% !important not working
It's been a struggle for the past day to me. I've looked everywhere on the internet and can't manage to get it done. I use DAL and initialize widget with URLs. So far so good: sector = django_filters.ModelMultipleChoiceFilter( queryset=Sector.objects.all(), widget=autocomplete.ModelSelect2Multiple( url="sector-autocomplete", attrs={ "data-placeholder": "Secteur", }, ), ) The problem occurs when I resize the page. The select2 items always overflow my container. There seems to be no other items which could be responsible for this overflow. The general recommendation is to set the following css rule: .select2 { width: 100%!important; } It actually feels like it's working when I begin reducing the viewport's width, until a point where the width remains fixed. The css rule on .select2 is actually taken into account, however the computed width seems to still be fixed. <select name="sector" data-placeholder="Secteur" id="id_sector" data-autocomplete-light-language="fr" data-autocomplete-light-url="/sector-autocomplete/" data-autocomplete-light-function="select2" multiple="" data-select2-id="id_sector" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"> </select> <span class="select2 select2-container select2-container--default" dir="ltr" data-select2-id="6" style="width: 428.5px;"> <span class="selection"> <span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1" aria-disabled="false"> <ul class="select2-selection__rendered"> <li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" placeholder="Secteur" style="width: 416.5px;"> </li> </ul> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"> </span> </span> I tried setting the width:100% setting on window resize with Javascript, but … -
How to set HTTP client hints in Django web app?
I would like to set HTTP client hints in a Django web app. I am especially interested in Sec-CH-Prefers-Color-Scheme, which is supported in Chromium browsers to detect the preferred color theme server side. It seems I have to send the browser the hint somehow so that it includes it in the request headers. -
On Prem Django app login with Azure AD Credentials
I have a usecase, we have a Django application running in onprem and it has admin login page, we have few users in Azure AD, we dont have any onprem AD, i want users to be authenticate with Azure AD, Can someone guide me how can this be achieved. Thanks Niranjan. -
Redirect viewset to another viewset on Django Rest Framework after parsing data
Say I have a viewset A, where I will receive a bunch of data via querystring. I want to parse this querystring on viewset A, and then redirect the request with the parsed querystring to viewset B. How would I go about doing this? I've tried insatiating the viewset B inside of A and then calling the get method manually to no avail. -
ModuleNotFoundError: No module named 'project_calxr'
I tried to deploy my website on Render but I got an error. this is my project CALX This is my setting in render log pic1 log pic2 This is a log that I got from deploying my website I am very new to coding. This is my first project. Sorry if I do something bad. I searched and tried many ways but still can't fix this. I'm not good at English, but I will use grammar to make you all understand what I want. I hope I can find a way to solve this error. I checked my file many times. I ask chat get. I watched the whole clip I found on YouTube. I try to translate and read some websites. -
How to configure solr with django-haystack
I am running solr 9.3 from docker and trying to integrate with django-haystack. I am unable to configure solrconfig.xml and schema.xml and not sure where to add these files. I tried generating schema.xml using python manage.py build_solr_schema but again I don't know how/where to put these files. Thanks in advance. -
How To Host Multiple Vite Apps in One Django Project?
Problem How would I host multiple vite applications built on different architectures (vanilla and react) in the same Dango instance? I have a a django app that had a pre-es6 javascript front end that I converted to a vite vanilla javascript application, delivered using the wonderful Django-Vite plugin. The app is working fine, but now there's a request to add a new react-based vite app to the existing django project, and django-vite does not support hosting multiple vite applications out of the box. Thoughts Have a single vite app that would redirect to another vite app, one of the two I need to build (not sure how this would work) Merge both vite manifest.json files together at build time to be served from a single location (don't know what the ramifications would be) ~Host a NextJS app external to Django~ (insert unicorns and rainbows here) <-- Can't do this one because leadership thinks integration would be more effort than it's worth Thanks! -
error in migrating django project with mysql database
when i want to migrate my django project with mysql as database i get this error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[] NOT NULL, `source` varchar(200) NOT NULL)' at line 1") this is my models.py file : from django_mysql.models import ListCharField from django.db import models # Create your models here. class news(models.Model): title = models.CharField(verbose_name='title of the news', max_length=200) text = models.TextField(verbose_name='news text') tags = ListCharField(base_field=models.CharField(max_length=200), max_length=200) source = models.URLField(verbose_name='news source url') #class Meta: # ordering = ['?'] def __str__(self): return self.title what should o do to fix it? these are versions for packages: Django==4.2.4 django-mysql==4.11.0 PyMySQL==1.1.0 mysqlclient==2.2.0 and this is mysql version installed in my system. mysql Ver 8.0.33-0ubuntu0.22.04.4 for Linux on x86_64 ((Ubuntu)) i tried to upgrade mysql but i get this error: E: Unable to locate package mysql -
nginx media files not at the intended location
I am working on a Django-React project and all my media files are located in the frontend folder. I am trying to serve the media files with nginx this is my first time working with Docker and nginx and I can't figure out how to make it work. can anyone help please? my file struckture is -backend (django-project) -Dockerfile -backend -settings.py -fontend (react-project) -Dockerfile -src -assets (media root for django and react) -nginx -Dockerfile -nginx.conf -docker-compose.yml My backend Dockerfile: # Use the official Python 3.11 image FROM python:3.11 # Copy the Django application code COPY . /app # Set the working directory WORKDIR /app # Install the dependencies RUN pip install -r requirements.txt # Expose port 8000 EXPOSE 8000 My frontend Dockerfile: # Use the official Node.js 16.13 image FROM node:16.13 # Copy the React application code COPY . /app # Set the working directory WORKDIR /app # Install the dependencies RUN npm install # Expose port 3000 EXPOSE 3000 # Start the React development server CMD ["npm", "start"] My nginx Dockerfile: # ./nginx/Dockerfile FROM nginx:latest # Set working directory WORKDIR /app # Copy Nginx configuration COPY ./nginx.conf /etc/nginx/nginx.conf the nginx.conf: events { worker_connections 1024; } http { server { … -
How to fix this: Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)/\\Z']
I am creating a Search filter for my blog. I have it working, but I am struggling to correctly link to a blog post in the search results. I can provide the results in simple text format. I followed this youtube tutorial . But how they built their project is a bit different to mine. The homepage of my blog already successfully links to specific blog posts, so I'm essentially trying to recreate elments of that in the search results page. I will paste my code below. The first and 2nd block quote are the 2 HTML pages, I use the same 'a href' in each one. But for some reason it won't work on my search results page, do I need to do something different to my def search_recipes(request): function in my views.py? search_recipes.html {% extends 'base.html' %} {% block content %} {% load static %} <center> {% if search %} <h1>You Searched For {{ search }}</h1> <br/> {% for recipe in recipes %} <a href="{% url 'post_detail' post.slug %}">{{ recipe }}</a> {% endfor %} {% else %} <h1>Hey! You Forgot to Search for a Recipe...</h1> {% endif %} </center> {% endblock %} Models.py from django.contrib.auth.models import User from … -
Django OnetoOne key insert on perform_update not working
in my models.py I've class Product(models.Model): code = models.CharField(primary_key=True, null=False) status = models.CharField(max_length=50, blank=True, null=True) class Price(models.Model): code = models.OneToOneField(Product, on_delete=models.CASCADE) price_tc = models.FloatField(blank=True, null=True) price_uc = models.FloatField(blank=True, null=True) price_bx = models.FloatField(blank=True, null=True) I want to insert the price after each insertion of product to ensure the one to one. So Implemented Django Perform Create in views.py class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer ordering = ["code"] def perform_create(self, serializer): serializer.save() Price.objects.create(self.request.data["code"]) I get the error : Price.code must be a "Product" instance, so i swap to def perform_create(self, serializer): serializer.save() m = Product.objects.get(code=self.request.data["code"]) Price.objects.create(code=m) But still not working. -
I want to change the labels of the login form
I want to change the labels of the login form, but this does not happen. When running, these labels show their default state, "login" and "password". thanks for your guide from django import forms from django.contrib.auth.models import User from .models import Profile class LoginForm(forms.Form): username = forms.CharField(lable='نام کاربری') password = forms.CharField(widget=forms.PasswordInput, lable='پسورد') Custom change of labels -
Django template - for look iterate over variable
I am looking for a way to iterate over variable in django template. In template I do not know how to assign variable in for loop. In get_context_date of ListView i am assigning data of two files to two vars like: context[f"{t_name}_header"] = db_oper context[f"{t_name}_body"] = db_header Context is generated for two files which results with vars like: context["test1_header"] context["test1_body"] context["test2_header"] context["test2_body"]` test1 and test2 are names populated from model. I can access them with object_list in template. In template html file I would like to iterate over context like: {% for object in object_list %} {% for item in object.name|add:"_header" %} ...do stuff {% endfor %} {% for item in object.name|add:"_body" %} ...do stuff {% endfor %} {% endfor %}` In result in html template I got nothing. How to properly filter variable in for loop so it could go thru eq. test1_header ?