Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem generating dynamic HMTL with python
I have a WebApp that it generated a dynamic html depending on logged user. The problem is sometimes open mes.html page but that is completely empty, and I see white on browser, and the code of this file is completely empty. But many times that work properly. What can to be the problem? def calendario(request): miCalendario = FormularioCalendario(request.POST) aino = 2023 usuario = request.user.id user = User.objects.get(id=usuario) if request.method=='POST' and ('cargar' in request.POST): miCalendario = FormularioCalendario(request.POST) obtener_mes(miCalendario.data['mes'],aino,user) return render(request, "BieleGastosApp/mes.html", {"calendario": miCalendario}) return render(request, "BieleGastosApp/calendario.html", {"calendario": miCalendario}) def obtener_mes(mes, aino,usuario): mem_sem=0 aino= 2023 res_mes = [] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) mes_file = os.path.join(BASE_DIR, 'BieleGastosApp/templates/BieleGastosApp/mes.html') f = open(mes_file,'w') html=""" {% extends "BieleGastosApp/base.html" %} {% load static %} {% block content %} <div align="center"> <form action="" method="POST" > <table> {{ calendario.mes }} </table> <div> <p> --------------------- </p> </div> <input class="boton" type="submit" value="Cargar" name="cargar"> {% csrf_token %} </form> </div> <div align="center"> <table width="50%" border="0" align="center" id="mes_calendario"> <th> <td align='center'>Lun </td> <td align='center' >Mar </td> <td align='center'>Mie </td> <td align='center'>Jue </td> <td align='center'>Vie </td> <td align='center'>Sab </td> <td align='center'>Dom </td> </th> """ #user = Usuario.objects.get(autor= usuario) for i in range (1,32,+1): horas_viaje = 0 viaje_opacity=0.0 horas_trabajo = 0 trabajo_opacity=0.0 pernocta_opacity=0.0 gastos_opacity = 0.0 fecha = … -
can't login after creating a user in django, login function returns none
after I created a user in Django I then tried to login but can't. i don't if its a setting that needs to be done or the problem is with the code. this is my sign-in views # def signin(request): if request.method == 'POST': email = request.POST.get('email') pass1 = request.POST.get('password1') user = authenticate(email=email, password=pass1) if user is not None: login(request, user) fname = user.first_name return render (request, 'store.html', {'fname':fname}) else: messages.error(request, 'invalid password or email') return render (request, 'signin.html') return render (request, 'signin.html') and sign-up views the pass2 says variable not accessed def signup(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] myuser = User.objects.create_user(username, email, pass1, ) myuser.first_name = fname myuser.last_name = lname myuser.save() return redirect ('signin' ) return render(request, 'signup.html') this is my signup.html <form method="post" action="signup"> {% csrf_token %} <div class="mb-3"> <label for="" class="form-label">Account name</label> <input type="text" class="form-control" id="username" name="username" placeholder="account name" required> </div> <div class="mb-3"> <label for="" class="form-label">Email address</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp" name="email" placeholder="Enter email address" required> </div> <div class="mb-3"> <label for="" class="form-label">First name </label> <input type="text" class="form-control" id="fname" name="fname" placeholder="First name " required> </div> <div class="mb-3"> <label for="" class="form-label">Last … -
Django static files not found when I try to specify favicon
I'm developing my first Django website. I have an issue with static files. In my homepage I linked my logo with this code. <img class="d-block mx-auto mb-4" src="{% static 'mysite/images/logo.png' %}" alt="" width="300" height="225"> It was perfectly ok. When I tried to change my favicon and tried to link another .png file from the static folder, it can't find the favicon png image. <link rel="shortcut icon" href="{% static '/mysite/images/logo.png' %}" > I don't know why it doesn't detect the favicon while getting the logo. My settings.py file: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') If I try to link another pictures It can't find. Only my logo.png is available. -
Django consumer frequently get disconnected and reconnected on different pods on K8S
big brothers! I deployed my Django app on K8S pods. I implemented websocket server with websocket consumer using Django channels package. And the problem is, I found K8S would frequently close and reconnect websocket connection, that's to say K8S would frequently new consumer objects on the same websocket connection URL on different pods. I have cached data inside consumer object, and this situation really bothers. How can I keep websocket connection in K8S? -
Django composite Key
I have a table called "Tickets" and exact copy of this same table called "Logs" .The aim is to copy every data into "Logs" . So to keep the structure same I need to exclude Django default generated field "id" and planned to use a composite key with field name "ticket_no" and "updated_on". is there any way to make these field as primary key without this 'id'. -
Adding a Threaded Comment functionality in my Django blog using FETCH API
Please I am stuck on a problem I've been trying to solve by myself for up to a month now. I am at my wit's end. So I have a Django blog and I am trying to implement a threaded comment functionality using FETCH API to avoid a page refresh each time a comment is submitted. Also, I intend to limit the number of comments shown first to just 10 with a "load more comments" button at the bottom that when clicked would reveal the next 10 comments, and so on until there is no more comment to be shown at which point the "load more comments" button disappears. You see, I successfully implemented this feature with FETCH API for only single parent comments. But I am trying to take my blog further by adding a threaded comment, or rather, to make it possible for parent comments to have child comments. However, I can't seem to successfully implement the above functionalities asynchronously. Only after reloading the page do the parent comments and child comments show on the page, but I want the comments to show immediately after hitting the comment submit button. I believe the problem is with my Javascript … -
How to make text remain on page even after user exits and opens again?
Using js,it is possible to make text remain on screen when user submits the text, but I want that it remains even after user exits or lets say opens the website on a different device. I think databases would be involved. Can we use Django for this purpose? I am trying to make a website like a common notepad type thing. Anyone who opens the site can add text and leave and it stays there until he himself or any other person removes the number. How should I proceed with this idea? -
Javascript function doesn't change the color of the button back after spamming the button
I'm creating Django-RestFramework app, but it's not that important. In one of my templates i've created keyboard (bootstrap buttons) because User there has to type specific letters. I also created JS function that listens for keyboard clicks and then flashes corresponding button on the screen. After 0.2s button's color gets back to original state, but im getting some kind of error: When I hold the button, color is changing and then it's not going back into original state. Any advices? template: {% extends 'base.html' %} {% block content %} <div class="boxes-row"> {% for i in '12345' %} <div class="d-flex justify-content-center align-items-center"> {% for letter in word.word %} <div class="word-box"> </div> {% endfor %} </div> {% endfor %} </div> <div class="keyboard"> <div class="row mt-4"> <div class="col-md-6 offset-md-3"> <button class="btn btn-outline-success btn-lg top" id="buttonQ">Q</button> <button class="btn btn-outline-success btn-lg top" id="buttonW">W</button> <button class="btn btn-outline-success btn-lg top" id="buttonE">E</button> <button class="btn btn-outline-success btn-lg top" id="buttonR">R</button> <button class="btn btn-outline-success btn-lg top" id="buttonT">T</button> <button class="btn btn-outline-success btn-lg top" id="buttonY">Y</button> <button class="btn btn-outline-success btn-lg top" id="buttonU">U</button> <button class="btn btn-outline-success btn-lg top" id="buttonI">I</button> <button class="btn btn-outline-success btn-lg top" id="buttonO">O</button> <button class="btn btn-outline-success btn-lg top" id="buttonP">P</button> </div> </div> <div class="row mt-1"> <div class="col-md-6 offset-md-3"> <button class="btn btn-outline-success btn-lg mid" id="buttonA">A</button> … -
Why do we need to install pytz package when we want to use Django with MondoDB?
After many research, i found that to use Django with MongoDB, we have to install pytz and downgrade pymonngo to 3.12.3, because the new version of pymongo (4.0 from 29.11.2021) is not supported by Djongo 1.3.6. But what's the interest of pytz ? When i try to use Django with MongoDB without installing pytz, it doesn't work. -
How do I fix a database configuration error when securing Django Admin with two factor authentication using custom user model and database?
I am trying to add two factor authentication to the Django Admin Site as an extra layer of security using django-otp (version 1.2.2) and qrcode (version 7.4.2). Both have been installed as part of django-two-factor-auth (version 1.15.4). Furthermore, I have set up a custom user model in a custom Postgresql database. For the setup of the custom user model and database, I followed the tutorial Django Real Estate App Using Multiple Users & Databases by Brian Brkic (especially parts 1, 2, 3, and 10). For the implementation of the two factor authentication, I have started with the tutorial Towards Django Two Factor Authentication Integration by Very Academy, but continued with Django Two Factor Authentication Example because I thought I could avoid all the extra forms. The migration to the custom database python manage.py migrate --database=users worked well and the Admin Site at localhost:8000/admin is presented properly, including the field for the OTP code. However, when I fill in the username, password and OTP code in the login form and hit send, I get the error ImproperlyConfigured at /admin/login/ settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I came across this type of error … -
I have tried to submit the form in django but only redirection function is working data is not showing in django admin
My views.py are def login_register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] password=request.POST['password'] # check for errornous inputs #create the user myuser=User.objects.create( first_name=first_name, last_name=last_name ) myuser.save() return redirect('shophome') return render(request, 'shop/login.html') my urls.py are urlpatterns = [ path('', views.index, name='shophome'), path('product-list/', views.product_list, name='product_list'), path('product-detail/', views.product_detail, name='product_detail'), path('cart/', views.cart, name='cart'), path('checkout/', views.checkout, name='checkout'), path('my-account/', views.my_account, name='My_account'), path('contactus/', views.contactus, name='contactus'), path('wishlist/', views.wishlist, name='wishlist'), path('login/', views.login_register, name='login_register'), ] I have tried to submit the form with post method but its not working. when i submit the form it should redirect to home page and data should save in django admin but only redirection is working. -
Django Database Routing using USER from request
I am trying to implement a PER USER database routing in Django and things are not going that smoothly. This is what I have right now and IT WORKS but I was wondering if there is anything better for what I want : class DatabaseMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if (str(request.company) == 'company1'): request.database = 'COMPANY_X' else: request.database = 'default' response = self.get_response(request) return response #THIS HAS SECURITY RISKS BUT I DONT THINK THERE IS SOMETHING BETTER OUT THERE FOR NOW from threadlocals.threadlocals import get_current_request class UserDatabaseRouter: def db_for_read(self, model,user_id=None, **hints): request = get_current_request() if(not (request is None)): return request.database else: return None def db_for_write(self, model,user_id=None, **hints): request = get_current_request() if(not (request is None)): return request.database else: return None -
Django with Postgres - Sub query slow
Django Postgres - Sub query slow Hello, I want to select players with their current location (not in the futur and closest from now) ordered by Player.registered_at. I also want to filter the Player regarding their current location with DRF. Here are my models : class Player(models.Model): class Meta: indexes = [ models.Index( fields=["closed", "deleted"], condition=Q(closed=False, deleted=False), name="opened_player_index", ) ] registered_at = models.DateTimeField(_("registerd at"), db_index=True) name = models.CharField(max_length=100) closed = models.BooleanField(_("closed"), default=False) deleted = models.BooleanField(_("deleted"), default=False) class Location(models.Model): name = models.CharField(max_length=100) class PlayerLocation(models.Model): class Meta: indexes = [ models.Index( fields=["player", "active_since", "location"], name="player-active-since-location", ) ] active_since = models.DateTimeField(_("active since"), db_index=True) player = models.ForeignKey( Player, on_delete=models.PROTECT, related_name="locations" ) location = models.ForeignKey( Location, on_delete=models.PROTECT, related_name="+" ) Here is my query : class PlayerQuerySet(models.QuerySet): def with_location(self): # Get current healthcare facility as SubQuery current_player_location = PlayerLocation.objects.filter( player_id=OuterRef("pk"), active_since__lte=Now() ).order_by("-active_since") return self.annotate( # add current location of player queryset lookup_location=Subquery( current_player_location.values("location")[:1] ), location_name=Subquery( current_player_location.values("location__name")[:1] ), ) Here is the output of the explain analyze postgres query (for the count) : EXPLAIN ANALYZE SELECT COUNT(*) AS "__count" FROM "player" WHERE ( NOT "player"."closed" AND NOT "player"."deleted" AND ( SELECT U0."location_id" FROM "player_location" U0 WHERE ( U0."active_since" <= (STATEMENT_TIMESTAMP()) AND U0."player_id" = ("player"."id") ) ORDER BY … -
postgresql unittest db and django
HI I'm making test code but I have a problems... this is my django settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "name", "USER": "user", "PASSWORD": "passwd", "HOST": IP, "PORT": port, "ATOMIC_REQUEST": True, "TEST": { "NAME": "test_db", }, } } and my test code class TestPreprocessAPI(APITestCase): preprocess_data = factories.PreprocessDataFactory() def test_get_preprocess_data(self): url = reverse("url") response = self.client.get(url) data = response.json() self.assertEqual(response.status_code, 200, "status code is not 200") self.assertIsInstance(data, list) the temperate test data store in production db "settings.py's default db" not "TEST settings test db" why this happen? and how can I use test db I checked test db made I checked my postgresql auth -
Getting custom User details from access token in API(DJANGO)
I am a novice in Django and have started learning about jwt authentication implementation in django. I have successfully obtained access token and refresh token on successful login (username and password) by a user. Now, if I want to get the same user details like email, username and his mobile number when he clicks on some button from frontend, how to do it? Does the returned token from backend gets stored in frontend so that I can send it in the fetch function OR is there any way to get access to that token in another APIView in backend? I have tried every code provided in the answers for the similar question but not getting the result. Please help me in understanding this and as well as the code to implement it. -
Redirect a indexed broken url to new one in python django- nginx server
I've a python-django projet & it's hosted in AWS- nginx server. recently we chnaged the filename but whenever someone searching the old file (that is indexed in google) shows. it throws 404 error. how will I redirect old url(indexed one ) to new one. ie: "www.example.com/logistics-services-odisha" to "www.example.com/logistics-services-in-odisha" please help me. this is urgent. we are trying it in robots.txt but no clue more -
Way to Return a Return [closed]
Is there any way to achieve return a return? This way I can achieve return from nested functions. I achieved by returning in if block and returned None as default. def inner_function(user): if isinstance(user, User) and not is_admin(user): return HttpResponse("Access Forbidden!", status=403) def outer_function(model_instance, param1, param2): response = inner_function(model_instance) if response is not None: return response """ ...codes """ outer_function(model_instance) -
AttributeError: module 'django.db.models' has no attribute 'PriceRanges' [closed]
Getting the error when trying to execute django admin command as per code below. This runs no problem if I render it to html but getting the error when trying to execute through command line. Ignore the ''' around the code, couldnt see another way to allow this page to submit the question. Folders: project General management # (inc __init__.py) commands # (inc __init__.py) data_import.py # command file __init__.py migrations templates models.py view.py etc... data_import.py from django.core.management.base import BaseCommand, CommandError from django.contrib import admin from django.db import models from General.models import PriceRanges class Command(BaseCommand): help = 'Run the data import process' def handle(self, *args, **options): all_ranges = models.PriceRanges.objects.all() self.stdout.write(all_ranges) models.py from django.db import models class PriceRanges(models.Model): price_range_id = models.CharField(primary_key=True, max_length=36) price_range_from = models.IntegerField(blank=True, null=True) price_range_to = models.IntegerField(blank=True, null=True) price_range_increment = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.price_range_from}, {self.price_range_to}, {self.price_range_increment}" class Meta: managed = False db_table = 'price_ranges' db_table_comment = 'Define the search price ranges and increments' execute command in terminal - python manage.py data_import error details: all_ranges = models.PriceRanges.objects.all() ^^^^^^^^^^^^^^^^^^ AttributeError: module 'django.db.models' has no attribute 'PriceRanges' Any help would be very appreciated. -
Django Channels SSE messages are hit or miss unpredictably
I am building an app with general django views and DRF views for a Flutter app for the same features. I also have django-channels for sending notifications to clients through Server Sent Events. I have inherited from AsyncHttpConsumer for the SSE consumer and locally everything works perfectly fine. The entire project is a docker compose setup quickstarted with cookiecutter-django, with redis, celery, django, traefik, and some other containers. In my django and DRF views, I call a function I created in the User model to send notifications where I send messages to the channel layer through the group name. Locally all messages are received as it should, but when I perform the same actions in a staging environment, the messages are a hit or miss. Without any apparent pattern, sometimes messages arrive as it should, other times only one out of 4-5 attempts work, and even other times, none do. I use the JavaScript EventSource to handle incoming messages. From the django logs, I can see 4 workers and some debug statements show that one (varying each time) worker receives the event, while the rest prints empty content. (The consumer checks if the message is actually for the user in … -
how to split Django urls.py into multiple files
I have a function based view in my app, and I am trying to split my urls.py as follows my_app / |- urls |- __init__.py |- dogs.py |- cats.py |- views |- __init__.py |- dogs |- index.py ... # my_app/urls/__init__.py from .dogs import urlpatterns as dog_urls from .cats import urlpatterns as cat_urls app_name = "pets" urlpatterns = dog_urls + cat_urls # my_app/urls/dogs.py from .. import views urlpatterns = [ path("dogs/", views.dogs.index, name="dogs") ... ] With this set up I am getting this error django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pets.urls' (namespace)>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. I do not see where in my code I am creating a circular dependency, nor do I understand what I am doing wrong with urlpatterns. -
PeriodicTask model not creating in some conditions #676
I'm using Django 4.2 with django-celery-beat 2.5.0. I had no trouble creating PeriodicTasks and they were running properly. But 2 days ago, without any related changes, just some of my tasks are not being created. These tasks has a name with pattern of task_*. Note that my other tasks(other patterns) are being created using PeriodicTask model normally. I get no error when creating my tasks, I also log the periodic task ID in EFK but In the database there is no such ID. This is how I create my tasks: schedule, _ = IntervalSchedule.objects.get_or_create( every=repeat_every, period=IntervalSchedule.SECONDS, ) periodic_task = PeriodicTask.objects.create( interval=schedule, name=self.data.get("task_name"), task="my_app.tasks.call_services_periodic_task", args=json.dumps([ self.data.get("v1"), self.data.get("v2"), self.data.get("v3"), self.data.get("v4"), self.data.get("v5"), ]), start_time=timezone.now() + datetime.timedelta(seconds=self.data.get("start_in")), ) print(periodic_task.id) And it prints the periodic task ID. But it is not in the database. How can I fix the issue? Any help would be appreciated, Thank you very much -
Django Logger - writing logs in different files
These are the parameters I have inside my LOGGING in a Django REST Framework project. I have set logs everytime I shoot an email, and everytime I catch an error, I would like it to log into my error file and debug stuff into my debug.log file. However, I get error logs in both files, while I only get debug in my email debug.log file. "handlers": { "invitation_email_info": { "level": "DEBUG", "class": "logging.FileHandler", "filename": "projectname/logs/invitation/.debug.log", "formatter": "verbose" }, "invitation_email_error": { "level": "ERROR", "class": "logging.FileHandler", "filename": "projectname/logs/invitation/.error.log", "formatter": "verbose" }, }, "loggers": { "Invitation": { "handlers": ["invitation_email_info", "invitation_email_error"], "level": "DEBUG", "propagate": False, }, I tried playing around and was thinking if I should create more loggers, one for Invitation_Debug and one for Invitation_email. Please let me know. Thanks. -
getting error when integrating ccavenue in my django project
# ccav_app/ccav_utils.py from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import padding as sym_padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend import base64 import os def pad(data): padder = padding.PKCS7(128).padder() padded_data = padder.update(data) + padder.finalize() return padded_data def unpad(data): unpadder = padding.PKCS7(128).unpadder() unpadded_data = unpadder.update(data) + unpadder.finalize() return unpadded_data def derive_key(secret_key): salt = os.urandom(16) # Generate a random salt (16 bytes) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), iterations=100000, salt=salt, length=32, # Use 32 bytes for a 256-bit key backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(secret_key.encode())) return key def encrypt(plain_text, secret_key): key = derive_key(secret_key) iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend()) encryptor = cipher.encryptor() encrypted_text = encryptor.update(plain_text.encode()) + encryptor.finalize() return base64.b64encode(iv + encrypted_text).decode() def decrypt(cipher_text, secret_key): key = derive_key(secret_key) data = base64.b64decode(cipher_text.encode()) iv = data[:16] cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend()) decryptor = cipher.decryptor() decrypted_text = decryptor.update(data[16:]) + decryptor.finalize() return unpad(decrypted_text).decode() this is my ccavutil.py file where i am gettig data and secret key through encrypt and decrypt but getting error ValueError at /cc/ Invalid key size (352) for AES. Request Method:POSTRequest URL:http://127.0.0.1:8000/cc/Django Version:4.2.1Exception Type:ValueErrorException Value:Invalid key size (352) for AES. I want to integrate the ccavenue payment gateway in my website … -
Dockerized Django application not accessible on specified port
I have a Django application running inside a Docker container on my server. I am trying to access it via a specific port, but it's not working as expected. Here are the relevant details: Dockerfile (CMD section): CMD ["python", "manage.py", "runserver", "0.0.0.0:9000"] Jenkins Pipeline (part of the Jenkinsfile): stage('Build and Deploy') { steps { script { // Build the Docker image sh 'docker build -t my-django-app -f Dockerfile .' // Stop and remove the existing container (if any) sh 'docker stop my-django-container || true' sh 'docker rm my-django-container || true' // Run the Docker container sh 'docker run -d --name my-django-container -p 9000:9000 my-django-app' } } } Additionally, I've allowed port 9000 through the firewall using the following command: sudo ufw allow 9000/tcp My Jenkins server is publicly available at ip:8080, but when I try to access my Django application at ip:9000, it doesn't work. I'm relatively new to Docker, and any assistance in troubleshooting this issue would be greatly appreciated. -
How to test Django with multiple broswers together with Selenium to reduce the code?
I installed pytest-django and selenium in Django as shown below. pip install pytest-django && pip install selenium Then, I created pytest.ini, test.py and __init__.py(Empty file) in tests folder as shown below: django-project |-core | └-settings.py |-my_app1 |-my_app2 |-pytest.ini └-tests |-__init__.py └-test.py Then, I set the code below to pytest.ini: # "pytest.ini" [pytest] DJANGO_SETTINGS_MODULE = core.settings testpaths = tests Finally, I could test Django (Admin) with the multiple browsers Google Chrome, Microsoft Edge and Firefox separately but not together with Selenium as shown below so the code is a lot: # "tests/test.py" import pytest from selenium import webdriver from django.test import LiveServerTestCase """ Google Chrome Test Begin """ @pytest.fixture(scope="class") def chrome_driver_init(request): chrome_driver = webdriver.Chrome() request.cls.driver = chrome_driver yield chrome_driver.close() @pytest.mark.usefixtures("chrome_driver_init") class Test_URL_Chrome(LiveServerTestCase): def test_open_url(self): self.driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in self.driver.title """ Google Chrome Test End """ """ Microsoft Edge Test Begin """ @pytest.fixture(scope="class") def edge_driver_init(request): edge_driver = webdriver.Edge() request.cls.driver = edge_driver yield edge_driver.close() @pytest.mark.usefixtures("edge_driver_init") class Test_URL_Edge(LiveServerTestCase): def test_open_url(self): self.driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in self.driver.title """ Microsoft Edge Test End """ """ Firefox Test Begin """ @pytest.fixture(scope="class") def firefox_driver_init(request): firefox_driver = webdriver.Firefox() request.cls.driver = firefox_driver yield firefox_driver.close() @pytest.mark.usefixtures("firefox_driver_init") …