Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Really weird: CKEditor "PDF file" uploads become an IMAGE of page one
When my forum users attempt to attach "PDF" documents to their posts, using CKEditor, what winds up happening is that an =image file= is instead attached, consisting of a JPG image of page-one. I have utterly no idea why such a thing is happening . . . -
Docker container not finding manage.py using DRF
I have been trying to containerise a project of mine that uses postgresql. But for some reason it is unable to perform the commands completely, when I check the web container, by following it on docker-desktop I can see that it is performing the migrations but at some point it stops and gives me the following error: 2023-01-17 19:51:29 Apply all migrations: admin, auth, company, contenttypes, oauth2_provider, product, sessions, social_django, users, warehouse 2023-01-17 19:51:29 Running migrations: 2023-01-17 19:51:29 No migrations to apply. 2023-01-17 19:51:29 sh: manage.py: not found For some reason it does not see manage.py. When I run docker-compose run web sh and when I check if manage.py exists in the directory using ls in the CLI I discover it is there. What could I be doing wrong here? The Dockerfile: # pull official base image FROM python:3.9-alpine # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install python dependencies RUN apk add -u zlib-dev jpeg-dev libffi-dev gcc musl-dev RUN python3 -m pip install --upgrade pip COPY requirements.txt /app/requirements.txt RUN pip install --no-cache-dir -r requirements.txt # … -
Attibutes are 'disappearing' from CBV. Django
I am trying to build CBV with class View parent. This view takes slug of object and find that object between two django models. The functions from services.py was doing a lot of DB queries, so, I tried to reduce them by giving to FeedbackSection necessary attributes(slug, model_instance and context) and lately override them in get method. class FeedbackSection(View): """ Feedback section for different objects. This is something like 'generic' view, so I implement it that it will find the model and feedbacks for this model by having only slug. """ template_name = 'feedbacks/feedback-section.html' form_class = CreateFeedbackForm slug = None model_instance = None context = None def get(self, request, *args, **kwargs): self.slug = kwargs.get('slug') self.model_instance = get_model_instance(self.slug) self.context = get_feedback_section_context(self.slug, self.form_class, self.model_instance) return render(request, self.template_name, self.context) @method_decorator(login_required) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # will create feedback object and update model[Advert, Company] rating. end_feedback_post_logic(self.request.user, form, self.model_instance) return render(request, self.template_name, self.context) The attributes(slug, model_instance and context), when post method is in runtime is equivalent to None. The problem is that this implementation was working fine yesterday, but today it's not. I know I can use my functions again, but in post method. I don't want to do … -
Can the "super-user" assign a "common password" to a user, regardless?
I would think that the "super user" should be entitled to assign any password to another user that they wants to assign, whether or not it is "common." But the software does not seem to agree. Is there any way to allow a "super user" to impose such an override, if they please? -
How to place inline formsets form fields manually in Django templates and I want to show only specific fields in Template forms
We need to place form fields in specific x,y location and field size as per the layout provided in the attached image manually in a bootstrap template page, below are our models.py & forms.py code models.py: from django.db import models from django.utils import timezone from datetime import datetime def generateNewEmpID(): today = datetime.now() YearMonthDay = today.strftime("%Y%m%d") newEmpIdPrefix = 'NT' + YearMonthDay try: last_employee_id = Employee.objects.all().last().employee_id # Eg : NT2018012710001 except AttributeError: last_employee_id = None if not last_employee_id: newEmpID = str(newEmpIdPrefix) + '10001' return newEmpID else: if last_employee_id[:10] == newEmpIdPrefix: oldEmpID_int = last_employee_id[11:] newEmpIDSuffix = int(oldEmpID_int) + 1 newEmpID = newEmpIdPrefix + str(newEmpIDSuffix).zfill(5) return newEmpID else: newEmpID = str(newEmpIdPrefix) + '10001' return newEmpID class Employee(models.Model): employee_id = models.IntegerField(max_length=30, default=generateNewEmpID, primary_key=True) first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) account = models.CharField(max_length=100, blank=False, null=False) designation = models.CharField(max_length=30, blank=False, null=False) mail_id = models.CharField(max_length=100, blank=False, null=False) photo = models.ImageField(blank=True, upload_to='employee/photos') mobile_no = models.IntegerField(max_length=10) phone_no = models.CharField(max_length=100, blank=True, null=True) address = models.CharField(max_length=100) date_of_join = models.DateField(default=datetime.date()) ctc_pa = models.IntegerField(max_length=10) pan_no = models.CharField(max_length=10) epfno = models.CharField(max_length=20) bank = models.CharField(max_length=100) bank_account = models.CharField(max_length=30) bank_ifsc = models.CharField(max_length=15) emergency_contact = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) class Meta: managed = False db_table = 'employee' class dependents(models.Model): employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE) … -
django forms.ChoiceField random choices
in the Forms I add a field with the parameter login = forms.ChoiceField(choices=gen_login()) When using gen_login(), a list is generated and the values do not change randomly during the subsequent page refresh. If you use gen_login, the list is updated when the page is refreshed, but it does not pass validation def gen_login(): return map(lambda x: (x, x), [(''.join(random.choices(string.ascii_uppercase, k=2)) + '_') for i in range(6)]) -
Remove "username" from Django CustomUser model
Python 3.11 & Django 4.1.5`. I extended Django's user model. Works fine. I then went to remove the username field in order to login with email. Works fine except for one part. In Django admin I can view users, edit users. I can even create new users via the terminal. But if I try create a new user in the Django admin I get the following error... "Key 'username' not found in 'CustomUserForm'. Choices are: password1, password2." My User model code is.... models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return str(self.pk) managers.py from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Users require an email field') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, … -
Django how to rebuild reference to get value?
I want to generate an email with dynamic fields. The basic idea is to replace reserved words in email content with a value from the database. I have a model User with the following fields: class User(models.Model): full_name = models.CharField(max_length=254) age = models.IntegerField(max_length=254) email = models.EmailField(max_length=254) note = models.TextField(max_length=254) And I created another model Templates where I store the email template: class Templates(models.Model): template_name = models.CharField(max_length=255) template_content = RichTextField(blank=True, null=True) As you can see, the email template stores in the RichTextField and have look like this: Hello ${object.full_name} This is your email: ${object.email} At the backend I have a POST function which supposes to replace all ${object.whatever} with the relevant field, but I do not understand how can I explain to the program what I need without hardcoding all existing model fields. def replace_email_content(request): if request.method == 'POST': chosen_id = request.POST.get('choosen_id', None) content = request.POST.get('content',None) user = User.objects.get(id=chosen_id) # ...Some REGEX here to find all places where value should be inserted list_of_found_words = ['${object.full_name}','${object.email}'] for word in list_of_found_words: # HERE code to generate link ${object. WHATEVERNAME_from_model} -> user.WHATEVERNAME_from_model new_content = content.replace(word,GENERATED_LINK) How can I generate this link? -
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?