Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use multiple forms in a single page in django
Hi i am pretty new to django. I am making a app for taking tiny notes. You can click on the texts (which is a django forms but it doesnt have the outlines) and edit them. I will make the submit form button appear when we change the content with javascript but for now lets leave it that way. With the "+" button you can add more Note instances. Now, the problem is when i want to edit the notes the only way i know is using forms, and when i do that i have to call another form for each Note instance...(i suppose). What i want on my website is, you can simply edit the content or title by clicking the text area, and submiting it(I can give https://trello.com as an example!). views.py def document_page(request, title): document = Document.objects.get(title=title) notes = document.notes.all() form = NoteForm(request.POST or None, request.FILES or None, instance=notes[0]) if form.is_valid(): form.save() return HttpResponseRedirect('/note/document/' + title) return render(request, 'note/document_page.html', {'document': document, 'notes': notes, 'form': form}) models.py class Note(models.Model): title = models.CharField(max_length=16, default='note-title') content = models.TextField(max_length=512, default='content') creation_date = models.DateTimeField(auto_now_add=True) document = models.ForeignKey(Document, on_delete=models.CASCADE, blank=True, null=True, related_name='notes') def __str__(self): return self.title forms.py class NoteForm(ModelForm): class Meta: model = … -
Frontend design tool espacially built for django
I want a frontend design tool built espacially for Django Tried webflow, but it is very inconvenient to download the designed template and then overwrite it so it works with your backend django apps. So I‘m searching for something which works well with Django -
What is the workflow for Stripe's Custom Payment?
I am currently developing a payment module for my django application and I am seeking assistance. Presently, my application uses Checkout Stripe for payment processing, but I find it limiting because it doesn't allow me to fully customize the checkout page according to my preferences. Additionally, I would like to keep the users on my website during the payment process. While exploring Stripe's documentation, I came across the "Custom Payment Flow" feature, which seems to be what I need. My desired flow is as follows: when a user clicks on the "Buy product" button, they should be redirected to a checkout page that I have customized using HTML. This checkout page will include product details, a form to collect personal information, and the Stripe payment form below. I understand that when the page loads, I need to update a variable called items using jQuery or JavaScript to populate it with the specific item or items the user intends to purchase. // The items the customer wants to buy const items = [{ id: "xl-tshirt" }]; However, I am unsure about how to handle the personal information that I will collect from the user. Could someone please provide guidance on how … -
How to handle multiple `GET` query parameters and their absence in Django ORM when filtering objects?
I'm currently building a blog, but this applies to a lot of projects. I have articles stored in Article model and have to retrieve them selectively as per the GET parameters. In this case, I want to return all the articles if the language GET query parameter is not supplied and only the specified language articles when the parameter is supplied. Currently I am doing the following: # articles/views.py @api_view(['GET', ]) def articles_view(request): """ Retrieves information about all published blog articles. """ language = request.GET.get('language') try: if language: articles = Article.objects.filter(published=True, language__iexact=language).order_by('-created_at') else: articles = Article.objects.filter(published=True).order_by('-created_at') # articles = Article.objects.first() except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ArticleSerializer(articles, many=True, exclude= ('content', 'author',)) data = serializer.data return Response(data) I feel this can be improved and condensed to a single Article.objects.filter(). The use of if for every query param seems inefficient. This is especially required since the articles will later also be retrieved via tags and categories along with language in the GET query parameters. With the expected condensed querying, there would be less if conditional checking and the freedom to include more query params. Can someone please help me with this? -
Django - multiple pages using one form
There's a number of questions regarding one page and handling multiple forms but I seem to have the reverse issue. I have two pages that contain datatables showing filtered data from my model, but both are the same source data and every object (in both tables, on both pages) has the same "edit" button bringing the user to the same form allowing them to edit the object details. My problem is redirecting from the form to the original page. I have tried using HttpResponseRedirect but that doesn't seem to be working, it goes to my homepage everytime. def edit_drawing(request, drawing_no): drawing = get_object_or_404(Drawings, pk=drawing_no) if request.method == "POST": form = DrawingForm(request.POST, instance=drawing) if form.is_valid(): form.save() messages.success(request, f'Drawing {drawing.drawing_no} was successfully updated.') return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: form = DrawingForm(instance=drawing) return render(request, 'edit_drawing.html', {'form': form, 'drawing': drawing}) I thought I could do something like this where my tag in the original html would tell the redirect where to go if I passed a variable: <a href="{% url 'schedule:edit_drawing' drawing_no=your_drawing_no %}?next={{ request.path }}">Edit Drawing</a> But when I try to use return redirect(next_url) in the view, next_url is undefined and doesn't work. Does anyone have a best practice to handle something like this? I … -
Django migration error: Applying migrations throws an error, and querying 'flight.objects.all()' results in an error as well
I'm facing an issue with my Django project where I encounter errors when trying to apply migrations using python manage.py migrate and when executing flight.objects.all(). Here's the code: from django.db import models # Create your models here. class Flight(models.Model): origin = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="departure") destination = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="arrival") duration = models.IntegerField() def __str__(self): return f"{self.origin} to {self.destination}" class Airport(models.Model): city = models.CharField(max_length=64) code = models.CharField(max_length=3) def __str__(self): return f"{self.city} ({self.code})" The Flight table previously had two Character fields instead of foreign keys and I had stored a row in it but later I decided use Airport table as a foreign key in Flight table. However after I exited the shell and tried to run "python manage.py migrate" I got an error: django.db.utils.IntegrityError: The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'Kathmandu' that does not have a corresponding value in flights_airport.id. I figured it might be because of the previously stored data in the Flight table so i tried to delete it, however i cant even view the contents of the Flight table. Whenever i try running "flight.object.all()" i get another error: django.db.utils.OperationalError: no such column: flights_flight.origin_id Can anyone help … -
Django user.set_password(password) is not hashing the password
I have wrote Custom user Model in Django everything is working fine except password is not being hashed when but when I had created the superuser password was hashed here are my models for custom user and custom user manager model.py() class CustomUser(AbstractUser): email = models.EmailField(_("email address"), null=False,blank=False,unique=True) USERNAME_FIELD='email' REQUIRED_FIELDS = ["username"] object=CustomUserManager() class CustomUserManager(UserManager): def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self,username ,email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user( username,email, password, **extra_fields) def create_superuser(self,username, 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(username, email, password, **extra_fields) should i use this from django.contrib.auth.hashers import make_password and how to use this -
How to handle ForeingKey fields in DRF serializer
I have 2 models with ForeignKey relation class Order(models.Model): ip = models.CharField(max_length=15) ref_code = models.CharField(max_length=15) is_ordered = models.BooleanField(default=False) class OrderItem(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) quantity = models.IntegerField(default=1) size = models.ForeignKey(Size ,on_delete=models.CASCADE, related_name='sssize', default = None) order = models.ForeignKey(Order, related_name="item", on_delete=models.CASCADE) This is my serializer class CreateOrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem exclude = ('is_ordered',) def create(self, validated_data): order_item, created = OrderItem.objects.update_or_create( product = validated_data.get('product',None), quantity = validated_data.get('quantity', None), size = validated_data.get('size',None), ) return order_item I need to somehow get or create Order object base on ip (which i get from request) and is_ordered fields and pass it to serializer or do it in view I have tried to add order field in view.py after i get my serialized data but i get an error saying that order field is required View.py def post(self, request, pk): serializer = CreateOrderItemSerializer( data=request.data, ) print(serializer.initial_data) if serializer.is_valid(): product = serializer.save() ip = get_client_ip(request) order = Order.objects.get_or_create(ip = ip, is_ordered = False) product.order.add(order.id) Or need i get ip strait from POST method JSON? -
Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin
I have a model that I want to add to my admin pages. The model class is. class Client(models.Model): FBUSER = "FBU" GOOGLEUSER = "GU" FBACCESSCODE = "FBAC" GOOGLESECRET = "GS" MISC = "MISC" CLIENT_KEY_CHOICES = [ (FBUSER, "Facebook User ID"), (FBACCESSCODE, "Facebook Access Code"), (GOOGLEUSER, "Google User"), (GOOGLESECRET, "Google Secret"), (MISC, "Misc"), ] client_key = models.CharField( max_length=4, choices=CLIENT_KEY_CHOICES, default=FBUSER, ) id = models.BigAutoField(primary_key = True), client_name = models.CharField(max_length=100, blank=True, null = True), client_value = models.CharField(max_length=100, blank=True, null = True), and my admin.py is class ClientDataAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['client_key', 'client_name', 'client_value' ]}), ] list_display = ('client_name', 'client_key', 'client_value') search_fields = ['client_name'] I have looked at several similar error explanations and fixes but none fit, this case. I have other models and admin scripts that work fine, but I cannot find anything wrong here. The admin page shows the add link but I get the following error when I hit it... Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin. Request Method: GET Request URL: http://localhost:8000/admin/kdconnector/client/add/ Django Version: 4.1.7 Exception Type: FieldError Exception Value: Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin. I suspect it comes from the choices … -
Why is my breakpoint in Django not activated when I use a custom authentication backend
I have a custom user authentication back end in Django so I can make a user log in with email and or username. I placed a break point in the in the authenticate method but it is not firing so I can check why the authenticate method is returning None all the time. I changed the settings to include: AUTHENTICATION_BACKENDS = ["users.backends.EmailOrUsernameBackend"] Here is the view to handle the login: from django.contrib.auth import authenticate @api_view(["POST"]) def LoginUser(request): email = request.data.get("email") username = request.data.get("username") password = request.data.get("password") exists = User.objects.filter(email=email).exists() if exists: user = User.objects.get(email=email) if user.is_active and user.email_verified_at is None: authenticated = authenticate(email=email, username=username, password=password) if authenticated is not None: serializer = LoginSerializer(authenticated) token, created = Token.objects.get_or_create(user=user) return Response( {"id": serializer.data["id"], "Authorization": token.key, "role": user.role}, status=HTTP_200_OK, ) else: return Response("Wrong email and/or password", status=HTTP_401_UNAUTHORIZED) else: return Response("Account is not active! Did you change your email and haven't confirmed it?") else: return Response("Email is not registered, please register") Here is the custom backend to authenticate the username, or email and password: class EmailOrUsernameBackend(ModelBackend): def authenticate(self, **kwargs): breakpoint() email = kwargs.get('email') username = kwargs.get('username') password = kwargs.get('password') if email: try: user = User.objects.get(email=email) except User.DoesNotExist: return None elif username: try: user = … -
Best way to old "version" of specific parameters on django model
I want to do a "version control" kind of thing. I have a django model called "Person" I also have a method of updating all persons "gender" and "language" according to "detection" version. this method improves from version to version. I dont want to "detect" gender of person in latest version to not over use resources, each detection cost ... my method need to run over all persons with gender version 1 or language version 1 and update the person lang and gen to version 2 (run the method). so the simple is: class Person(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) phone_version = int ... language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) language_version = int ... but I have also 20 more filters (like gen and lang) so I prefer to have one attribute named version, so I could filter also in a simple way. if I do ManyToManyField to class Version it will be slow to do filters, right ? class Person(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) version_control = models.ManyToManyField(DetectionVersion ...) class DetectionVersion(models.Model): phone_version = int ... language_version = int .. is the second fast and a good solution ? -
Wrong distance between two points in Geodjango
I have user class: class User(AbstractBaseUser): location = PointField(srid=4326) and I calculate distance between two points in serializer this way: obj.location.distance(request.user.location) * 100 For example I have two points: POINT(-95.3385 29.7245) POINT(-85.3385 29.7245) One point is for authorized user the other is for the other user. Serializer returns 1000 kilometers. I don't know what is latitude and longitude and it doesn't matter because in online calculators in one case it is a little bit more than 1000 km and in the other - a little bit less than 1000 km. And it is never 1000 km. Any ideas why this is happening? -
Calling javascript functions in static, Django
Im struggling to understand why I cant call a javascript function when my Bootstrap button is clicked in Django. I have created the static folder in my directory "main/static/main/js/script.js" I am able to load the static css file for boostrap without any issues, but for whatever reason the javascript function "testing()" cant be called. Web browser console logs as Uncaught ReferenceError: testing is not defined onclick. Am i suppose to use AJAX instead, or is there simply something wrong with my settings or url path. my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATICFILES_DIRS = [BASE_DIR /'main/static'] STATIC_URL = '/static/' my scripts.js function testing() { alert("Button clicked!"); } my index.html, that is using bootstrap: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>MoviePicks</title> <!-- Core theme CSS (includes Bootstrap)--> <link rel="icon" type="image/x-icon" href="{%static 'main/assets/favicon.ico'%}" /> <link href="{%static 'main/css/styles.css'%}" rel="stylesheet" /> </head> <body id="page-top"> <!-- Header--> <header class="bg-dark bg-gradient text-white"> <div class="container px-4 d-flex flex-column align-items-center text-center"> <!--code to play … -
How to save multiple product ID from cart to Order table under one Order ID?
I tried to do this with my own coding based on the internet and chatgpt. However it only save one item from the cart. Can somebody help me?? (p/s : I used ManyToMany field for ProdID under Order table to save multiple products from Cart page) models.py (i put the null = True bcs i just want to focus on the orderID functionality) class Cart(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) item_qty = models.IntegerField(default=1) class Customer(models.Model): CustID = models.CharField(max_length=100, primary_key = True) CustName = models.TextField() CustAdd = models.TextField() CustPhone = models.TextField() class Order(models.Model): OrderID = models.CharField(max_length=100, primary_key = True) ProdID = models.ManyToManyField(Product) CustID = models.ForeignKey(Customer, on_delete = models.CASCADE, null=True) totalprice = models.FloatField(null=True) ordered_date = models.DateTimeField(auto_now_add=True) payment = models.TextField(null=True) paystatus = models.CharField(max_length=50,default='Pending') coding related to my problem in cartpage.html <form action="{% url 'placeorder' %}" method="get"> {% csrf_token %} <tbody> <tr> {% for cart in cart %} <td><button pid = "{{ cart.product.ProdID }}" class="remove-cart btn"><ion-icon name="close-outline"></ion-icon></button></td> <input type="hidden" name="prodid" value="{{cart.product.ProdID}}" id="prodid" class="prodid"> <td class="w-5"><image src="{{ cart.product.ProdPic.url }}" style="height:80px; width:65px;" class="rounded-circle"></td> <td>{{cart.product.ProdName}}</td> <td class="cart-product-quantity"> <input type="button" pid = "{{ cart.product.ProdID }}" class="minus-cart btn btn-light btn-circle btn-sm" value="-"></input> <span id="quantity" min="1">{{ cart.item_qty }}</span> <input type="button" pid = "{{ cart.product.ProdID }}" class="plus-cart btn btn-light btn-circle … -
How to make calorie goal dynamic in my django app that user can input according to them?
https://github.com/geetanshpardhi1/FitCalorie The above link redirects you to my repo where you can find code. In myapp/index.html (line no.127) I have added functionality for the calorie goal which is hardcoded for value 2000 and I want to make it dynamic for each user, how can I do it? My doubt is in which model do I have to add a goal field and how can I integrate HTML input with it? -
Budgeting feature for django ecommerce web app
Can anyone help me with login to build a budget feature within a ecommerce platform. i have this project I am designing for my final year project but i want to design a page where user can find multiple product within a specific price. Let say the user want to a shirt, bag and shoe but have 7000, I want the app to return all the three product that can be bought with 7000. -
Django - Display specific attribute of object in <Select> in template
I have the following Python models: class Usuario(models.Model): login = models.CharField(max_length=200) senha = models.CharField(max_length=200) meta = models.ManyToManyField('meta', through='Usuario_meta') def __str__(self): return f'id: {self.id} - login: {self.login} - senha: {self.senha}' class Meta(models.Model): tipo = models.CharField(max_length=200) def __str__(self): return f'id: {self.id} - senha: {self.tipo}' class Usuario_meta(models.Model): usuario = models.ForeignKey(Usuario,on_delete=models.CASCADE) meta = models.ForeignKey(Meta,on_delete=models.CASCADE) data = models.DateField() valor = models.IntegerField() def __str__(self): return f'Meta do usuário: {self.usuario} - meta:{self.meta} - data:{self.data} - valor: {self.valor}' The following view: class UsuarioMetaCreate(CreateView): model = Usuario_meta template_name = 'lancamento_meta_cadastro.html' fields = '__all__' The following html: <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Submit" /> </form> Which displays the following: I would like to show, in the "usuario" select, only the attribute "login". Apparently, it calls the 'str()' and displays all the fields. Is there a way to show only a specific attribute while using CreateView and without modifying the 'str()' method? I have already tried using <form action="" method="post"> {% csrf_token %} {{form.usuario.login}} <input type="submit" value="Submit" /> </form> But it doesn't display anything -
How to use python
How to solve this question using Python. Does anyone try to help me to solve this question? I'm trying to solve this question but it is not working properly. -
Dynamically create periodic tasks or one time tasks - django celery beat
We have multiple scripts written in different lang ( Python, shell, golang ) and so on. I am trying to create a centralized application, where any user can create periodic tasks or one time tasks using django/celery. Basically the idea is user1 -> python test.py arg user2 -> ./test.sh arg1 arg2 The idea is not to pre defined tasks and dynamically create tasks. is it possible ?? any lead or blog should be helpful. -
DRF: Serializer update method returns KeyError during partial update, instead of ValidationError raised by model clean() method
In Django Rest Framework, I'm testing one of the endpoints for proper exception handling. A ValidationError is expected but instead a KeyError is returned. I've been trying to debug this case for a while now so here's the step-by-step breakdown of what happens: Step 1: Incoming data gets serialized: class BatchIdView(APIView): ... def patch(self, request, batch_id): ... serializer = BatchSerializer(batch, data=data, partial=True) if not serializer.is_valid(): return Response(data=humps.camelize(serializer.errors), status=status.HTTP_400_BAD_REQUEST) There are no custom validators in this serializer and data is validated during this step (is_valid() method returns True) Step 2: Attempting to update the object (actually this code comes directly following previous snippet): try: serializer.update(batch, serializer.validated_data) except ValidationError as e: return Response(data=humps.camelize(e.messages), status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(data={"error": str(e)}, status=status.HTTP_501_NOT_IMPLEMENTED) Step 3: During the update() method, model's save() method triggers validation: class Batch(models.Model): ... def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) def clean(self): if self.product_type in ["..."] and self.model is not None: raise ValidationError({"model": "error text goes here"}) I've double-checked that this raise ValidationError() line gets triggered in that particular test case. Step 4: Instead of returning the validation error, the serializer decides to trigger to_representation() method which is customized and is checking for another field: def to_representation(self, instance): … -
FileField doesn't upload when deploying on server
I'm deploying a Django app on my server. On my local machine, it works fine. I've also been able to access site thanks to Caddy and running the python runserver 0.0.0.0:8000 command as a systemd service. When I now try to upload a file to my server via the form that I have created, the file doesn't get uploaded. My forms.py: class EntryForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'})) modelMedium = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}), required=False) modelLarge = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}), required=False) file = forms.FileField(required=True) timeStamps = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Time Stamps in seconds'}), required=True) def __str__(self): return self.title class Meta: model = Entry fields = ['title', "modelMedium", "modelLarge", "file", "timeStamps"] The corresponding part of view.py: def upload(request): if request.method == "POST": form = EntryForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Uploaded successfully!") return redirect("home") else: messages.success(request, "Invalid form!") return redirect("upload") When looking at journalctl, I'm not getting any error messages, Django gives me the message "Uploaded successfully", and the entry into my model is made correctly (even with the file name), but the file does not exist when I check the directory. I checked all the permissions for the folders that I am referencing and they are all set correctly (or I assume … -
I am implementing Django email sender, however , it is giving me an error that some module is not found
Following is the error: ModuleNotFoundError: No module named 'django.core.mail.backends.smpt' views.py: def register_patient(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone= request.POST['phone'] pic = request.POST['picture'] print(name) patient = Patient(name=name, email=email, phone=phone, photo=pic) patient.save() subject = "Thank you for registering" message = "Welcome the the clinic." from_email = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, from_email, recipient_list) print("fsfsdf") return render(request, "thanks_reg.html",{"name" : name}) imports: from django.core.mail import send_mail from django.conf import settings I have imported django.core.mail. Perhaps, it reqiures some other module to be imported -
In Django, given an instance of Model A, how to define a relation between two instances of model B?
What (I think) I'm trying to achieve is to create a new column in my database (resp. a new field in my model) for model B every time there is a new instance of model A. To clarify, say I have the following model in Django : class Unit(models.Model): unit = models.CharField(max_length=200) with two instanciations : Kilograms and Volume (m^3). I'm looking to specify the following class: class Object(models.Model): object = models.CharField(max_length=200) # Field to relate `Volumes` to `Kilograms`, as a float so that I'm able to declare the relation between Kilograms and Volume (m^3) for each specific object. In a way, I'm trying to declare a float that relates the volume for each kilogram of the object (or vice-versa). I could use a workaround and add a FloatField if I knew Kilograms and Volume would be the only instances of Unit, but unfortunately, there might be others. PS: Additional (less important) question: Could I select a default unit, and declare the other ones compared to that default unit. Something like the following: class Object(models.Model): object = models.CharField(max_length=200) default_unit = models.ForeignKey(Unit, on_delete=models.CASCADE) # Field to compare unit_1 to default_unit # Field to compare unit_2 to default_unit # And so on … -
Translate model field names in Django Rest Framework serializers
How to translate model field names in Django Rest Framework serializers. I am working on a django project and django rest framework(DRF) and I need to return the translated fields of a model in french if the user selects 'french' or in english if the user selects 'english'. So how to do that, please? I tried to translate field names in the serializer using gettext_lazy from django.utils.translation import gettext_lazy as _ class TranslatedCharField(serializers.CharField): def get_field_names(self, declared_fields, info): field_names = super().get_field_names(declared_fields, info) translated_field_names = [str(_('title')).lower() if field_name == 'title' else field_name for field_name in field_names] return translated_field_names class PostSerializer(serializers.ModelSerializer): title = TranslatedCharField() class Meta: model = Post fields = ['title','about'] I tried to that using some third party packages such as: drf-extensions django-rest-framework-translate django-rest-framework-translate but still not working... -
Some translations are not getting translated
I have this in my admin.py: class SomeAdmin(admin.ModelAdmin): @admin.display(description=_('Cases %(year)d') % {'year': previous_year}, ordering='cases_previous_year') def previous_year(self, inv_presidency): ... some code ... and this in app/locale/ar/LC_MESSAGES/django.po #: case_tracking/gdoi/case_movements/admin.py:313 msgid "Cases %(year)d" msgstr "قضايا %(year)d" everything is getting translated, except the one mentioned above!! why is that? Thanks