Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
have django models come with defaults
I have some Django models that my site relies on very heavily, it dose not even matter what is in the models just that there is something in them. 2 of my pages get markdown data from the models and then convert them to HTML and display it on the page. I tried messing around with the default parameters in some of the models but I still have to go by the admin dashboard to set things up. Is there a way that I can have the database come with pre-setup objects when I run python manage.py migrate? my models from django.db import models # Create your models here. class apikey(models.Model): key = models.CharField(default="") class video(models.Model): official_name=models.CharField(max_length=200) date = models.DateField() vid = models.CharField() thumbnail_url = models.CharField(max_length=1000) biblestudy = models.BooleanField() this is the models file from my other app from django.db import models # Create your models here. class message(models.Model): visitmessage = models.TextField(default="# hi") ourvision = models.TextField(default="# hi") -
What is wrong with the code? Register the product id and passwords
Work on a form django to register, which is the product ID, user name, password, and password confirmation. A message always appears that the product ID is incorrect, or the passwords do not match, even though all the entries are correct. def Registration(request): if request.method == "POST": productid = request.POST.get ("productid") username = request.POST.get ("username") password = request.POST.get ("password") re_password = request.POST.get ("productid") if password != re_password: messages. error (request, "Password is not Matching") return HttpResponseRedirect ("Registration") elif productid != ("05Md87fC36ya2B8i"): messages. error (request, "Product ID is not Correct") return HttpResponseRedirect ("Registration") else: act = Registrations () act. productid = productid act. username = username act. password = password act. re_password = re_password act.save() messages. success (request, "Your account has been successfully created") return HttpResponseRedirect ("company") else: return render (request,"Registration\Registration.html") ` <div class="card p-3 login-border"> <span class="text-center mt-3 text-pluse"><strong >Registration</strong></span> <form method="POST"> {% csrf_token %} <div class="input-group mb-2 mt-4"> <input type="password" class="form-control" name="productid " id="productid" placeholder="product Id" required> </div> <div class="input-group mb-2 mt-4"> <input type="text" class="form-control" name="username " id="username" placeholder="Your Username"required> </div> <div class="input-group mb-2 mt-4"> <input type="password" class="form-control" name="password" id="password" placeholder="Your password"required> </div> <div class="input-group mb-2 mt-4"> <input type="password" class="form-control" name="re_password" id="re_password" placeholder="Confirmation Your password" required> </div> <div class="form-check … -
Chained dropdown not working with HTMX and django
Hi guys I'm basically experimenting with HTMX and django to create a chained dropdown, the thing is that i don't really understand what's going on because I can't find the error in the code. from django import forms from django.shortcuts import render from ..models import UserLicense, CompanyInfo class PruebaForm(forms.Form): company = company = forms.ModelChoiceField( queryset=CompanyInfo.objects.all(), widget=forms.Select(attrs={"hx-get": "load_users/", "hx-target": "id_user"}) ) user = forms.ModelChoiceField( queryset=UserLicense.objects.none(), ) def locationview(request): form = PruebaForm () return render(request, 'template_de_prueba.html', {"form": form}) def load_users(request): company_id = request.GET.get('company') users = UserLicense.objects.filter(company_id=company_id) return render(request, 'users_dropdown_list_options.html', {'users': users}) At this point this peace of code should be bringing the data from the url "load_users/" when selecting the company but the thing is that it's not doing it and i don't understand why this is the template for the form {% extends "main_page_layout.dj.html" %} {% block content %} <form method="post"> {% csrf_token %} {{form.as_p}} </form> {% endblock %} this is the template for getting all the usernames {% for user in users %} <option value={{user.id}}>{{user.user_name}}</option> {% endfor %} and these are the two main models class CompanyInfo(models.Model): """Company information model.""" name = models.TextField(primary_key=True, blank=False, null=False) country = models.TextField(blank=True, null=True) contact_person = models.TextField(blank=True, null=True) contact_person_email = models.TextField(blank=True, null=True) def __str__(self): return … -
drf_spectacular schema annotation for optional serializer return type
I have a Django Rest Framework ModelSerializer with the following SerializerMethodField: def get_segments(self, obj): segments = models.Segment.objects.filter(obj=obj) if segments: return SegmentSerializer(segments, many=True).data I'm trying to use drf_spectacular's extend_schema_field to annotate the return type. @extend_schema_field(SegmentSerializer), is close, but my function can also return None, so I want to do something like @extend_schema_field(SegmentSerializer | None), which doesn't work. Is there a way to use a serializer type in extend_schema_field while marking it as nullable? -
Unique Constraint Failed: Authentication_authprofile.user_id, Anyone to help me
Am creating a user profile with custom model Fields. But am getting an error if l try to submit The form. UNIQUE constraint failed: Authentication_authprofile.user_id Am not seeing any error in my Code but anyone to help me and solve it. views.py def userprofile(request): url= request.META.get('HTTP_REFERER') if request.method == 'POST': user_profile = AuthProfile() if AuthProfile.objects.filter(user_id=request.user.id).exists(): avatar = request.POST.get('avatar') gender = request.POST.get('gender') country = request.POST.get('country') user_profile.avatar = avatar user_profile.gender = gender user_profile.country=country user_profile.user_id=request.user.id user_profile.save() return redirect('/') return render(request, 'authentification/auth-policy/user-dashboard.html') Models.py class AuthProfile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, unique=True) avatar=models.ImageField(default='avatar.jpg',upload_to='profile_avatar') gender =models.CharField(max_length=10, blank=True, null=True) country=models.CharField(max_length=50, blank=True, null=True) def __str__(self) -> str: return f'{self.user.username} Profile' @receiver(post_save, sender=User) def create_auth_profile(sender, instance, created, **kwargs): if created: AuthProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_auth_profile(sender, instance, **kwargs): instance.authprofile.save() l also attached a picture for error if I try to submit the form. [] The problem is that l can't update the user profile. anyone to help me -
i receive "TypeError: NetworkError when attempting to fetch resource." message while trying to fetch django server with "PUT" method
My fetch function const savePost = () => { fetch(`http://127.0.0.1:8000/api/posts/${id}/edit`, { method: "PUT", mode: 'cors', headers: { "withCredentials": "true", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", 'Access-Control-Allow-Headers': '*', "Access-Control-Request-Method": "PUT", 'Accept': 'application/json', }, body: JSON.stringify(post) }).catch(error => console.log(error)) In DJANGO settings.py INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['*'] I've already put CORS into my django settings.py and looked for a while to find how to solve this, but nothing helped. The main things i did is adding headers to fetch request and adding more CORS settings to django settings.py I don't know how to fix this error, if you could help me, I would really appreciate this -
The update on the address field isn't working
I'm working on a Python/Django project. In the update view, I'm encountering a very specific issue: When I try to update the bank_account field, the system updates it without any problems. However, when I attempt to update the address field, the address doesn't get updated. Here's the code: class DeveloperUpdateView(LoginRequiredMixin, UpdateView): model = Developer form_class = DeveloperForm template_name = 'developer/developer_form.html' success_url = reverse_lazy('backoffice:developer-list') def post(self, request, *args, **kwargs): object = Developer.objects.get(id=kwargs['pk']) developer_form = DeveloperForm( data=request.POST, instance=object, prefix='developer' ) bank_account_form = developer_bank_account_formset(data=request.POST) address_form = developer_address_formset(data=request.POST) if developer_form.is_valid(): developer = developer_form.save() if ( bank_account_form.has_changed() and bank_account_form.is_valid() ): existing_bank_accounts = DeveloperBankAccount.objects.filter( developer=developer ) if existing_bank_accounts.exists(): existing_bank_accounts = existing_bank_accounts.first() existing_bank_accounts.delete() bank_accounts = bank_account_form.save(commit=False) for bank_account in bank_accounts: bank_account.developer = developer bank_account.save() if ( address_form.has_changed() and address_form.is_valid() ): existing_addresses = DeveloperAddress.objects.filter( developer=developer ) if existing_addresses.exists(): existing_addresses = existing_addresses.first() existing_addresses.delete() addresses = address_form.save(commit=False) for address in addresses: address.developer = developer address.save() else: return render( request, "developer/developer_form.html", { "form": developer_form, "bank_account_form": bank_account_form, "address_form": address_form, "action": "update", "error": True, }, ) return HttpResponseRedirect(reverse('backoffice:developer-list')) def get_context_data(self, **kwargs): context = super(DeveloperUpdateView, self).get_context_data( **kwargs ) context['form'] = DeveloperForm( instance=self.object, prefix='developer' ) bank_account_form = developer_bank_account_formset() address_form = developer_address_formset() try: queryset = DeveloperAddress.objects.filter(id=self.object.address.id) address_form = developer_address_formset(queryset=queryset) address_form.extra = 0 except DeveloperAddress.DoesNotExist: address_form.queryset = … -
Django Haystack index.remove_object not working
I cannot get index.remove_object to actually follow through with removing the object. They continue to appear in the index even after deleting them. I have tried via the signal processor as well as manually in the shell. I get no error messages, but the object still shows up via SearchQuerySet. Here is the relevant code: ### search_index.py ### class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) id = indexes.IntegerField(indexed=False, stored=True, model_attr='id') ### shell ### from haystack import connections from haystack.query import SearchQuerySet from .models import Book book_object = Book.objects.first() SearchQuerySet().filter(id=book_object.id).count() --> 1 index = connections['default'].get_unified_index().get_index(Book) index.remove_object(book_object, using='default') SearchQuerySet().filter(id=book_object.id).count() --> 1 book_object.delete() # RealTimeSignalProcessor fires here, confirmed via print statement, no errors SearchQuerySet().filter(id=book_object.id).count() --> 1 I can even add a print statement to the signalprocessor that shows the code is firing, but for some reason the index itself isn't updating. The object does disappear if I run rebuild_index, but I don't want to have to do that each time I delete something. index.update_object is working just fine, and new values are reflected in the index. But remove_object does not. Any thoughts? -
Django pymongo update_many ''Cannot use the part (y) of (x.y) to traverse the element ({x: []})'}'
I have a collection like this with sample documents as: [ { "_id": { "$oid": "64b28bafb2ea43dd940b920d" }, "title": "Village Libraries", "keywords": { "bn": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b28badb2ea43dd940b920b" } } ], "en": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b28aacb2ea43dd940b920a" } } ] } }, { "_id": { "$oid": "64b676b3b2ea43dd940b9230" }, "title": "Folk Tales", "keywords": { "bn": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b67683b2ea43dd940b922d" } } ], "en": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b676afb2ea43dd940b922e" } } ] } } ] I would like to run a multi update query on this collection (using Python (Django and pymongo)) like: db.collection.update({}, { "$pull": { "keywords.bn": { "$id": ObjectId("64b67683b2ea43dd940b922d") } } }, { "multi": true }) But running the update query: ... from pymongo import MongoClient ... print('q= '+str({'$pull': {'keywords.bn': {'$id': meta_bid}}})) # OUTPUT: q= {'$pull': {'keywords.bn': {'$id': ObjectId('64b67683b2ea43dd940b922d')}}} y= ent_col.update_many({}, {'$pull': {'keywords.bn': {'$id' : meta_bid}}}) results in the following error: full error: {'index': 0, 'code': 28, 'errmsg': 'Cannot use the part (bn) of (keywords.bn) to traverse the element ({keywords: []})'} I have tested the query in Mongo Playground (link) and it works fine there. So what am I doing wrong? Thank you in advance for reading … -
What are the recommended settings in a Django project that uses firebase as the database?
What are the recommended procedures if my Django project uses firebase-google as the main database? It is relatively simple to import data from firebase, however Django is already configured for sqlite, is it necessary to make any changes related to this? Currently I only import firebase libraries and configuration files according to documentation, but I don't do makemigrations for example. Although the project works, I would like to understand the implications of working this way. -
How to test dependent Django API endpoints in isolation?
I'm working on a Django project with two API endpoints that operate in tandem. Here's the flow: The first API endpoint modifies some data, or maybe creates new records, and then it returns certain information. This returned information from the first API is then used as input to call the second API endpoint. I've been able to write a test for the first API endpoint without any issues. However, when it comes to the second API endpoint, I'm at a crossroads: Should I call the first API within the test of the second API to get the required information? (This feels like it's breaking the isolation principle of testing.) Or, should I replicate the state or environment using fixtures/mocks so that I can directly test the second API without the actual call to the first API? I'd appreciate insights on the best practices for this scenario. Is there a standard or recommended way of handling such situations in Django testing? -
Python web development
May I know what utility or package should I use to get web analytics of web site just like shopify. I would like to see which categories, products and blogs are being read more or clicked more. How much is the time spent by each person on those links ? Steps to achieve that functionality -
Django database-dependent one-time initialization
In my Django app, I have a routing.py helper module with a get_route function that is used by my app. Before I can call this function, I need to build a graph network, which is slow (seconds), so I want to do this once instead of on every get_route call. I build my graph network based on data in my database, so I need to access models (read-only) during this initialization. This question is similar but as pointed out there, the accepted answer is wrong, since it relies on django's AppConfig.ready(), but as is pointed out in the docs, if you make database queries in there, they will access your production database instead of your test database when running tests. Is there a way to do one-time initialization after Django has loaded the database? -
I want to display user image on my index.html {{ user.UserProfileInfo.profile_pic.url }}
Here is my models.py and here is how i tried to use it in my index.html I'm ready and willing to upload any other snippet of my code if needed. any help will be greatly appreciated thanks in advance I'm trying to display the user's image on my index.html template -
Dockerized django taking long time for build the docker-compose
I'm running a dockerized Django application: only Django + Postgres on local. When I start the application and go to any localhost URL, it takes up to 20-30 minutes to build. Here is my dockerfile: FROM python:3-alpine LABEL maintainer="joyalcs2@gmail.com" ENV PYTHONUNBUFFERED=1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Here is my docker-compose.yml: version: "3.11" services: app: build: context: . args: - DEV=true ports: - "8000:8000" image: app:django container_name: rest_container volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" requirements.txt: Django == 4.2.4 djangorestframework == 3.14.0 psycopg2 == 2.9.7 drf_spectacular == 0.26.4 I tried many times and i changed the image many time .but it takes so much time.Also, i used -
Submit a form with Fetch to a Django View
I'm a beginner trying to figure how to use both Django and Fetch api. I was trying to follow this question Django - taking values from POST request, JavaScript fetch API To figure out how to POST a form to a Django view, and access the data from the view. I'm not sure if my header has an issue. my html form <form class="basicform"> <label for="nametextbox">Change First Name</label> <input type="text" name="nametextbox"> </form>` My fetch POST request function postForm(id, form){ var formData = new FormData (form); let response = fetch("{% url 'fetch-ppl' '12345' %}".replace('12345',id), { method: 'POST', body: formData, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "X-CSRFToken": getCookie("csrftoken") }, }) .then(response => response.json()) .then(data=>{ console.log(data); }) return 'Post Done'; } My POST view, that I'm trying to send the form data to def post_form_rest(request, pk): ppl = PersonalData.objects.get(id=pk) serializer = PersonalDataSerializer(ppl,many=False) if (request.POST): print("It's a Post Request") print(request.POST); data = ["post request done"] return JsonResponse(data) return JsonResponse(serializer.data) My problem is when I send my POST request, the django view doesn't detect any POST data at all, it just skips to the end where it gives me a json response of the initial model object. (I don't get any print statements … -
Kubernetes: Secrets update but server not rolling out with new env values
I've a Kubernetes cluster running Django on DEBUG=True using ConfigMap and some other secrets using K8's secrets. The problem I'm having is that even if I rollout the server it keeps having debug true values, and when I inspect the container, the env shows that it's in False. Any idea why this is happening, and how to solve it? -
Django shows Internal Server Error in Production while uploading images
My django application shows internal server error when I try to upload images in the production server when I turn the debug = False and it works well when debug = True. I'm using django-imagekit for processing the images. I'm using Whitenoise to server my media and static files. Here is my code: setting.py STATIC_URL = '/static/' MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py image = ProcessedImageField(upload_to='authors', format='JPEG', options={'quality': 60}) I hosted the site on Vercel -
Django Grappelli 3.0.7 radio_fields admin.HORIZONTAL not working
Upgraded to Grappelli 3.0.7 with Django 4.0.10 and radio fields are stacking vertically even though specified as radio_fields = {'show_weekends': admin.HORIZONTAL, 'group_by_dept': admin.HORIZONTAL} If I comment out Grappelli in INSTALLED_APPS, they work properly so it's not a Django issue -
Migrations in FastAPI libs?
In Django it is quite convenient that 3d party libs could store their own models and migrations. F.e. django-celery-beat - it has functionality which require database table. It is also convenient to have single settings object from which 3d party libs could get necessary settings. But what about FastAPI? How 3d party lib could say a user which settings it needs? How to provide a user functionality which requires a database table? -
Why CSS works with "python manage.py runserver" but not with Gunicorn?
When I run, from the command line, python manage.py runserver mywebsite.com:8099 the css works fine. But when I use the systemd service with Gunicorn socket, the app works but without the css. Even if I use the following command: gunicorn demo.wsgi:application, the app works fine but without the css. Excerpt from my settings.py: STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "mystaticfiles" ] Excerpt from my nginx config file: location /static/ { root /root/djdeploy/demo/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } My Django project working directory is: /root/djdeploy/demo/, I have put my css files in the following folder: /root/djdeploy/demo/mystaticfiles -
Error Django - SQL Server near "EXEC": syntax error
I have a problem calling Stored Procedured in Django, can you please help, below is the error: My funtion view def homeKTA(request): cursor = connection.cursor() try: cursor.execute("EXEC dbo.processos") result = cursor.fetchall() finally: cursor.close() return render(request, "homeRCKTA.html", result) yes that's exactly what is expected -
Revoke/replace Celery tasks under certain conditions
Let's say I've got a class Foo and a function which can be called like that: calculate(foo, dt) (the first argument is an instance of Foo, the second a datetime.datetime instance). Also, calculate updates various things related to foo in a database, calculate is decorated with @transaction.atomic to avoid reaching an inconsistent state in case of issue, behind calculate lies a recurrence relation, running it is computationally expensive, this is one of the reasons why it's called through a Celery task, when dateX > dateY, running calculate(foo, dateX) is pointless if you know you'll have to run calculate(foo, dateY) anyway, because the set of values updated by calculate(foo, dateX) is included in the set of values updated by calculate(foo, dateY). Now, how to run calculate as often as necessary without unnecessary calculations? In other terms, I think I'm looking for a function schedule_calc, taking 2 arguments foo and dt (like calculate), also matching the following requirements: when there isn't any task related to foo, a new one is created which will eventually run calculate(foo, dt), when there is such a task which will eventually run calculate(foo, date1), let's call it T1, several possible outcomes: if date1 <= dt and T1 … -
How to upload mutiple images in the django admin
It involves uploading multiple images to the django admin and the only one should show in the listings.html , and then in that instance post the other images should display there . I have done majority of the work to ensure the post is saved. Please bear in mind that i use an html page (pro.html) where i have the form my users will input whatever they want to post . Once the post in submited , it is automatically saved in the django admin . Amongst the form i require 8 images . The thing now is, if i upload 8 images it is going to save 8 times instead of once. This is my views.py from django.conf import settings from django.conf.urls.static import static from .forms import PostForm from django.shortcuts import render, get_object_or_404 from .models import Post, PostImage from django.http import HttpResponse # Create your views here. def post_create(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() for file in request.FILES.getlist('image'): image = Image(image=file) image.save() else: form = PostForm() return render(request, 'estateapp/pro.html', {'form': form}) def home(request): return render(request, 'estateapp/home.html') def Listings(request): posts = [] for post in Post.objects.all(): post = { 'title': post.title, … -
Django Management Command Triggers URLs When Checking Database Connection
I've encountered an unexpected behavior while working on a Django project involving a custom management command. The command I've created, named wait_for_db, is intended to test whether the database connection is ready before proceeding with other tasks. However, when I trigger this command using python manage.py wait_for_db, it seems to be invoking some URLs, leading to database-related errors. I've structured the management command to primarily check the database connection's readiness without interacting with URLs or the web server. The goal is to ensure that the database is available before proceeding with other operations. Here's a simplified version of my management command: """ Django command to wait for the database to be available. """ import time from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to wait for database.""" def handle(self, *args, **options): """Entrypoint for command.""" self.stdout.write('Waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except (Psycopg2OpError, OperationalError): self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) Despite my best efforts, when I execute python manage.py wait_for_db, it seems to trigger some URLs or components that access the database. As a result, I receive errors indicating that …