Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatic avoidance of category duplicates
I have the problem with Category Model. I have 2 tables: class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) class Movie(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) so they are standard models with categories. User can create Category by creating a movie with the name of category additionaly. The problem is when user is trying to create Movie with category name that already exists, because it will create another category with the same name (like duplicate) and I want to avoid it. How to do it? I can't create unique name field, because many users can have same category (but I can use ManyToManyRelation) but still I don't know how to automatically avoid duplicates like bellow: If Category with that Name and this User does not exist > create Category If Category with that Name and this User exists > use this Category Regards -
How to Redirect tenant to subdomain home page after user can login in public schema
I have to redirect to home page without login in subdomain after login in public tenant That means suppose - public domain is : logic.com subdomain is : tenant1.logic.com I have tried to login to the public domain (logic.com/login) so now I have to redirect to the home page of the subdomain(tenant1.logic.com/home) Without subdomain login def login_user(request): if request.method == 'GET': return render(request, 'users/login-user.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['email'], password=request.POST['password']) if user is None: return render(request, 'users/login-user.html', {'form': AuthenticationForm(), 'error': 'Username and ' 'password did not ' 'match'}) else: client = Client.objects.filter(owner=user).first() with schema_context(client.schema_name): login(request, client.owner) host = request.META.get('HTTP_HOST', '') scheme_url = request.is_secure() and "https" or "http" url = f"{scheme_url}://{client.slug}.{host}" return HttpResponseRedirect(url) What can I do if anyone has know about this? Thanks in advance -
What are the technologies i have to use to bulid news website and app with live news streaming option
what are the technologies required, is it possible with using Wordpress -
how to mail an image stored in an array variable as attachment without saving it on the drive
I have an image stored in the memory as a NumPy array format( stored in a NumPy array variable). I want to mail this image as an attachment to a user without saving it on my drive. Is there a way for doing this? I have tried various codes but have not gotten the mail. can someone help me with this? any help is truly and sincerely appreciated. -
From a list of dictionaries in python Django how to filter/find and highest valued prize per user per day
I want to find out per day per user what is the highest prize he has won my_list = [{'id': 1, 'user_id': 4, 'date': datetime.datetime(2022, 9, 9), 'prize': '45.00'}, {'id': 2, 'user_id': 5, 'date': datetime.datetime(2022, 9, 5), 'prize': '85.00'}, {'id': 3, 'user_id': 5, 'date': datetime.datetime(2022, 9, 5), 'prize': '35.00'}, {'id': 4, 'user_id': 4, 'date': datetime.datetime(2022, 9, 9), 'prize': '95.00'}, {'id': 5, 'user_id': 3, 'date': datetime.datetime(2022, 9, 9), 'prize': '10.00'}, {'id': 6, 'user_id': 6, 'date': datetime.datetime(2022, 9, 5), 'prize': '15.00'}] the result should be as below result = [{'id': 2, 'user_id': 5, 'date': datetime.datetime(2022, 9, 5), 'prize': '85.00'}, {'id': 4, 'user_id': 4, 'date': datetime.datetime(2022, 9, 9), 'prize': '95.00'}, {'id': 5, 'user_id': 3, 'date': datetime.datetime(2022, 9, 9), 'prize': '10.00'}, {'id': 6, 'user_id': 6, 'date': datetime.datetime(2022, 9, 5), 'prize': '15.00'}] In above Example user_id=4 have 2 prizes on date(2022, 9, 5) i.e $45 and $95. Among these 2 we have to pick the highest valued record $95 -
Error when returning JsonResponse(). Django
It's returning error when i use instance or without that in JsonResponse. Maybe JsonResponse cannot serialize data. The error is Traceback (most recent call last): File "/Users/admin/Documents/Projects/food/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/admin/Documents/Projects/food/venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 138, in call response = self.process_response(request, response) File "/Users/admin/Documents/Projects/food/venv/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'tuple' object has no attribute 'get' I couldn't find source of error. I tried to solve that with helping google. But I did't find any exact solution. Yes tuple doesn't have a method get. views.py class CreateCategoryAjaxView(View): def post(self, request, *args, **kwargs): form = CategoryForm(request.POST, request.FILES) if form.is_valid(): instance = form.save() return JsonResponse( {'is_success': True, 'id': instance.id, 'title': instance.title}), return JsonResponse({'is_success': False, 'errors': form.errors}) forms.py class CategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' widgets = { 'title': forms.TextInput( attrs={'placeholder': ' Пиццы...', 'class': 'form-control', 'id': 'id_category_title'}), 'image': forms.FileInput(attrs={'accept': 'image/*', 'id': 'id_category_image'}), } -
What's the difference between get_user_model() and importing CustomUser model directly?
This is my views.py in a API server running Django REST framework. from rest_framework import generics from users.models import CustomUser from .serializers import CustomUserSerializer class PCAPIView(generics.ListAPIView): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer This code works fine. However, when I google around, I discovered that the recommended way is to use get_user_model(). So, the proper views.py should look like this; from rest_framework import generics from django.contrib.auth import get_user_model from .serializers import CustomUserSerializer class PCAPIView(generics.ListAPIView): queryset = get_user_model().objects.all() serializer_class = CustomUserSerializer I tested and both code worked as I wanted. What is the difference between the 2 code? Is get_user_model() really better? I am using django v4, python 3.9, django rest framework. -
I am currently using django 4.0 getting this error while including ('rest_auth.urls')
from django.contrib import admin from django.urls import path,include from Users.urls import * from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path("",include("Users.urls")), path('api/v1/rest-auth/', include('rest_auth.urls')), ] Error:-ImportError: cannot import name 'url' from 'django.conf.urls' -
Use diffrent model for users who login with django google allauth login
I am using Custom User model for only admins but I have to create seperate login sysytem for clients who uses django allauth google login system and these clients have below model: class ClientUser(models.Model): username = models.CharField(max_length=50, blank=True, null=True, unique=True) email = models.EmailField(("email address"), unique=True) first_name = models.CharField(max_length=50, blank=True, null=True, unique=True) last_name = models.CharField(max_length=50, blank=True, null=True, unique=True) phonenumber = models.CharField(max_length=15, null=True) def __str__(self): return "{}".format(self.email) How could I make google allauth use this model? -
how to set django datatable in dropdown manue in admin pannel?
I need help in django admin custom designing. I have datatables for example blog tables in one dropdown scubscription tables on other. I have shared screen short of my datatables. here GSMAPP datatables that I want to divide in some dropdown.any suggestion please -
How can I access form(in template) which is defined in another app(views) in Django
New to Django. So please help me. What my goal here is that I want to access form from another application(cart) to my current application(shoppApp). views.py(cart application): from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shoppApp.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product,quantity=cd['quantity'],update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id,slug=slug,available=True) cart_product_form = CartAddProductForm() return render(request,'shop/product/detail.html',{'product': product,'cart_product_form': cart_product_form}) forms.py(cart application) from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES,coerce=int) update = forms.BooleanField(required=False,initial=False,widget=forms.HiddenInput) details.html(shoppApp application) {% extends "shop/base.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class="product-detail"> <img src="{% if product.image %}{{ product.image.url }}{% else %}{% static 'img/no_img.jpg' %}{% endif %}"> <h1>{{ product.name }}</h1> <h2><a href="{{ product.category.get_absolute_url }}">{{product.category }}</a></h2> <p class="price">${{ product.price }}</p> <form action="{% url 'cart:cart_add' product.id %}" method="post"> … -
How to set port in Django channels websocket
I am working on Django project and built Chat application, now troubling with websocket port, when i start chat with any one person the default port generating and i leave that user and chat with other user port is changing so i can't receive other person message notification because of port changing every time so please help for that consumers.py class PersonalChatConsumer(WebsocketConsumer): def connect(self): my_id = self.scope['user'].id other_user_id = self.scope['url_route']['kwargs']['id'] if int(my_id) > int(other_user_id): self.room_name = f'{my_id}-{other_user_id}' else: self.room_name = f'{other_user_id}-{my_id}' self.room_group_name = 'chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data=None, bytes_data=None): data = json.loads(text_data) message = data['message'] email = data['email'] data_base = self.save_message(email, self.room_group_name, message) print("This is a database output", data_base) print(text_data) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'email': email, } ) def chat_message(self, event): message = event['message'] user_id = event['email'] user_obj = User.objects.get(id=user_id) self.send(text_data=json.dumps({ 'message': message, 'email': user_obj.email, 'user_id': user_id })) print(f"{user_obj.email} : Messaage sent") def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # @database_sync_to_async is used with asynchronous code def save_message(self, email, thread_name, message): sendername = User.objects.get(id=email) sender_name = str(sendername) my_id = self.scope['user'].email new_message = ChatModel.objects.create(sender=email, sender_name=sender_name, receiver_name=my_id, message=message, thread_name=thread_name) new_message.save() return "Succes" setting.py 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', … -
how to find value in (txt) python string
i'm new to python world and i'm trying to extract value from text. I try to find the keyword by re.search('keyword') , but I want to get the value after keyword text = word1:1434, word2:4446, word3:7171 i just want to get the value of word1 i try keyword = 'word1' before_keyword, keyword, after_keyword = text.partition(keyword) print(after_keyword) output :1434, word2:4446, word3:7171 i just want to get the value of word1 (1434) -
How can I authenticate a user who belongs to another database in my other service in django rest framework?
I'm new to django and I am required to create two microservices with separate databases; One to hold user information and the other to hold todo/tasks information. So far, I have created two separate projects with two separate databases, To authenticate the user using simplejwt authentication. (todo_auth project with todo_auth database) To show the todo/task information specific to that user. (todo project with todo database) Once I login the user in the todo_auth project I need the todo project to detect that I have logged in the user when I pass in the jwt token that I got when I logged into the todo_auth project. How can I achieve this? Many thanks. PS: I'm running the two django projects on the same server with different port numbers. -
Is it possible for django template url direct to another project?
I have two projects called blog, user_auth, both are all django projects. In blog project, I need to do a user authentication. Of course we can do it in current blog project like the following. <span class="sign-in"> <a href="{% url 'blog:sign-in' %}">sign-in</a> </span> <span class="sign-up"> <a href="{% url 'blog:sign-up' %}">sign-up</a> </span> The question is if we have more projects which also need to do user authentication, we will have many repeated codes. Here user_auth project is to manage all the projects' user authentication. My question is if we can use {% url %} in a templates in blog project to direct to user_auth project? -
How do I allow a user to to select an arbitrary number of 'n' languages during account registration?
Suppose I am creating the next language learning application like Duolingo. Initially during the account registration process, the user can select up to 5 studying languages. At a later time, a user can subscribe to a premium subscription and set up to N number of languages in a different page like in their account settings. These selected languages will eventual filter a user's feed. How should I go about this in the proper way? What would something like this be called, so that I can read more about it in the documentation. Thank you kindly. It would be nice if I could define the allowed number directly in the settings file: STANDARD_USER_LANGUAGE_ALLOWANCE = 3 SUBSCRIBED_USER_LANGUAGE_ALLOWANCE = 5 Method 1 (Most likely terrible and not DRY): class User(AbstractUser): // Manually list all of them here and keep adding in the future language1 = ... language2 = ... language3 = ... class Language(models.Model): name = models.CharField( max_length=20, ) short_name = models.CharField( max_length=20, ) def __str__(self): return self.name class Meta: ordering = ['name'] Method 2 (Maybe use a ManyToMany relationship with a multiple checkbox as the widget)? Would this even be a good application of ManyToMany? class User(AbstractUser): languages = models.ManyToManyField(Language) -
Django annotate count for another queryset
Models: class Regions(models.Model): name = models.CharField(max_length=255, unique=True) class Owners(models.Model): name = models.CharField(max_length=255, null=False, unique=True) url = models.URLField(null=True) class Lands(models.Model): region = models.ForeignKey(Regions, on_delete=models.CASCADE) owner = models.ForeignKey(Owners, on_delete=models.PROTECT, null=True) description = models.TextField(max_length=2000, null=True) class LandChangeHistory(models.Model): land = models.ForeignKey(Lands, on_delete=models.CASCADE, null=False, related_name='lands') price = models.IntegerField() size = models.IntegerField() date_added = models.DateField(auto_now_add=True) Queryset that works but i need it to be annotated in another queryset somehow: lands_in_region = Lands.objects.values('region__name').annotate(count=Count('region_id')) returns for example: {'region__name': 'New York', 'count': 3}, {'region__name': 'Chicago', 'count': 2} In the 2nd queryset i need count of lands available in region. But instead of real count, i always get count = 1. How to combine them? Im pretty sure i could do it in raw sql by joining two tables on field "region__id", but dont know how to do it in django orm. f = LandFilter(request.GET, queryset=LandChangeHistory.objects.all() .select_related('land', 'land__region', 'land__owner') .annotate(usd_per_size=ExpressionWrapper(F('price') * 1.0 / F('size'), output_field=FloatField(max_length=3))) .annotate(count=Count('land__region_id')) ) For example. If it returns: land1 | 100$ | 100m2 | New York land2 | 105$ | 105m2 | New York land3 | 102$ | 102m2 | Chicago i need 1 more column, that counts for each land how many NewYork's and Chicago's are there land1 | 100$ | 100m2 | New York … -
Refused to execute script ... MIME type ('text/html') is not executable, and strict MIME type checking is enabled -- django reactjs whitenoise heroku
im currently in the process of deploying (read: struggling) my: django(backend) react-js/redux(frontend) django-ninja(api) whitenoise(backend - staticfiles) app to heroku. however, i keep getting this error message whenever i launch the app and go live: "Refused to execute script from 'https://off-world-v0.herokuapp.com/static/js/main.6b71531f.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled." "Manifest: Line: 1, column: 1, Syntax error." This error does NOT appear when im in development, so after spending the past 2 days crawling stackoverflow, reddit, youtube, etc. - a number of other individuals seem to be running into the same problem, yet no reliable answer (to my knowledge) has been postulated at this time. The strange part is the app did work on one try after i removed this line from the build/static "index.html" file: <link rel="manifest" href="./manifest.json"/> However, after updating and launching the app again the same errors came back, this time with a different staticfile asset as the source of the error. Attached below are some snippets of my code. Any insight or help would be greatly appreciated and would come with gifts/tributes/alms/bounty of your choosing to be delivered in the afterlife. django settings.py import os from pathlib import Path from dotenv … -
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table
I am having a problem with Django 2.2.7 and postgresql 12 using the command "python manage.py migrate". When I execute it, the process fails with the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "clients_clients" I understand that this error indicates that when a field is used as a foreing key in another table, this field must be unique. My model clients in Django is: class Clients(models.Model): name = models.CharField(max_length=60, unique=True) document_num = models.CharField(max_length=15) phone = models.CharField(max_length=15, blank=True) email = models.EmailField(max_length=30, blank=True) instagram = models.CharField(max_length=30, blank=True) address = models.TextField(max_length=100, blank=True) The model with the foreing key to the field "name" of clients_clients is: class Budgets(models.Model): date = models.DateField(error_messages={'null': "You must set a date"}) title = models.CharField(max_length=50, unique=True) client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, to_field='name') price = models.DecimalField(default=0, decimal_places=2, max_digits=10) observations = models.TextField(max_length=200, blank=True) As is shown above, the field "name" in model "Clients" is set as unique=True. But in spite of that, the error mentioned is shown. Anyone can help me to understand why? -
How to fix Error QuerySet value for an exact lookup must be limited to one result using slicing
I am trying to get/filter a specific piece of information and delete it from data bases. This data is a many to many relationship. Here is the model: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. Here is the views: if active_session.log: print(active_session.log.values()) log_order=1 specific_log=Log.objects.filter(log_order=log_order) print(specific_log) active_session = ActiveSession.objects.get(log=specific_log).latest() active_session.log.remove(specific_log) active_session.log.add(data) print(active_session.log.values()) How can I overcome this error by narrowing down the Log data to be delete from inside the ActiveSession model -
Django Rest Framework Authentication Credentials Were Not Provided/ Invalid Token
I am using DRF and Djoser. I am able to Login and set a token (verified this by looking in Django database after user logged in) but I get the following errors when: Trying to sign up: Invalid Token Trying to retrieve data from API: Authentication credentials were not provided Code is not the best, I am simply trying to get things functional before I work on better security. Any and all help is appreciated. Below is my code: settings.py ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'project', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'django.contrib.postgres', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] serializers.py class ProjectsSerializer(serializers.ModelSerializer): class Meta: model = Project read_only_fields = ( 'created_by', 'created_at', 'updated_at', ), fields = ( 'project_title', 'project_description', 'interest_category', ) Views.py class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectsSerializer queryset = Project.objects.order_by('-created_at') permission_classes = (IsAuthenticated,) Urls.py from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("projects", ProjectViewSet, basename="projects") urlpatterns = [ path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('', include(router.urls)), ] -------------------------FRONTEND--------------------- createStore() state: { user: { username: '' }, isAuthenticated: false, token: '' }, mutations: … -
Form with default value when loading django page
I would like that when the page is loaded, a value or the default filter of the form is already triggered. In this case, I have a boolean filter that returns True or False and I wanted the True to be loaded by default because it filters items in HTMl Executado = django_filters.CharFilter(lookup_expr='exact').initial={'Executado':TRUE} -
Removing/Deleting Data in a Django Project
I have the following model with many to many relationship: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. For each ActiveSession I want to add different Log with different log_order. My desired outcome is to delete the Log in each ActiveSession if it is equal to data.log_order which means it already exists and I am trying to avoid duplication. Here is my trials that did not go through and got me different errors such as AttributeError: type object 'ActiveSession' has no attribute 'savedlogs' Here is the views.py if ActiveSession.savedlogs.values(): print("Outcome of active_session.log.values()",active_session.log.values()) # print(ActiveSession.objects.all()) if ActiveSession.Log.get(log_order=data.log_order): current_session=active_session.savedlogs.get(log_order=data.log_order) print('CurrentSession:', current_session) ------------required code to delete the Log inside the session------ else: active_session.log.add(data) print("Different Logs exists but not this log_order") else: active_session.log.add(data) print('Log added to Session') print(active_session.log.values()) To simplify and shorten unnecessary code the data.log_order is the outcome of a form which works perfectly fine. Please let me know if any clarification required. -
Making a decorator that does sum based on one field of a model in django, and also show images in template
I have encountered two challenges, one trying to do a sum with a decorator or in a generic view or in template, and other that i want to make sure images show in a browser, they were showing before but it stopped later: my model: class Accounts_revenue(models.Model): revenue_of = models.CharField(max_length=100, default='i.e: visa payment',null=False) revenue_by = models.ForeignKey(Profile, on_delete=models.CASCADE,null=True, blank=True ) amount = models.IntegerField( default='') day_on_which = models.DateField(auto_now=True, null=True, blank=True) evidence_document = models.ImageField(upload_to = 'uploads/', blank=True, default='') def __str__(self): return str(self.revenue_of) def get_absolute_url(self): return reverse('dashboard:revenue', kwargs= {'pk':self.pk} ) and my view class Accounts_revenues(ListView): template_name='dashboard/revenues.html' model= Accounts_revenue context_object_name = 'revenues' ordering = ['-day_on_which'] and in my template where i have both image and sum problem. {% for revenue in revenues %} <tbody> <tr> <td>{{ revenue.id }}</td> <td> <h2 class="table-avatar"> <a href="{{ revenue.get_absolute_url }}" class="avatar avatar-sm mr-2"><img class="avatar-img rounded-circle" src="{{ revenue.evidence_document.url }}" alt="User Image"></a> <a href="{{ revenue.get_absolute_url }}">{{ revenue.revenue_of }}</a> </h2> </td> <td>{{ revenue.expense_by }}</td> <td>{{ revenue.amount }}</td> <td>{{ revenue.day_on_which }}</td> <td class="text-right"> <div class="actions"> <a href="{% url 'dashboard:revenue_update' revenue.pk %}" class="btn btn-sm bg-success-light mr-2"> <i class="fas fa-pen"></i> </a> <a href="{% url 'dashboard:revenue_delete' revenue.pk %}" class="btn btn-sm bg-danger-light"> <i class="fas fa-trash"></i> </a> </div> </td> </tr> </tbody> {% endfor %} {% else %} <p>You seem … -
Python / Django render_to_string outpu rendered as text with html entities
I am porting a python / Django application from: Django==1.5.1 python version 2.6.6 to Django==3.2 python version 3.6.8 The issue that I am having is that I have a section of code that renders to string, a particular HTML template, and then adds that to list to output elsewhere. The actual code that produces this HTML is: class AccountAdmin(SmarterModelAdmin): list_display = ('username', 'files_url', 'teamMembers', 'roleMemberships', 'safetyLimit', 'admin_quota', 'manager', 'enabled', 'path') list_filter = ['enabled', 'manager', 'accountType'] search_fields = ['username'] inlines = [RolesInline] valid_lookups = ( 'members__member__username', 'teams__role__username', ) roles = Account.objects.filter(teams__member=account).order_by('username') roleList = [] for role in roles: link = '/admin/files/account/?teams__role__username=' + role.username # mylink = '<a href="{myurl}">'+role.username+'</a>' # linkText = format_html(mylink,myurl=link) linkText = render_to_string('common/contact.html', context={'URL': link, 'contact': role}) roleList.append(linkText) return ', '.join(roleList) roleMemberships.short_description='Roles' roleMemberships.allow_tags=True``` I have added in a logging.warn to validate what comes out of the render_to_string, and it is straight HTML. The commented out lines were something that I tried that fixed a similar issue. common/contact.html is: <a href="{{ URL }}" {% if not contact.enabled %} style="text-decoration:line-through;" {% endif %} >{{ contact.username }}</a> However, on the final render, It comes out like this: <a href="/admin/files/account/?teams__role__username=abaumann" >abaumann</a>, <a href="/admin/files/account/?teams__role__username=abaumann">abaumann</a> which when run through a browser looks like this: I …