Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate Django / Python Test for view with LoginRequiredMixin and UserPassesTestMixin
I am trying for some time to test a view of mine that I have protected from access via LoginRequiredMixin and UserPassesTestMixin. Unfortunately I do not manage to write the appropriate test. here is the view. The special thing is, that the user must not only be logged in, but he must also belong to the group "Administrator" or "Supervisor". With this combination I have not yet managed to write a test. Please who can help me. Here is my View: class FeatureListView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = FeatureFilm template_name = "project/feature-list.html" def test_func(self): if self.request.user.groups.filter(name="Administrator").exists(): return True elif self.request.user.groups.filter(name="Supervisor").exists(): return True elif self.request.user.groups.filter(name="Operator").exists(): return True else: return False def handle_no_permission(self): return redirect("access-denied") and here is a snippet of the url.py: urlpatterns = [ path("feature/list/", FeatureListView.as_view(), name="feature-list"), path( "feature/<int:pk>/date", FeatureDetailViewDate.as_view(), name="feature-detail-date", ), how would you test this FeatureListView and the template belongs to thank you very much! -
Django: How does one mock a method called in an api test?
I keep hitting a method scan_file() that should be mocked. It happens while calling self.client.post() in a django api test. The app setup is below, I've tried mocked the imported scan_file patch("myapp.views.scan_file") as well as the source location patch("myapp.utils.scan_file") neither work. # myapp.views.py from myapp.utils import scan_file class MyViewset(): def scan(): scan_file() # <- this should be mocked but its entering the code #myapp.utils.py def scan_file() -> bool: boolean_result = call_api() return boolean_result #test_api.py class MyAppTest(): def test_scan_endpoint(self): patcher = patch("myapp.views.scan_file") MockedScan = patcher.start() MockedScan.return_value = True # This post hits the scan_file code during the api # call but it should be mocked. resp = self.client.post( SCAN_ENDPOINT, data={ "file" :self.text_file, "field1" : "Progress" } ) I've also tried the following syntax for mocking, and tried including it in the test setup() as well: self.patcher = patch("myapp.views.scan_file") self.MockedScan = self.patcher.start() self.MockedScan.return_value = True -
How are Django's form assets (Media class) served?
The "Form Assets" page of Django says Django allows you to associate different files – like stylesheets and scripts – with the forms and widgets that require those assets. For example, if you want to use a calendar to render DateFields, you can define a custom Calendar widget. This widget can then be associated with the CSS and JavaScript that is required to render the calendar. When the Calendar widget is used on a form, Django is able to identify the CSS and JavaScript files that are required, and provide the list of file names in a form suitable for inclusion on your web page. Okay, but what component of Django takes those form assets and actually puts them in the page? I ask because I'm trying to use django-autocomplete-light (DAL) with django-bootstrap5 on a multi-select form with a many-to-many field. I've done all the installing, put the widget on my form field: class SomeForm(forms.ModelForm): class Meta: model = Something fields = ['things'] widgets = { 'things': autocomplete.ModelSelect2Multiple( url='myapp:things-autocomplete') } I can see the HTML for the form widget includes autocomplete-light stuff to multi-select "things" with "things" autocomplete: ... <select name="things" class="form-select" required id="id_things" data-autocomplete-light-language="en" data-autocomplete-light-url="/thing-autocomplete/" data-autocomplete-light-function="select2" multiple> </select> ... … -
Will I be able to use a wordpress site domain as a django website on a VPS?
I deleted all the files and folders associated with the Wordpress site I intend to write from scratch using standard HTML, JavaScript, CSS and with Django framework. My question is if I can use this domain with this newly created site in a VPS. At first I had erased the files and folders and recreated it with the Django app right onto the Wordpress structure, and that does not seem to be working. I am most likely doing something wrong anyways, but I am after the right way of accomplishing this. -
Django cannot migrate on Galera but MariaDB standalone works
I'm using Django together with MariaDB, I now moved my application to K8s and my Django migration don't want to run through, instead the whole migration process fails. On my local development system I'm using a standalone MariaDB instance where everything is working fine. How can it be that the same process is not working against a Galera-Cluster, here the output of my application is the following while trying to migrate all the tables: python manage.py migrate Operations to perform: Apply all migrations: App, App_Accounts, App_Storages, admin, auth, contenttypes, database, django_celery_results, sessions, sites Running migrations: Applying contenttypes.0002_remove_content_type_name... OK Applying App_Storages.0001_initial... OK Applying App_Accounts.0001_initial...Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django_prometheus/db/common.py", line 71, in execute return super().execute(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) ^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/venv/lib/python3.11/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1170, "BLOB/TEXT column 'avatar_path' used in key specification without a key length") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/strics/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line … -
I want to make a checkbox type filter on the items of an e-commerce
I have a simple e-commerce where I want to filter items. This will be done in a form checkbox, but the form's categories are user-created, ie it's a "for" of Cor.objects.all() . The filter only works for the last selected color. So I wanted it to have multiple filters. index.html: <div class="widgets-item"> <form id="widgets-checkbox-form" action="{% url 'carro_filtro' %}" method="GET"> <ul class="widgets-checkbox"> {% for cor in cores %} <li> <input class="input-checkbox" type="checkbox" id="color-selection-{{ cor.id }}" name="termo" value="{{ cor.nome_cor }}"> <label class="label-checkbox mb-0" for="color-selection-{{ cor.id }}"> {{ cor.nome_cor }} </label> </li> {% endfor %} </ul> <input type="submit" class="btn btn-custom-size lg-size btn-primary w-100 mb-5 mt-5" value="Filtrar"> </form> </div> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.CarView.as_view(), name='shop'), path('filtro/', views.CarroFiltro.as_view(), name='carro_filtro'), ] views.py class CarView(ListView): model = Car template_name = 'shop/index.html' paginate_by = 12 context_object_name = 'cars' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['personalizacoes'] = Shop.objects.filter( publicado_shop=True).order_by('-id').first() context['categorias'] = Categoria.objects.all() context['cores'] = Cor.objects.all() return context def get_queryset(self): qs = super().get_queryset() categoria = self.kwargs.get('nome_categoria', None) if not categoria: qs = qs.filter(publicado=True).order_by('-id') return qs qs = qs.filter( categoria_carro__nome_categoria__iexact=categoria, publicado=True).order_by('-id') return qs class CarroFiltro(CarView): def get_queryset(self): qs = super().get_queryset() color_selection = self.request.GET.get('termo') print("X"*100) print(color_selection) print("X"*100) if not color_selection or color_selection is … -
Django custom selection HTML page for django admin form
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page. I have done a 100 times before, but now the value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none Driving me crazy, I cannot find anything wrong in the code The Html template {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_modify %} {% block extrahead %} {{ media }} {% endblock %} {% block content %} <form class="change_superprofile_parent_form" method="POST" class="change_superprofile_parent_form">{% csrf_token %} {% for superprofile in superprofiles %} <input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br> {% endfor %} <input type="submit" value="Submit"> </form> {% endblock %} Django admin.py def change_superprofile_parent(self, request, queryset): """ Action to change the superprofile of the selected """ queryset = queryset.values_list("id", flat=True) if request.method == 'POST': selected_value = request.POST.getlist('superprofile_selected') eligible_superprofiles = SuperProfile.objects.filter(status='Active') return render( request, 'admin/auth/user/change_superprofile_parent.html', context={ 'superprofiles': eligible_superprofiles, } ) -
Django: Pass non-editable data from the client to the server
I am building a media tracker for TV shows and movies. When the user makes a query on the front-end, on the server I make a request with an API in which I get TV shows/movies with id, title, image link, media type, seasons, etc. After that, I display the result of the query on the front-end with the name and image: Then the user can select one of the results and get a simple form: The thing is that after submitting the form, I want to save the score and progress with the id, media type and other parameters that aren't shown on the front-end but are related to the media submitted. At the moment I am using to pass the values to the server: <input type="hidden" name="id" value="{{media.response.id}}"> The problem with this is that the user could change the id value with the developer tool (inspector), which would cause problems. I don't really know how to validate the form as the id could be any number. Is there a better and still simple approach? Thanks in advance -
Django_filter: filtering using current value of another field
So I was tasked with creating a events page where my company can post upcoming events and visitors can filter based on location, title or event type based on other 'is_virtual' which can be in person, virtual or hybrid. Now they want to 'ignore' the location filter if the event is virtual or hybrid but to keep it if the event is in person. I've been having issues accessing the value of the is_virtual field of the current object to create the conditional filtering based on it's value. here's the filter code: import django_filters from django import forms from .models import EventsPage class EventsFilter(django_filters.FilterSet): event_type = django_filters.ChoiceFilter( choices=EventsPage.event_choices, empty_label='Event Type', widget=forms.Select(attrs={'class': 'custom-select mb-2'}) ) location = django_filters.ChoiceFilter( choices=EventsPage.location_choices, empty_label='All Locations', widget=forms.Select(attrs={'class': 'custom-select mb-2'}) ) title = django_filters.CharFilter( lookup_expr='icontains', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Search Events'}) ) class Meta: model = EventsPage fields = ['event_type', 'location', 'title'] any ideas helps! thanks in advance. tried using the method keyword argument built in django_filter library and the values passed to the helper method only show the value of the current field but I can't see the current value of the is_virtual field. here's what I tried to do: location = django_filters.ChoiceFilter( method='location_filtering', choices=EventsPage.location_choices, empty_label='All … -
Django show exception in webpage instead of on console
I am launching a Django API from the console via the following command line: python3.10 manage.py runserver 0.0.0.0:8080 However, sometimes, when there is an error on one of the pages, like for instance if I import a python package that was not installed via pip, the webserver does not get launched, I get a python exception on the console, but no webserver is launched (the network port is not even listening). Is there a way to still have the webserver running and showing any exceptions or errors that might arise ? This API is for learning purposes, the students should only be able to deploy their code by doing a git push and the new code is deployed. But in case of an error that is not shown in the webpages they would not know what went wrong, they do not have access to the server to see the console. Thank you for your help. -
Use a nested dict (or json) with django-environ?
I've got a nested dict format that I wanted to setup in an environment. It looks like this: DEPARTMENTS_INFORMATION={ "Pants": { "name": "Pants Department", "email": "pants@department.com", "ext": "x2121" }, "Shirts": { "name": "Shirt Department", "email": "shirts@department.com", "ext": "x5151" }, "Socks": { "name": "Sock Department", "email": "socks@department.com", "ext": " " } } I am using django-environ for this and tried using it like this: DEPARTMENTS = env.dict("DEPARTMENTS_INFORMATION", default={}) But it's giving me this error: ValueError: dictionary update sequence element #0 has length 1; 2 is required I'm not sure how to make the nested dictionary an environment variable - any help appreciated! -
Is there a away to make a Django SaaS app without subdomains?
i would like to ask if there's a way to make a django app with 2 roles (me as a django admin that can use /admin panel to manage the website) and customers (who have access to the app) but without using subdomains or subfolders ? thank you so much. -
Modify the structure of a table in html provided from a listview and j in django
Good night, RESUME: When I tried add a new field of the model in the html table with js and listview, the header of the table YES is modified, but the rows of it NOT are modified. I would clarify that JS is not my native develop. now I am starting with it. Then, the history of my attempts and the codes, in the source ant with the modifications. I have a table that is sourcing from a data object in js script, and render in a template of django. The data of the model is read from models.ListView. How I can to modify the structure of it??? I have tried to do, on the one hand in the js changing the "columns" property. It not modify nothing. To modify the header of the table, I have to modify the list html addint tr/td but the rows structure not add the new fields, the colums are in distinct order. without modifications: without modifications for example, if add the field 'types' that exists in model, first, in the js : columns: [ {"data": "position"}, {"data": "name"}, {"data": "types"}, {"data": "desc"}, {"data": "options"}, then, in the html add a th in the … -
Django: unable to login user with correct email/password
I am very new to Django and this is my first project. I am trying to build a simple login/registration with MySQL as db and a custom user model. The user is successfully signing up but unable to login using correct pw and email. I tried redoing my signup function and index function (login) and changed username to email in my custom model and index function. view.py: from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.shortcuts import render, redirect from .models import CustomUser from .forms import CustomUserCreationForm, EmailAuthenticationForm from django.contrib.auth.forms import AuthenticationForm from .backends import EmailBackend # sign up def signup(request): if request.user.is_authenticated: # if user is already logged in, redirect to the appropriate page return redirect('/home') if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=True) # Hash the password user.set_password(user.password) user.save() else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form': form}) # login def index(request): if request.method == 'POST': form = EmailAuthenticationForm(data=request.POST) if form.is_valid(): email = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = EmailBackend().authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') else: return redirect('error') else: form = EmailAuthenticationForm() return render(request, 'index.html', {'form': form}) forms.py: from django import forms from django.contrib.auth.forms … -
JSONDecodeError in Django after Paypal payment
I keep getting the below error when I complete payment via Paypal in development: JSONDecodeError at /checkout/thankyou Expecting value: line 1 column 1 (char 0) I have looked around and I can see that there is some issue with the format of the JSON, and my view can't process it. I can't figure out what the issue with my data is exactly, however. I want to use my Json data to create an order on my Django model once it has pulled through, however I can't get to that stage yet. checkout.html script: let bagContents = '{{ bag_products|safe }}'; const csrftoken = getCookie('csrftoken'); const paymentAmount = '{{ total | safe }}'; // Parse bagContents, then for each create a variable for name, id and quantity let bag = JSON.parse(bagContents); for (let i = 0; i < bag.length; i++) { let itemName = bag[i].name; let itemId = bag[i].id; let itemQuantity = bag[i].quantity; console.log(itemName); console.log(itemId); console.log(itemQuantity); } function completeOrder(){ let url = '{{ success_url }}' fetch(url, { method: 'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'bagContents': 'bagContents'}) }) } paypal.Buttons({ // Sets up the transaction when a payment button is clicked createOrder: (data, actions) => { return actions.order.create({ purchase_units: [{ amount: { value: … -
django icontains doesnt work with line beakes
im using django 2.1.8 model.py class Article(models.Model): title = models.CharField("title", default="", max_length=20) text = models.CharField("comment", default="", max_length=120) the one object i have [ { "id": 1, "title": "test", "comment": "there is a linebrake" } ] views.py a = Article.objects.filter(text__icontains="\r\n").all() b = Article.objects.filter(text__icontains="there").all() It finds a but not b. As long as icontains includes the "\r\n" i can find all things normal. But a user wont search for "\r\n linebrake". how does it work without "\r\n"? -
Auto add pages for image gallery django
I have a Django website which is basically an image gallery. I want to be able to limit the amount of images that can be posted per page, and when this limit is reached, create a new one. Firstly, can this be done? If so how? TYIA -
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?