Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Messages notifications inside a div box
When the user enter a not valid credentials it print this notificaitons message: Sorry, your password was incorrect.<br/> Please double-check your password But this doesn't look good when it is printed: I want it to be printed between the Login button and the Forgot password. Like that: So theoretically the white box should expend to the bootom to leave so place for the notifications message html file <div class="testlol2" > <div class="login-box" align="center"> <img class="logo" src="{% static 'images/testlogo.png' %}" alt=""> <div class="testlol" align="center"> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <div class="my-button"> <input class="login-button" type="submit" value="Log in"> </div> </form> {% if messages %} <ul class="messages"> {% for message in messages %} <p{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p> {% endfor %} </ul> {% endif %} <a class="forgot" href="">Forgot password?</a> </div> </div> </div> css file body{ background-color: #fafafa !important; } .messages { position: relative; top: 10px; right: 8px; color: red; } .logo { position: relative; top: 28px; left: 134px; width: 200px; } .testlol { position: relative; top: 115px; right: 90px; } .testlol2 { display:flex; justify-content: center; } .login-box { display:flex; justify-content: center; align-items: start; align-self: center; position: relative; top: 100px; background: #fff; border: 1px solid … -
justify-content disappears inside mail Django HTML
I created a function in Django to sending activation mails. Now I am styling mail, but the problem is that the justify-content: center; property inside header tag disappears in the mail message. I mean margin-bottom: 20px; display: flex; font-size: 20px; options exist there but justify-content not. def send_activation_email(user, request): email_subject = "..." email_body = render_to_string('activate.html', { ... }) email=EmailMessage(subject=email_subject, body=email_body, from_email=EMAIL_FROM_USER, to=[user.email]) email.content_subtype='html' email.send() <body style="padding: 30px; background-color: #f0f0f0;"> <div style="background-color: white; padding: 30px; border-radius: 10px; box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;"> <header style="margin-bottom: 20px; display: flex; justify-content: center; font-size: 20px;">...</header> </div> </body> -
Unresolved reference, when trying to import an app in django
I'm having problems while trying to import my app.(unresolved reference of new_app and some_page) views.py content: from django.shortcuts import render from django.http import HttpResponse def some_page(request): return HttpResponse('Hello world') In settings i've added app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'new_app' ] -
Using Postgresql in Django and wants to caculate storage of used by tables
I am using postgresql as django database now i want to calculate the storage size of my models. Like i want to calculate the storage of my model data. Can any provide a solid solution. Recently i see the example of python sys import but this didn't help me kindly provide a solid solution. -
How to Include multiple urls to one django app
In django I've an application 'users' which has a custom user model, a custom registration and profile views, How can I include the app's urls and django's default login and logout urls to the same 'users' app at the same time as below: from django.urls import path, include urlpatterns = [ path('users/', include("django.contrib.auth.urls")), # Django's default authentication urls for login and logout views path('users/', include('users.urls')), # 'users' app custom urls for the registration and profile views ] -
Unable to stop a while loop in djnago chanels after receiving a message (Trying to do a timer using while and asyncio)
I want to stop the while loop when i receive new message how can i do this I am doing this task each time receiving a message from the front end (Its Like A timer, when i press the button the timer start and if the timer == 20s or the button is pressed again the timer will restart) restarting = True i = 0 restarting = False while restarting == False : i += 1 await asyncio.sleep(1) if i == 20 or restarting == True : await self.channel_layer.group_send( self.room_group_name, { 'type': 'starting_timer', 'Timer': i, } ) break await self.channel_layer.group_send( self.room_group_name, { 'type': 'starting_timer', 'Timer': i, } ) so my problem is when i receive a message before 20s (lets say i pressed the button after 5s) the old timer keep sending messages from the old while loop and send another messages of the restarted timer I want to stop the while loop when i receive new message how can i do this -
How to count how many itens were created by day, week and month from DateTimeField()
Having the following model: class Objects(models.Model): created_at = models.DateTimeField(auto_now_add=True) How can I count how many Objects were created by day, week and month, returning an integer number for each query? -
MongoDB connection via Django connector using X.509 certificate
I have a Django API project for which I am using a MongoDB cloud database. The connection to the DB requires authentication via X.509 certificates. How do I achieve this trusted connection using the Djongo connector? Below is the Database connection configuration for my local setup. What needs to change for the CLoud connection with X.509? Thank you for your time and valuable suggestions!!! -
Boostrap Modal and loading images in Django
Firstly I am a beginner at Django but am slowly learning, I have deployed a couple of Django projects, but I have come up against a problem where I have run out of ideas on how to solve due to a lack of knowledge. I have no experience really with the frontend, I have yet to touch Boostrap (although obviously know some HTML ) or JS in detail. I am using a HTML template to build a Photography portfolio, I have a Album view with image thumbnails which work nicely and I have a href to the list of images within that Album. The problem is that template uses Boostrap Modal to open the list of images within the same page, this looks very nice and I want to try and keep it working but unsure how to pass my Django data (ie., the slug from the href ) through the modal. What I have attempted is to split my gallery-detail template which takes in the listview of the Album images filter by that album, and then include that within my main Gallery template which uses my Gallery ListView to show the thumbnails. I though the modal would work this … -
How display categories in forms only for user who created this?
I am creating app for control transaction (expense, income, budget). I want each user to be able to create their own spending categories and their own expenses. All expenses and categories created by a user are to be visible only to that user. If user A creates the category "Food123" then user B cannot see it. He can create his own such category. I've created two models - Category and Expense. class Category(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="category") class Expense(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="expense") I use a generic view when creating expenses and categories. class ExpenseListView(LoginRequiredMixin, ListView): model = Expense context_object_name = 'expense' template_name = 'expense/expense_list.html' def get_queryset(self): return self.request.user.expense.all() class ExpenseCreateView(CreateView): model = Expense success_url = '/record/expense' form_class = ExpenseForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) class CategoryCreateView(CreateView): model = Category success_url = '/record/expense' form_class = CategoryForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) What is more, I've used forms.py. class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields = ('name', 'amount', 'category') class CategoryForm(forms.ModelForm): class Meta: model = Category fields … -
django-polymorphic: Admin website error: displaying inline admin with ManyToMany using intermediate polymorphic model
I'm a django novice. It's my first Django project. As you can guess it from the title of the question, my problem is a bit long to explain. In short: I want to know how to make a basic Admin Inline display for a ManyToMany relationship with intermediate polymorphic model. I'm having an TemplateDoesNotExist at /admin/blu_forms/contactentry/e6529155-82a3-43b6-9e14-34951c88471a/change/ error. The initial idea is simple: I have two classes ContactEntry and ContactField. A contact entry can have many fields and vice-versa, so we have a ManyToMany relationship between the two. Since I want to store typed data in this relationship (because a given field is linked to typed data for a given entry - field relation) so I use an intermediate model (through model) to hold that data. The correct typing is handled with Polymorphism (django-polymorphic). This works well. I made a custom script to populate the database (PostgreSQL) and it works nicely. My issue is with the admin website. When I register ContactEntry and ContactField, I see the list of data, but when I click to see the details of a specific instance, I get an error. The correct lists of instances: And the error I get when I click for instance … -
React native face authenticaion and authorization
I have a project which I have to implement a face recognition service. Scenario is: Existing user authenticates with his face then by validating his face app or server finds out which user is trying to log in, then sends the access_token back to the userwithout entering username/password or guest user tries to register and while entering credentials app reads his/her face and sends the face credential to the backend as well. I tried to use expo-local-authentication but it doesn't give me something unique about the face it read so I can send it to backend. Is there any service or library out there? Btw backend is on django -
Trouble with create function in django using rest framework
I am a Flask developer using Django for a project I am working on... I am using rest framework in django because I am using firebase for auth and found some good advice on how to incorporate it using rest framework Problem is when I try to create a supplier for a user, you can see the error response from Postman below... Request to: http://localhost:8000/pm/createsupplier/3/ Request body: { "supplier": {"name": "Donald Duck", "phone": 111, "email": "donald@yahoo.com"} } Request response: { "email": "kbess86@gmail.com" } And the supplier is not created models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.CharField(max_length=200) email = models.CharField(max_length=200) class Supplier(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.IntegerField() email = models.EmailField() views.py: class createsuppliers(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = CreateSupplierSerializer lookup_field = 'user' serializers.py: class CreateSupplierSerializer(serializers.ModelSerializer): name = serializers.CharField(required=False, allow_blank=True, max_length=100) email = serializers.CharField(required=False, allow_blank=True, max_length=100) phone = serializers.IntegerField(required=False) def create(self, instance, validated_data): supplier_data = validated_data.pop('supplier') supplier = Supplier.objects.create(user=instance, **supplier_data) return supplier class Meta: model=Supplier fields=['name','email','phone'] -
Django CreateView form in modal not show
I have a simple CRUD for a table named Clasificacion. The problem is I would like use a Modal for insert record, but actually I don't use the Django form, instead I declared a normal form with all the fields one by one, but I would like use the From, but is not posible for me show the form content, instead the modal shows empty with the ok button.This table has a model declared as: class Clasificaciones(models.Model): clasificacion=models.CharField(max_length=30) detalles=models.CharField(max_length=1000) This is How I declared the ListView and the CreateView class ClasificacionesListView(ListView): model = Clasificaciones template_name = 'clasificacion/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Lista de clasificaciones" return context class ClasificacionesCreateView(SuccessMessageMixin, CreateView): model = Clasificaciones form_class = ClasificacionesForm template_name = 'clasificacion/index.html' success_url = reverse_lazy('clasificaciones') success_message = "Insertado correctamente!!!!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context and this is the index.html with the modal. The modal is in other directory but not works if I put in the same index.html file {% extends "starter.html" %} {% block content %} <div class="content-wrapper"> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <div class="pull-right"> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#modalAddClasificacion">Nueva clasificación</button> </div> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> … -
Disconnect all recivers of particular sender and signal than reconnect them in django
Is there any way I disconnect all receiver of a model in specific signal (like post_save) than reconnect them? # some thing like this all_receiver = collect_receivers(signal=post_save, sender=MyModelClass) post_save.disconnect(all_receiver, sender=MyModelClass) # do some work post_save.connect(all_receiver, sender=MyModelClass) seems post_save.disconnect(sender=MyModelClass) just work fine with disconnecting signals but Django documentation is not clear about what will happened if I pass just sender. and I baffled about how can I reconnect, disconnected receiver? Note that because my app is 3rd-party I don't have access to receivers but, for one of my features I have to mute all receiver connected to my model in post_save than reconnect them. -
How to fetch list of dictionary json data and show it on html page as table data
I have two columns data.One is "GLI Code" column and another is "Country" column. I need to set the “GLI Code” data in “GLI Code” column. “Country” data in “Country” column. here is my data in list of dictionary format. views file: def tables_data(request): dbfs_source_file_path = 'dbfs:/mnt/adls/MPF/Alternate_Currency_Keys_Aug.csv' local_file_download_path = './mpf_dataset.csv' dbfs_api = DbfsApi(api_client) dbfs_path = DbfsPath(dbfs_source_file_path) dbfs_api.get_file(dbfs_path, local_file_download_path, overwrite = True) df = pd.read_csv(local_file_download_path).head(5) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) return render(request, "home/tables-data.html", {'data':data}) data ouput: [{'index': 0, 'GLI Code': '15013256_U', 'Country': 'Indonesia', }, {'index': 1, 'GLI Code': '20061265_U', 'Country': 'Philippines'}, {'index': 2, 'GLI Code': '20063869_U', 'Country': 'Indonesia'}] html file: <thead> <tr> {% for i in data %} <th>{{i}}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for g in data.GLICode %} <td>{{g}}</td> {% endfor %} </tr> <tr> {% for c in data.Country %} <td>{{c}}</td> {% endfor %} </tr> </tbody> Above html code not giving me the expected output like below screenshot data. I want to set the data as below screenshot format. -
How to restore deleted table from django migrations?
I've deleted both table and 0001_initial.py migration file from a model. I didn`t think I will need this model anymore, but now I do need it. The problem is that python manage.py makemigrations doesn't create a table with the name of deleted table and therefore my migrations are only displayed in migrations files. But they don`t affect database. How can I create or restore that table again or should I delete the whole database and restore everything afterwards? Thanks in advance! -
self.scope['user'] always returns AnonymousUser in websocket
I have researched similar questions but can't find an answer that works for me. I would like to get the username or user_id from a session when a user connects to a websocket. This is what I have in consumers.py: import json from channels.consumer import AsyncConsumer from time import sleep import random import redis from django.conf import settings from django.contrib.auth.models import User, AnonymousUser from channels.db import database_sync_to_async from asgiref.sync import async_to_sync from rest_framework.authtoken.models import Token from channels.middleware import BaseMiddleware redis_instance = redis.StrictRedis(host=settings.REDIS_HOST_LAYER, port=settings.REDIS_PORT_LAYER, db=0 ) class PracticeConsumer(AsyncConsumer): async def websocket_connect(self, event): print('session data', self.scope['user']) await self.send({"type": "websocket.accept", }) ... @database_sync_to_async def get_user(self, user_id): try: return User.objects.get(username=user_id).pk except User.DoesNotExist: return AnonymousUser() This is my asgi.py: """ ASGI config for restapi project. It exposes the ASGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'signup.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ) ) }) and the user login function + token sent when user logs in: class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass user = authenticate(**authenticate_kwargs) if not user: return { 'user': 'Username or password is incorrect', } … -
Why are the items not appearing in the table?
I'm creating a point of sale using Django, a part arrived here that the items are not showing up, since I already registered them... Could someone help me? A note: I'm Brazilian, my code is in the language, but I think there will be no problems. Here's the codes: This is the models part, which is inside the 'registration' app. I want this information to appear in another app called 'pages' inside, of course, the folder called 'templates'.. from django.db import models class ListaProdutos(models.Model): nome_produto = models.CharField(max_length=50, verbose_name='Produto') quantidade_produto = models.IntegerField(verbose_name='Qntd.') custo_venda = models.CharField(max_length=10, verbose_name='Custo/Venda') fornecedor = models.CharField(max_length=50, verbose_name='Fornecedor') data_adicao = models.DateTimeField(verbose_name='Data de Adição') def __str__(self): return "{} {} {} {} {}".format(self.nome_produto, self.quantidade_produto, self.custo_venda, self.fornecedor, self.data_adicao) class ListaDespesas(models.Model): nome_despesa = models.CharField(max_length=50, verbose_name='Despesas') quantidade_despesa = models.CharField(max_length=50, verbose_name='Qntd.') custo = models.IntegerField(verbose_name='Custo') tipo_gasto = models.CharField(max_length=50, verbose_name='Tipo de Gasto') data_atualizacao = models.DateTimeField(verbose_name='Data de Atualização') def __str__(self): return "{} {} {} {} {}".format(self.nome_despesa, self.quantidade_despesa, self.custo, self.tipo_gasto, self.data_atualizacao) Still in the 'registration' app, only in the urls part: from django.urls import path from .views import ProdutoCreate, DespesaCreate from .views import ProdutoUpdate, DespesaUpdate from .views import ProdutoDelete, DespesaDelete from .views import ProdutoList, DespesaList urlpatterns = [ path('cadastrar/produto', ProdutoCreate.as_view(), name='cadastrar-produto'), path('cadastrar/despesas', DespesaCreate.as_view(), name='cadastrar-despesa'), path('editar/produto/<int:pk>/', ProdutoUpdate.as_view(),name='editar-produto'), path('editar/despesa/<int:pk>', DespesaUpdate.as_view(),name='editar-despesa'), path('excluir/produto/<int:pk>/', … -
Django Rest Framework Field Validation Issue
My subscription view is located inside of UserViewSet. I'm wondering why I'm getting IntegrityError at /api/users/1/subscribe/ new row for relation "users_subscription" violates check constraint "prevent_self_subscription" DETAIL: Failing row contains (11, 1, 1). instead of proper json answer. Somehow SubscriptionSerializer field validation doesnt wish to work. Any thoughts? models.py class Subscription(models.Model): user = models.ForeignKey( User, related_name='subscriber', on_delete=models.CASCADE) author = models.ForeignKey( User, related_name='subscribing', on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'author'), name='unique_subscription' ), models.CheckConstraint( check=~models.Q(user=models.F('author')), name='prevent_self_subscription' ) ] serializers.py class SubscriptionSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = models.Subscription fields = ('author', 'user', ) validators = [ serializers.UniqueTogetherValidator( queryset=models.Subscription.objects.all(), fields=['author', 'user', ] ) ] def create(self, validated_data): return models.Subscription.objects.create( user=self.context.get('request').user, **validated_data) def validate_subscribing(self, value): if self.context.get('request').user == value: raise serializers.ValidationError( 'You cant subscribe to yourself!') return value views.py @action(['post'], detail=True) @permission_classes(permissions.IsAuthenticated) def subscribe(self, request, *args, **kwargs): author = get_object_or_404(models.User, id=kwargs['id']) data = request.data.copy() data.update({'author': author.id}) serializer = serializers.SubscriptionSerializer( data=data, context={'request': request}) if request.method == 'POST': serializer.is_valid(raise_exception=True) serializer.save() return Response( status=status.HTTP_201_CREATED, data=self.get_serializer(author).data) -
Resolving a ForeignKey field pointing to the model it belongs to
I have a model class in Django which has a ForeignKey referencing the model it actually belongs to: class Foo(models.Model): name = models.CharField(max_length=256, verbose_name="Name") #... some other fields bar = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True ) def __str__(self): return self.name I want to add a custom method in that class which resolves, on the fly, the name in a new field, e.g. bar_resolved when instantiating it in a QuerySet in a view: from .models import Foo foo = Foo.objects.all() # do stuff I've tried this: class Foo(models.Model): name = models.CharField(max_length=256, verbose_name="Name") #... some other fields bar = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True ) # preparing the resolved bar field which should contain the 'name' value corresponding to the id: bar_resolved = models.CharField( max_length=256, verbose_name="Bar name resolved", null=True ) def __str__(self): return self.name def resolve(self): if self.bar: self.bar_resolved = self.bar.name return super(Foo, self).resolve() Then in my view: from .models import Foo foo = Foo.objects.all() foo.resolve() but it raises: 'QuerySet' object has no attribute 'resolve' How could I achieve that? and do I need to hard code a 'resolved' field in my model for that? -
How should i insert html input data into a django database
i cant figure out how to fix this problem. Im trying to insert some data from a html form into a small simple django database sqllite if im right. i tried to follow tutorials and did allot of searching online but it seems like i've hit tutorial hell. my question is: How can i achieve putting data from the text input field on the html file into the django database. Hers what ive got sofar: the HTML: <h1>Create a Post </h1> <form action="" method="POST"> {% csrf_token %} artiest: <input type="text" name="artiest"/><br/> song: <br/> <textarea cols="35" rows="8" name="song"> </textarea><br/> <button type="submit" value="Post"/> </button> </form> the views.py def check(request): post=Post() post.artiest= request.POST.get('artiest') post.song= request.POST.get('song') post.save() return render(request, 'spotifylist/check.html') the models.py class Post(models.Model): artiest = models.CharField(max_length=100) song = models.CharField(max_length=100) naam = models.CharField(max_length=100) link = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.artiest -
Duplicate instances not removed from queryset
I'm coming across a problem with the queryset returned in the get_tag_posts method within the Profile model. With the query as it is written, it won't remove duplicates even though .distinct() is being invoked. To provide a brief illustration of the problem: Question 1 - Tag A Question 2 - Tag A Question 3 - Tag A, Tag B As get_tag_posts is invoked it includes the following queryset: <QuerySet [<Tag: A>, <Tag: A>, <Tag: A>, <Tag: B>]> Yet I'm expecting the queryset to be returned as: <QuerySet [<Tag: A>, <Tag: B>]> From there each instance is annotated to calculate the number of times a given tag has been posted by a user. Why are duplicates of a single instance not being removed in this case? class Profile(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) def get_tag_posts(self, order_by=None): if not order_by: order_by = "-question__date" elif order_by == "name": pass else: order_by = "-score" questions_with_tag = Subquery(self.questions.filter( tags__name=OuterRef("name")).only('id')) tags = Tag.objects.filter( question__profile=self ).distinct().order_by(order_by) return { 'records': tags.annotate(times_posted=Count(questions_with_tag)), 'title': f"{tags.count()} Tags" } class Tag(Model): name = CharField(unique=True, max_length=25) class Post(Model): body = TextField() date = DateTimeField(default=timezone.now) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) vote = GenericRelation( 'Vote', related_query_name="%(class)s" ) … -
Django list_editable with custom method in list_display
I'm trying to do inline editing for list. I have the column language, which i use a custom method get_language to display how i want. from django.contrib import admin from .models import * class MovieAdminModel(admin.ModelAdmin): search_fields= ('title_en') list_display = ('get_language',) list_editable = ('get_language') def get_language(self, obj): if obj.language==1: return 'Persian With English Subtitle' else: return 'Persian' get_language.admin_order_field = "language" get_language.short_description = "language" When i use get_language in list_editable an error is returned because get_language is not in the Model, language is. If i use language in list_editable, says it isn't defined in list_display. How do i solve this? -
Django view - redirect to one page and open another in new tab
I have a Django view that looks like this: def edit_view(request, pk) # do something ... messages.success(request, "Success!") return redirect('index') The view should redirect to "index" (like in the code above), but it should also, at the same time, open another (second) page in new tab. How can this be achieved?