Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter a Django model by properties of a reverse foreign key
I need to filter a Django model based on properties of a reverse foreign key and I'm not sure of the best way to do this. I have two models in which Products belong to a ProductRange class ProductRange(models.Model): pass class Product(models.Model): product_range = models.ForeignKey(ProductRange, related_name="products") is_archived = models.BooleanField() Product Ranges in which all products are set is_archived=True are to be considered archived, if any products are not marked as archived they are not considered archived. I need a way to filter Product Ranges based on this, i.e a filter that returns product ranges for which all products are archived. I'm aware I can filter by the related name: ProductRange.objects.filter(products__is_archived=False) However this returns product ranges where Any product is archived no all products. I'm also aware I can do the filtering in Python but I need this filter work on a large dataset and I'm sure there is a more efficient way to do this in the database. I've also considered using models.Subquery or models.Exists, however I feel like there is probably a simpler and more performant way of doing this that I am missing, also this would require a lot of refactoring to avoid a circular import. I feel … -
How to customize UI of Swagger (drf-yasg) to use dark mode?
So we have done our Django API documentation setup using drf-yasg, and I was wondering if it's possible to use dark mode in the documentation screen. For reference, the screen looks something like this: -
AttributeError: 'WSGIRequest' object has no attribute 'tenant'
I'm using django-tenants, following the Installation Guide, and I've created a simple project. Here's the scenario: I have a model named UnVerifiedTenants that stores company data, including their email and tenant ID. class UnVerifiedTenants(models.Model): """ model that Saves user email, depending upon below points 1. all emails from tenants for proper tenant utilization 2. all emails who just enquired and did not proceed further """ tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(verbose_name="Email Address", unique=True) admin = models.BooleanField("Is user admin", default=False) created_on = models.DateField(auto_now_add=True) updated_on = models.DateField(auto_now=True) When users create their accounts on the registration page, the data is stored in this model. After users verify their phone number (which is stored in a different table), I migrate their schema. After completing the migration, they enter their email on the login page. I check their email, retrieve their schema, and create a URL to redirect them to their tenant domain for further authentication: class Login(generic.TemplateView): form_class = InitialAuthenticationForm template_name = "login.html" def post(self, request, **kwargs): email = request.POST["email"] scheme = "https" if self.request.is_secure() else "http" domain = settings.DOMAIN shared_user = AllUsersEmails.objects.filter(email=email).first() if shared_user: tenant_obj = shared_user.tenant try: tenant = tenant_obj.schema_name sub_url = f"accounts/enter-password/{encrypt(email.encode()).decode()}" url = f"{scheme}://{tenant}.{domain}/{sub_url}" shared_user.update_last_login() return redirect(url) … -
Django - large file upload - moving file from temp folder to final destination fails
Stumbled upon this error when upgrading Python, Django and Alpine to latest versions... and it's a weird one. The error occurs when I upload a file that is larger than FILE_UPLOAD_MAX_MEMORY_SIZE (set to 5MB). I have two development environments set up. One is local dev server (just normal py manage.py runserver), the other one is running under Docker(Windows) + Alpine linux + Apache2 + mod_wsgi which is also still a 'development' environment. This error occurs only under Docker environment and only when file exceeds max memory size. Under all other circumstances the upload works - even when file exceeds memory limit on local dev server. The error: Saving new order file to: customer_name/_web_portal/PendingOrders/7935/zip_03.zip Internal Server Error: /b2b_api/orders/ Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/code/api/views.py", line 352, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise … -
DRF APITestCase but HttpResponseNotFound status_code=404
Hi I'm trying to make unittest by django and DRF but I have a problem when running test the below code is my tests, views, models code I check urls and runserver too and they work well. I need your help. tests.py class TestCohorts(APITestCase): def setUp(self): models.Cohort.objects.create(code=COHORT_CODE) def test_cohort(self): response = self.client.get("api/v1/cohort") print(response) data = response.json() self.assertEqual(response.status_code, 200, "status code is not 200.") views.py class CohortList(ListAPIView): queryset = models.Cohort.objects.all() serializer_class = serializers.CohortSerializer models.py class Cohort(models.Model): code = models.CharField(max_length=30) def __str__(self) -> str: return f"{self.code}" class Meta: db_table = "cohort" -
Should I render dynamic charts in Django or serve them from another webapp?
Here is this Django webapp hosted in a Apache2 server with mod_wsgi My question is: How do I add dynamic graphs to my webapp? In producion, in order to serve files, Nginx reverse proxy server catches the urls with the /static/ subdomain and serves the content (otherwise the request is redirected to apache) Google returns planty of ways to address the matter. Do you have any recomandation or relatable experience that I should know before choosing any? My concerns are: How clients update graph data without refreshing the whole page ? (I currentlly use htmx for rendering html) Should I use a second webapp to serve the content to nginx redirect? Is django-plotly-dash the most straight way? Will it work with htmx or else? I tried to periodically render an html with a plotly graph using htmx; resulted awful -
Django viewset: using get for list() only
I have this viewset where i wnat to use get method for list() only. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() def get_serializer(self, instance=None, *args, **kwargs): serializer = UserSerializer(method=self.action, instance=instance, *args, **kwargs) return serializer def get_permissions(self): if self.action == 'list': permission_classes = [IsAdminUser] elif self.action == 'update': permission_classes = [IsAuthenticated, IsOwner] elif self.action == 'create': permission_classes = [] else: raise ValueError(f"Invalid action: {self.action}") return [permission() for permission in permission_classes] I tried ti define http method names first, but list and retrieve both run for get method. Is there any other solution to this? -
User inbox feature in django project
Inbox feature in django project. I am working on this django project, and I want to implement an inbox feature in the project. The inbox will enable the admin if the website send messages to the users. Can someone help me out or point me in the right direction, I'll be so grateful. I am expecting the the users will be able to only read the admin message. -
Django: prevent Form to crash when akward date format is used
I have a form: class EditProfileForm(forms.ModelForm): template_name = 'users/edit_profile.html' def __init__(self, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.fields['email'].help_text = _( 'Providing your email would enable you to recover your lost password') class Meta: model = get_user_model() fields = ( 'first_name', 'last_name', 'email', 'birthday', 'language', 'headshot', ) with user model: class CustomUser(AbstractUser): birth_year = models.PositiveIntegerField( verbose_name=_('Birth year'), default=0) birthday = models.DateField(verbose_name=_( "birthday"), null=True, blank=True) headshot = models.ImageField(verbose_name=_('Avatar'), null=True, blank=True, default='user_headshots/user.png', upload_to="user_headshots/") language = models.CharField(verbose_name=_('Language'), max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE) I had a user use a strange format for birthday "25,2,96", which led the django application to crash: The view users.views.edit_user_profile didn't return an HttpResponse object. It returned None instead. not much more information in the Traceback !?! Looking into the django code and internet, I was amazed that the DateField formfields did not come with embedded validators There are plenty of information on internet about setting specific dateformats for a specific DateField, but I wasn't able to find one kind of best practice that would work with all sort of localized date formats. Everything I found is very complicated for such a trivial issue, and I'm pretty sure there is a neat and easy to implement solution. Any suggestion? -
My python3 manage.py makemigrations or python manage.py makemigrations is erroring
I am trying to run th migration prompt in django and it isnt working. This is the error: @user: django_angular_auth_api % python3 manage.py makemigrations Traceback (most recent call last): File "/Users/user/django-angular-auth/django_angular_auth_api/manage.py", line 22, in main() File "/Users/user/django-angular-auth/django_angular_auth_api/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 442, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py", line 137, in handle loader = MigrationLoader(None, ignore_no_migrations=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in init self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 305, in build_graph self.graph.ensure_not_cyclic() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/graph.py", line 284, in ensure_not_cyclic raise CircularDependencyError( django.db.migrations.exceptions.CircularDependencyError: users.0001_initial I added in a dependancy and did everything possible to try and fix it. wiped and redid db, and most other things i found online. -
ecommerce website with django adding many item to cart
` hello developers. Im using django for ecommerce website and I cant add item cart with number. For ex: I want to add 100 pieces of the same product with typing not increasing. Waiting your helps ` index.html <div class="card-footer p-0 no-gutters"> {% if product|is_in_cart:request.session.cart %} <div class="row no-gutters"> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="text" name='product' value='{{product.id}}'> <input hidden type="text" name='remove' value='True'> <input type="submit" value=" - " class="btn btn-block btn-light border-right"> </form> <div class="number-center col">{{product|cart_quantity:request.session.cart}} in Cart</div> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="number" name='product' value='{{product.id}}'> <input type="submit" value=" + " class="btn btn-block btn-light border-left"> </form> </div> {% else %} <form action="/#{{product.id}}" method="POST" class="btn-block"> {% csrf_token %} <input hidden type="number" name='product' value='{{product.id}}'> <input type="submit" class="float-right btn btn-light form-control" value="SEPETE EKLE"> </form> </div Thanks -
Best Explanation on the implementation of Dependency Injection in Python.?
I am a Software Engineer with significant amount of years of experience. I always desire using core development principles in my projects and these include using DI. which I have used alot in .NET projects and in Nodejs Projects. however I can't wrap my head around how DI actully works in python projects especially using FLask or Django. The examples I have seen are not really conidered DI to me. Would appreciate a good explanation. Thanks. I simply want to apply DI in future Django and Flask Projects. -
Django: no such table: auctions_user_user_permissions
I wrote the Django program and registered some products with the admin panel. After making some changes in the codes, I encountered some problems: 1- It is no longer possible to enter the admin panel and it gives this error. 2- None of the product information is displayed and it seems as if there is no data on the site. what is the problem? # item detail page in views.py def item_detail(request, bidid): bid_desc = List.objects.get(pk = bidid, active_bool=True) nowbids = Bidmodel.objects.filter(listb_id = bidid) return render(request, "auctions/item_detail.html",{ "list": bid_desc, "comments" : Comments.objects.filter(listc_id = bidid), "now_bid": minbid(bid_desc.first_bid, nowbids), }) index.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} <div> {% for item in items %} <div> <img src= {{ item.image.url }} alt = "{{item.title}}"><br> <a>{{ item.title }}</a><br> <a>{{ item.category }}</a><br> <a><a>Frist Bid: </a> {{ item.first_bid }} $ </a><br> <a href="{% url 'item_detail' item.id %}">View Product</a> </div> {% endfor %} </div> {% endblock %} item_detail.html: {% extends "auctions/layout.html" %} {% block body %} {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif … -
WeasyPrint: Image not showing on linux (ubuntu)
I am using weasyprint it working on window perfectly and also it is working on linux when I used this string in html file like weasyprint my.html my.pdf It perfectly show image but when I do the below code so the image not showing I html_string = '<img src="http://domain_name/static/assets/images/logo/logo.png" alt = "Logo" /> <h1>images</h1>' # Create a PDF object from the HTML string #pdf = weasyprint.HTML(string= html_string, base_url=request.build_absolute_uri()).write_pdf(presentational_hints = True, stylesheets=[weasyprint.CSS(string='@page { size: letter; }')]) # # Create an HTTP response with the PDF content response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="marksheet.pdf"' response.write(pdf) return response I used absolute_url but not showing images nothing get any idea why it not showing image -
can i host django website on shared hosting? if, yes what are the pros and cons of it?
i am working on a project of django and make it online but the price of VPS hosting price is high. So, i am getting for a affordable option. Many people suggest me for free trail of Azure or AWS, but i am uncertain for its speed and price after the trail end. If anyone upload their django website on shared hosting please share the speed of website. I did research for and came to conclusion that when i upload django website on shared hosting i will problem while setting the wsi or while creating superuser. Also my server get crashed frequently. -
How to upgrade Django 1.3.1 to 1.3.7 on Ubuntu in Docker
I have an old django project and I built it in docker for the development environment, django 1.3.1 is installed. (Python version is 2.7 setting in docker-compose) Is there any way to upgrade to django 1.3.7? Thanks for advance. I tried followings but don't work. apt-get upgrade django apt-get install python-pip and pip install [--upgrade] django==1.3.7 Downloading/unpacking Django==1.3.7 Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement Django==1.3.7 No distributions at all found for Django==1.3.7 My dockerfile: FROM ubuntu:12.04 ... # Install dependencies RUN apt-get update \ && apt-get install -y \ apache2 \ libapache2-mod-wsgi \ mysql-server \ python-mysqldb \ python-django ... -
testing urls in django
hi I get some problems with my test in my Django project I want to write test for my URLs and one of my URLs gets an argument and I try a lot of ways and it still giving error that reverse relation doesn't match I gave the URL the id and I gave the greater and smaller sign to it but it still doesn't work -
How to filter rooms based on user's input as room_capacity , check_in_date and check_out date in Django
Here is my input form which takes user's input as room_capcity , check_in_date and check_out_date : HTML Page <!-- Filter form --> <form action="{% url 'Rooms:show_filtered_rooms' %}" method="POST" class="flex flex-row justify-center my-8 mx-10 space-x-4" > {% csrf_token %} <div class="flex flex-col"> <label for="room_capacity" class="text-xl font-semibold">Room Capacity</label> <select name="room_capacity" id="room_capacity" class="w-48 h-10 border-2 border-gray-300 rounded-md" > <option value="" hidden>Select Room Capacity</option> <option value="single">Single</option> <option value="double">Double</option> <option value="triple">Triple</option> </select> </div> <div class="flex flex-col"> <label for="check_in_date" class="text-xl font-semibold">Check In Date</label> <input type="date" name="check_in_date" id="check_in_date" class="w-48 h-10 border-2 border-gray-300 rounded-md" /> </div> <div class="flex flex-col"> <label for="check_out_date" class="text-xl font-semibold">Check Out Date</label> <input type="date" name="check_out_date" id="check_out_date" class="w-48 h-10 border-2 border-gray-300 rounded-md" /> </div> <button type="submit" class="px-1 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600" > Apply Filters </button> </form> <!-- Filter form ends --> Here is my logic in view.py file: def showFilteredRooms(request): if request.method == 'POST': room_capacity = request.POST.get('room_capacity') check_in_date = datetime.strptime(request.POST.get('check_in_date'), '%Y-%m-%d').date() check_out_date = datetime.strptime(request.POST.get('check_out_date'), '%Y-%m- %d').date() print(room_capacity) print(check_in_date) print(check_out_date) # Step 1: Get booked rooms with the specified capacity and overlapping date range booked_rooms = Booking.objects.filter( capacity=room_capacity, checkInDate__lte=check_out_date, checkOutDate__gte=check_in_date ).values_list('roomNo', flat=True) # Step 2: Get available rooms with the specified capacity available_rooms = Room.objects.filter( capacity=room_capacity ).exclude(roomNo__in=booked_rooms) print(available_rooms) context = { 'available_rooms': available_rooms, 'filter_applied': True, # … -
I am trying to implement swagger for my django drf project but it's displaying all endpoint methods I don't want post put delete methods
Actually I am trying to implement swagger for my django drf project but it's displaying all endpoint methods I don't want post put delete methods display in swagger what should I do Actually I am trying to implement swagger for my django drf project but it's displaying all endpoint methods I don't want post put delete methods display in swagger what should I do? -
How to dynamically add markers using Folium and JavaScript based on user input coordinates?
I'm working on a project where I'm using the Folium library to create interactive maps. I want to allow users to input coordinates (latitude and longitude) through a form, and upon submission, I'd like to dynamically add a marker to the map at the specified location. Here's what I have so far: <section> <h2>Mapa de ocorrência:</h2> <form id="coordinateForm"> Latitude: <input type="text" id="latitude" name="latitude"><br> Longitude: <input type="text" id="longitude" name="longitude"><br> </form> <div id="map">{{ map | safe}}</div> </section> The map came from this code def fazer_mapa(self): family = self.kwargs['family'] zoom_level = 4 colecoes = Colecao.objects.filter(family=family) latitude_values = list(Colecao.objects.filter(family=family).aggregate(Max('decimalLatitude'),Min('decimalLatitude')).values()) longitude_values = list(Colecao.objects.filter(family=family).aggregate(Max('decimalLongitude'),Min('decimalLongitude')).values()) if latitude_values == [None,None] and longitude_values == [None,None]: latitude_values = [-19.8688655,-19.8688655] longitude_values = [-43.9695513,-43.9695513] zoom_level = 16 # média de onde será o meio do mapa latitude_media = (sum(latitude_values))/2 longitude_media = (sum(longitude_values))/2 mapa_family = Map(location=[latitude_media,longitude_media],zoom_start=zoom_level,tiles='Stamen Terrain') return mapa_family._repr_html_() Could someone guide me on how to use JavaScript to capture the user's input for latitude and longitude and then add a marker to the map using Folium? I appreciate any help or examples you can provide! -
Deploy react js + django + CentOS + SSL
I need some help deploying react js + django + CentOS + SSL. Here's what I have: react-ui/src/config/constant.js BACKEND_SERVER = "http://mysite.mydomain.xxx:8000/api/"; react-ui/package.json "start": "HTTPS=true react-scripts start", "build": "HTTPS=true react-scripts build", react-ui/.env HTTPS=true yarn start django I know some of these are high risk entries, but I am working on getting this functional. ALLOWED_HOSTS = [ '*' ] CORS_ALLOW_ALL_ORIGINS=True # Load the default ones CORS_ALLOWED_ORIGINS = ["https://localhost:3000", "https://mysite.mydomain.xxx:3000"] CSRF_TRUSTED_ORIGINS = ["https://localhost:3000", "https://mysite.mydomain.xxx:3000"] SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_EXPIRE_AT_BROWSER_CLOSE=True run django python manage.py runserver 0.0.0.0:8000 /etc/nginx/nginx.conf upstream mysite_server { server unix:/home/myuser/mysite/django-api/mysite.sock fail_timeout=0; } server { listen 80; server_name mysite.mydomain.xxx; #location = /favicon.ico { access_log off; log_not_found off; } #location /static/ { # root /home/myuser/mysite/django-api; #} #location / { # proxy_set_header Host $http_host; # proxy_set_header X-Real-IP $remote_addr; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # proxy_set_header X-Forwarded-Proto $scheme; # proxy_pass http://unix:/home/myuser/mysite/django-api/mysite.sock; # } return 301 https://mysite.mydomain.xxx$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name mysite.mydomain.xxx; root /usr/share/nginx/html; ssl_certificate "/etc/pki/tls/private/star-yyy-xxx.bag"; ssl_certificate_key "/etc/pki/tls/private/star-yyy-xxx.bag"; # ssl_certificate "/etc/pki/nginx/server.crt"; # ssl_certificate_key "/etc/pki/nginx/private/server.key"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers PROFILE=SYSTEM; ssl_prefer_server_ciphers on; # # # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; # location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header … -
Flutter app uploaded on play store but not fetching data through django backend connection even though it the code was working fine in the local studi
I have created a flutter app whoch is connected with the django backend website and uploaded this app on playstore when the app was uploaded successfully I download the app and when I run the app and try to fetch the data to the app from website django backend connection no data was being fetched there was no cennection between the app and the django backend of website which I downloaded it on playstore even though the app was working fine in android studio during testing. This is the link of my app https://play.google.com/store/apps/details?id=com.beneprep.mdcat -
`pytest -rP` got error while `pytest` didn't to run Selenium with Django and pytest-django on Windows 11
I set tests/test_ex1.py as shown below. *I use Django 4.2.1, pytest-django 4.5.2 and Selenium 4.11.2 on Windows 11: django-project |-core | |-settings.py | └-urls.py |-my_app1 |-my_app2 └-tests |-__init__.py └-test_ex1.py # Here Then, I defined test_example() with print("OK") to test Django Admin in TestBrowser1 class as shown below: # "tests/test_ex1.py" from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser1(LiveServerTestCase): def test_example(self): print("OK") driver = webdriver.Chrome() driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title Then, I could successfully run Selenium with pytest by not printing OK as shown below: $ pytest ===================================== test session starts ===================================== platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0 django: settings: core.settings (from ini) rootdir: C:\Users\kai\test-django-project2 configfile: pytest.ini plugins: Faker-19.3.0, django-4.5.2, factoryboy-2.5.1 collected 1 item tests\test_ex6.py DevTools listening on ws://127.0.0.1:56055/devtools/browser/271a3af7-5697-47e5-a7db-fd80c52ed70d . [100%] ====================================== 1 passed in 5.11s ====================================== But, I could not successfully run Selenium with pytest -rP by getting the error below even though it printed OK. *pytest -s, pytest --capture=no and pytest --capture=tee-sys also got the same error below even though it printed OK as well: $ pytest -rP ===================================== test session starts ===================================== platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0 django: settings: core.settings (from ini) rootdir: C:\Users\kai\test-django-project2 configfile: pytest.ini … -
Reverse for 'blog-single' with keyword arguments
I'm trying to create simple blog, I have a blog-home page that show the lastest puplished post and I want to open a single-blog page for each post but I encounter with this error : Reverse for 'blog-single' with keyword arguments '{'post_id': ''}' not found. 1 pattern(s) tried: ['blog/blog/(?P<post_id>[0-9]+)/\Z'] do you know how can I solve this ? [view](https://i.stack.imgur.com/eW6I4.jpg) [url](https://i.stack.imgur.com/kMdy0.jpg) [blog-home.html](https://i.stack.imgur.com/lvxOv.jpg) I check all the names and links in view, url and template but nothing was wrong -
Django Access Formset Instances from within Forms
I'm building a website where students can answer multiple questions on an assignment. I have models to store these objects. I'm trying to create a formset of questions for an assignment. To do this, I'm using an inlineformset_factory to handle multiple questions. It is important the questions be created before the formset is submitted, and that the formset updates each question. My application has the following models: Models from django.db import models class Assignment(models.Model): name = models.CharField(max_length=255) class AssignmentSubmission(models.Model): """Can be completed multiple times by students. Teachers can view/mark submissions.""" assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) class QuestionType(models.TextChoices): """Identifies what types of questions can be created.""" SHORT_ANSWER = "short_answer" LONG_ANSWER = "long_answer" FILE_UPLOAD = "file_upload" class Question(models.Model): """Used for adding additional submission fields to Quests. This model is used for all types of questions, including multiple choice, short answer, file upload, etc. """ instructions = models.TextField() assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) type = models.CharField( max_length=20, choices=QuestionType.choices, default=QuestionType.SHORT_ANSWER ) class QuestionSubmission(models.Model): """Used for storing a student's response for an individual question in an AssignmentSubmission. This model is used for all types of questions, including multiple choice, short answer, file upload, etc. When a student submits an Assignment, each Question will have a QuestionSubmission created …