Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
To get total price of all the items in cart django
I am working on a project where everything works out so aside some litle part of code which has to return the total price of items in the cart, but it only returns the price of the first item in the cart. Here is the code, it does not add all the total in the loop models.py `def final_price(self): total = 0 for order_item in self.items.all(): total += order_item.get_total_price() return total` -
How does Django authentication system works with AbstractUser model
Now I am writing a site on Django and I need to use the AbstractUser model to register and authorize users on the site, but I do not fully understand why when I use the authenticate function, it returns None instead of returning a user. Registration works perfectly for me. Users are also successfully added to the database, and are successfully found when searching by email Here is my models.py file class JobseekerRegisterInfo(AbstractUser): username = first_name = last_name = None id = models.BigAutoField(primary_key=True) phone_number = PhoneNumberField() email = models.EmailField(unique=True) full_name = models.CharField(max_length=120) password = models.CharField(max_length=150) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['phone_number', 'full_name', 'password'] def __str__(self): return self.full_name I also added in settings.py AUTH_USER_MODEL variable AUTH_USER_MODEL = 'jobseeker.JobseekerRegisterInfo' Here is my register and login forms in forms.py file class JobseekerRegisterForm(forms.Form): class Meta: model = JobseekerRegisterInfo fields = ('full_name', 'phone_number', 'email', 'password') full_name = forms.CharField(label="Ваше прізвище та ім'я", max_length=255, min_length=6, widget=forms.TextInput(attrs={'class': 'form-control'})) phone_number = PhoneNumberField(label="Ваш номер телефону(буде потрібна SMS-верифікація)", region='UA', initial=380, widget=forms.NumberInput(attrs={'class': 'form-control'})) email = forms.EmailField(label='Ваш Email', widget=forms.EmailInput(attrs={'class': 'form-control'})) password = forms.CharField(label='Придумайте пароль', min_length=6, widget=forms.PasswordInput(attrs={'class': 'form-control'})) password_repeat = forms.CharField(label='Повторіть пароль', min_length=6, widget=forms.PasswordInput(attrs={'class': 'form-control'})) captcha = CaptchaField(label='Введіть літери з картинки') def clean_password(self): password = self.cleaned_data['password'] if all([i.isdigit() for i in … -
Cant get URL,s in urls.py to work on DJANGO project
This is the urls.py file for the main site in my Django project. Ive got a category table and a country table linked to a product table and I cant get all the urls in the code below working. If i put the category_detail url in the list just after the slug:category_slug>/slug:slug/', product_detail url those urls work and country_detail links dont. If i put the country_detail urls after the slug:category-slug>/slug:slug/', product_detail url then only the country_detail url works. Any help appreciated from django.contrib import admin from django.urls import path from core.views import frontpage from store.views import product_detail, category_detail,country_detail urlpatterns = [ path('', frontpage, name='frontpage'), path('admin/', admin.site.urls), path('<slug:category_slug>/<slug:slug>/', product_detail, name='product_detail'), path('<slug:slug>/', country_detail, name='country_detail'), path('<slug:slug>/', category_detail, name='category_detail'),``` -
Django: objects.all() exclude linked models
I have different models in Django linked together: Projects Fonts (linked by project_id) Images (linked by project_id) etc When I'm using Project.objects.all() it retrieves all of the information from all the linked tables and query gets very slow. However in specific view I do not even need i.e. Fonts and Images. How can I tell django to skip these models while performing query? -
My local API 127.0.0.1:8000 doesn't work with docker
I have simple django project with one html page and I try to deploy it with docker. My Dockerfile you can see below: FROM python:3.10.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I run my image with next command: docker run -p 8000:8000 --rm 751aa7a2d66f But when I open my browser the localhost with API 127.0.0.1:8000 doesn't work. In the same time I run command docker ps and it shows the following: docker ps result What's the problem? Thanks in advance for your help. For your information I work on windows 7. I tried to run docker run -p 127.0.0.1:8000:8000 --rm 751aa7a2d66f but it didn't help. I also tried to change port of my local machine to 8001 with the same result. -
How to display an uploaded image in "Change" page in Django Admin?
I'm trying to display an uploaded image in "Change" page in Django Admin but I cannot do it as shown below: This is my code below: # "models.py" from django.db import models class Product(models.Model): name = models.CharField(max_length=50) price = models.DecimalField(decimal_places=2, max_digits=5) image = models.ImageField() def __str__(self): return self.name # "admin.py" from django.contrib import admin from .models import Product @admin.register(Product) class ProductAdmin(admin.ModelAdmin): pass So, how can I display an uploaded image in "Change" page in Django Admin? -
Django Pagination Getting 414 Error When Form Data Exceeds URI Limit
I'm supporting an app on an older version of Django (2.1.14) and I've run into a situation where I'm seeing 414 errors when attempting to navigate pages of querysets. I believe the paginator is sending all of the filled in form fields through the URL, which is too long. The page contains fields for performing a search, which is returned as rows in a table that contains some controls. If enough data is filled into these controls, then the requests from the paginator will fail with the 414 (URI is too long) error. Pagination works as expected when less form data is used. I am coming up empty on finding a solution, but can I change the behavior of Django's paginator to use a post instead or ignore some of the fields when using pagination to navigate through the data? Upgrading the Django version is an option, but would prefer to avoid at this time. Also the error doesn't display for the user and they just get the impression that the page is stuck. Likely more configuration for this is needed, but handling these errors beyond the writing to the console would be nice. -
Does Django Admin support an "Are you sure you want to do that" popup when a user is saving a new record?
I have an admin page that allows a user to make "usual" and and some "unusual" changes. The "unusual" would be setting a field on the model to None. I could check for this in ModelAdmin.save_model but I'd like to check the user is happy with what they're doing. Is there a standard way of notifying the user that they're doing something a bit funky and checking whether or not they definitely want to proceed? Ideally without custom html and redirects. -
Issue Heroku deployment message , is there a way to either downgrade Python version or ajust pywin32 package?
I have an issue deploying on Heroku. I have the following issue where Either python should be downgraded or Pywin32 is not in the correct version. Please check below the response of the Heroku deployment error: ERROR: Ignored the following versions that require a different python version: 4.4.0 Requires-Python >=3.6,<3.9 ERROR: Could not find a version that satisfies the requirement pywin32==301 (from versions: none) ERROR: No matching distribution found for pywin32==301 ! Push rejected, failed to compile Python app. ! Push failed I have as runtime.txt : python-3.10.4 My requirements.txt pywin32==301 Should I downgrade Python or Should I do something else with the packages? Also is there an easier platform / free server to put live my Django website? -
Django package to display a horizontal bar of images with left/right scrolling
All right, I know that the Django package I'm looking for already exists, somewhere in "djangopackages," I just don't know the right terms to use to look for my choices. The effect that I want is a horizontal bar, with left/right scroll buttons, which shows a set of image thumbnails in rotation. I'm quite certain that this "has been done to death," but I haven't stumbled on it yet. Therefore, to save myself a bit of time, I thought I'd simply ask the community ... what search term or category should I use on "djangopackages.com?" I'm not trying to manipulate the images – as in actually "rotating" them ... but, "what is this actually 'called?'" -
How often am I allowed to contact PayPal API?
Right now I contact the PayPal API to check the subscription status everytime the user enters the profile settings, and each time a new access token is generated. Is this considered a bad practice in production? Should I rather set a timer for 24 hours and check the subscription status only once a day to reduce the load on PayPal's end? Does this even matter? And would it be better to somehow store a new access token in the .env everytime it expires (PayPal gives the duration)? I just want to know if there are any limitations since [https://developer.paypal.com/api/rest/reference/rate-limiting/][1] does not give any specific numbers. -
How to annotate list and use this field in filter? Django ORM
I am annotate array: queryset = queryset.annotate( owner_names=ArrayAgg( Case( When( debtor__estateobjectcharacteristics__owner_name__isnull=False, then='debtor__estateobjectcharacteristics__owner_name', ) ) ) ) and in field owner_names contains something like ['Name1', 'Name2'] and that what im actually need. But after this i try to filter: queryset.filter( Exists( DebtorTenantProfile.objects.filter( debtor_id=OuterRef('debtor_id'), full_name__in=F('owner_names') ) ) ) and i get error ProgrammingError: syntax error at or near "ARRAY_AGG" i was tried to add output_field=ArrayField(CharField(max_length=255, blank=True, null=True)) (just in case imao) but i have the same error. Is this possible to make this queries work? because this is exactly what i need. Or maybe is there another way to annotate list of names and use this in filter? I would really appreciate for any suggestions or solutions ;) DB: PostgreSQL -
Filter queryset for many-to-many field for any foreign item matching specific criteria
I have 2 models: class BackupItems(models.Model): name = models.CharField(max_length=100) class CloudObjects(models.Model): creation_time = models.DateTimeField() removed_date = models.DateTimeField() item = models.ManyToManyField(BackupItems, db_table='cloud_object_items') This is holding data for some backup operations. CloudObject is a table with information when item was created and when it was deleted. For legacy issues, removed date is hardcoded as 2099-12-31 for all new entries. Once it's deleted, this date is substitute with real date. In the views I have simply query, where I list all items from BackupItems. BackupItems.objects.all() Now, I'd like to list only those BackupItems which have any CloudObjects in the future ( removed_date = 2099-21-31). I dont care what is that given item, if this CloudObject for given BackupItem exists in the future, it's fine for me. I don't want to see any item in queryset, where there are no CloudObjects in future for given BackupItem. How to crate this kind of view? -
How to increment and decrement a session counter in django on session start and expiry
def post(request,...): ... notify_counts = request.session.get('notify_counts') if notify_counts is None: request.session['notify_counts'] = 1 else: request.session['notify_counts'] +=1 How to decrement the session counter on session expiry? -
Django Rest Framework serializers.DictField constraint on possible keys
I have a REST API output that looks like this: { "something": "xyz" "something_dict" { "a": 10, "b": 20, "c": 30 } } I'm trying to create a serializer for that (mostly for automatic documentation generation purposes, but I believe that doesn't really matter), and for the something_dict field I thought it could be a good idea to use serializers.DictField. The problem is, the keys that can show up in the dictionary are limited to a certain set (values of an enum type), but I can't seem to find a good way to define it. Something like serializers.DictField(key=serializers.ChoiceField(choices=[enum.value for enum in Enum])) would be great but that's obviously not available. The only reasonable way to specify this is to use a nested serializer: class SomethingDict(serializers.Serializer): a = serializers.IntField(required=False) b = serializers.IntField(required=False) c = serializers.IntField(required=False) But that's slightly inconvenient as the set of available keys is potentially dynamic (values of an enum, as mentioned previously). The question is then: Is it possible to specify possible values for serializer.DictField keys or is there any way around it to make it dynamic? (I'd like to avoid defining the class in dynamic way, if possible) -
Rest Framework nested serializer and many = True
I got these serializers: class OptionSerializer(serializers.Serializer): label = serializers.CharField(max_length='100') percent = serializers.CharField(max_length='3') class RowSerializer(serializers.Serializer): (...) options = OptionSerializer(many=True) price = PriceSerializer() I can't find a way to serialize a row with few items as following. options = [{'label': 'option 1', 'percent': '2'}, {'label': 'option 2', 'percent': '2'}] rs = RowSerializer(data={'options': OptionSerializer(options, many=True).data}) Running rs.is_valid() throws TypeError: '>' not supported between instances of 'int' and 'str' Any idea about what am I doing wrong? -
Create a conditional prefetch_related/select_related with Django querysets
I want to only execute a prefect_related on my queryset when a boolean value in my database is True. I have the following models: from django.db import models class Map(models.Model): has_ratings = models.BooleanField() class Place(models.Model): name = models.CharField() map = models.ForeignKey(Map, on_delete=models.CASCADE) ... class Rating(models.Model): rating = models.IntegerField() place = models.ForeignKey(place, on_delete=models.CASCADE) ... Not every map has the rating functionality turned on. Therefore I only want to conditionally fetch the ratings and prevent the extra query to the Rating table for maps without ratings. The query below always queries the Rating table. Place.objects.all().prefetch_related( Prefetch( "ratings", queryset=Rating.objects.all(), to_attr="rating_list", ) ) So I tried to add a filter: Place.objects.all().prefetch_related( Prefetch( "ratings", queryset=Rating.objects.all(), to_attr="rating_list", ) ).filter(Q(map__has_rating=True)) This doesn't work because it filters all places for a Map with has_rating=False. Is this doable without loading the map in memory? How can I can I make the prefetch optional based on a database value with Dango querysets? -
Correct way to use dynamic imports in Vite + Vue
We have an app where we've been using a dynamic import syntax in our route definitions, like so: ... component: () => import('./components/SomeComponent'), We recently transitioned to vite, and since the switch, we've been catching TypeError: Failed to fetch dynamically imported module whenever we deploy a new version of the app. According to this SO post, this is happening because the hash for the files are invalidated on new deploys, but why are the files still being referenced with the previous hashes, when we are shipping a new build altogether? I also found a previous issue that ran into the same error, and found this link in its thread that talked about how rollup expects a specific syntax for dynamic imports: // current component: () => import('./components/SomeComponent') // expected? component: () => import('./components/SomeComponent.vue') Could this be why we are getting that Failed to fetch dynamically... error? Because my dynamic imports are missing the file extensions? I am a little confused, because the dynamic imports seem to still work even without the file extensions, it's just that we are catching errors on fresh deploys. -
django set image delete old reference and prevent delete default
despite of many mordern website employ an OSS for serving image, I still want to build a backend to manage small thumbnails locally. however, django image field is a bit tricky. there are three views I may change image reference: models.py views.py forms.py I used to do it simply by: forms.py request.user.profile.image = self.files['image'] and I always have a default models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = ProcessedImageField( default='profile/default.jpg', upload_to='profile', processors=[ResizeToFill(*THUMBNAIL_SIZE)], format='JPEG', options={'quality': THUMBNAIL_QUALITY}, ) After a lot of testing, I found that it always result in an issue, can be among: default image file get deleted. if the image has been set before, it holds an value that is not the default, when I reset it, the old referenced file is not deleted and will occupy disk storage. to do it perfectly, I decided to write a global function for import, whenever I want to set an image, call it from django.conf import settings def setImage(instance, attr, file): """ instance will be saved """ if file: ifield = getattr(instance, attr) # old reference, can be default iurl = ifield.url # default durl = settings.MEDIA_URL + instance._meta.get_field(attr).get_default() if iurl != durl: # old reference is not default # … -
Implement multiple filters with django_filters
So I'm currently working on an app and I'm having some problems with using multiple filters in the same function. I have a SortFilter which works. This is a dropdown menu from which you can sort on price for instance. Now I'm also trying to implement a checkbox filter where you can filter on all the brands found in the 'brand' attribute of the model. But if a user has selected a filter from the dropdown menu I still want this filter selected when using the checkbox filter. How can I do this? My code looks like this: filter.py: class SortFilter(django_filters.FilterSet): ORDER_BY_CHOICES = ( ('-discount_sort', 'Hoogste korting'), ('-new_price', 'Hoogste prijs'), ('new_price', 'Laagste prijs'), ) order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES, method='filter_by_order') class Meta: model = Product fields = [] def filter_by_order(self, queryset, name, value): return queryset.order_by(value) class CheckboxFilter(django_filters.FilterSet): brand = django_filters.ChoiceFilter(choices=[]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['brand'].extra['choices'] = [ (brand, brand) for brand in Product.objects.values_list('brand', flat=True) ] class Meta: model = Product fields = ['brand'] .html (dropdown part): <form method="get" class="form-inline"> <select class="single-select" name="order_by" id="order_by" onchange="this.form.submit()"> <option>Sorteer op:</option> <option value="-discount_sort">Hoogste korting</option> <option value="new_price">Laagste prijs</option> <option value="-new_price">Hoogste prijs</option> </select> </form> desired .html for checkbox: <form method="get" class="form-inline" id="checkboxes"> <ul> <li><a href="#">Applied … -
Django problem with DeleteView deleting parent content
I have two models: a Project model and ProjectNotes. ProjectNotes are notes that are related to Projects. The ProjectNotes model has a project field that is a foreign key of the related Project. The problem I have is that when I delete a note on a project, the entire project is deleted. Only the note should be deleted. I think I have on_delete=models.cascade set up correctly on the ProjectNotes model. So I think the issue is with the view. The models: class ProjectManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = ( Q(title__icontains=query) | Q(description__icontains=query) # Q(slug__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups return qs def get_with_counted_notes_documents_todos(self): queryset = self.get_queryset().annotate( num_notes=Count('notes'), num_documents=Count('project_documents'), num_todos=Count('todo_group') ) return queryset class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) tags = tagulous.models.TagField(to=SiteWideTags, blank=True, related_name='projects_tags') objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) class ProjectNotesManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = ( Q(title__icontains=query) | Q(body__icontains=query) # Q(slug__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with … -
I am trying to convert a canvas element to a dataURL but the image is cut short
I'm trying to send an image of a hand taken with a live feed from a webcam to my backend to predict the hand gesture. HTML: <form method="POST" enctype="multipart/form-data"> <div id="videos"> <video class="video-player" id="user-1" autoplay playsinline></video> <canvas class="output_canvas" width="1280px" height="720px"></canvas> <canvas class="video-player" id="computer" autoplay playsinline></canvas> </div> </form> The js method I'm trying to use when pressed it should use mediapipe to draw lines on the hand, and as soon as it has recognized a hand send that image to the backend let playGame = async () => { const videoElement = document.getElementsByClassName('video-player')[0]; const canvasElement = document.getElementsByClassName('output_canvas')[0]; const canvasCtx = canvasElement.getContext('2d'); let screenshotSent = false; function onResults(results) { canvasCtx.save(); canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height); canvasCtx.drawImage( results.image, 0, 0, canvasElement.width, canvasElement.height); if (results.multiHandLandmarks) { for (const landmarks of results.multiHandLandmarks) { drawConnectors(canvasCtx, landmarks, HAND_CONNECTIONS, {color: '#00FF00', lineWidth: 5}); drawLandmarks(canvasCtx, landmarks, {color: '#FF0000', lineWidth: 2}); } if (!screenshotSent) { //Take a screenshot of the canvas and send it to the server to be processed let screenshot = canvasElement.toDataURL('image/png'); console.log(screenshot); let response = fetch('/play_game/' + game_id + '/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ screenshot: screenshot, }) }); screenshotSent = true; } } } const hands = new Hands({locateFile: (file) … -
MultiValueDictKeyError at /signin/
I am tryin to add an remember me option to my login page. Whenever i try logining and i click on the remember me option, everything works fine. When i do not click on it, it raises this error. Here is my forms.py class Signin(forms.Form): username = forms.CharField( max_length=9, widget=forms.TextInput( attrs={ "id": "input_64", "name": "q64_typeA", "data-type": "input-textbox", "class": "form-textbox validate[required]", "data-defaultvalue": "", "size": "20", "placeholder": "180591001", "data-component": "textbox", "aria-labelledby": "label_64", "required": "", } ), ) password = forms.CharField( max_length=255, widget=forms.PasswordInput( attrs={ "id": "first_66", "name": "q66_name66[first]", "class": "form-textbox validate[required]", "data-defaultvalue": "", "autoComplete": "section-input_66 given-name", "size": "10", "data-component": "first", "aria-labelledby": "label_66 sublabel_66_first", "required": "", "placeholder": "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022", } ), ) remember = forms.BooleanField(required=False, initial=False) views.py def signin(request): if request.user.is_authenticated: return redirect(index) if request.method == "POST": form = Signin(request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] remember = request.POST["remember"] user = User.objects.filter(username=username).exists() if user: get_user = User.objects.filter(username=username) check_pass = check_password(password, get_user[0].password) if not check_pass: messages.error(request, "incorrect password") return redirect(signin) else: login(request, get_user[0]) if not remember: request.session.set_expiry(0) return redirect(index) else: messages.error(request, "Invalid User") return redirect(signin) else: form = Signin() return render(request, "accounts/login.html", {"form": form}) What i want to achieve is to make the remember me option not required. -
How to pass a tuple as a variable to render function in python/django? [closed]
I want to pass a tuple I decleared globally in views.py to a render function. But the categories.html does not see the tuple. views.py: `categories = ( ("0", ""), ("1", "electronics"), ("2", "books"), ("3", "clothes"), ("4", "instruments"), ("5", "other") )` def categories(request): return render(request, 'auctions/categories.html', { "categories":categories }) and categories.html looks like this: <ul> {% for category in categories %} <li>{{category.1}}</li> {% empty %} <li>No Items</li> {% endfor %} </ul> it just print No Items. How can I fix it? I wanted to print all categories -
Double GROUP BY in Django rest framework
I'm trying to do this query: SELECT * FROM series WHERE series.co_uni = 'SOME STRING' AND series.language = 'SOME STRING' AND series.visualization = 1 GROUP BY co_ind, no_ind; In DJANGO with filter result = Series.objects.filter(language = language, co_uni = co_uni, visualization = 1).values('co_ind', 'no_ind').annotate(ci=Count('co_ind'), ni=Count('no_ind')).order_by('co_ind', 'no_ind') Is it possible? I'm getting KeyError: "Got KeyError when attempting to get a value for field `year` on serializer `SeriesSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'year'."