Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Model QuerySet from a Django model instance
I have a model instance in Model's clean() method, and I want to add it to a QuerySet like below. def clean(self) -> None: #here self == model instance I need to add to queryset if self.id: from django import forms g=dag.DAG() g.create(self) if not g.validate_DAG(): self.custom_exception="Check hierarchy of users, cyclic dependency being created" raise forms.ValidationError(f"{self.custom_exception}") return super().clean() def create(self, update_cashback_relation): try: # Create a directed graph from catalog.models import UserRelationCashback self.G = nx.DiGraph() # # Add nodes to the graph user_relations_data=UserRelationCashback.objects.all() user_relations_data.get(id=update_cashback_relation.id).delete() user_relation_updated=user_relations_data.get(id=update_cashback_relation.id) print(user_relations_data.get(id=update_cashback_relation.id).__dict__) user_relations_data = user_relations_data | update_cashback_relation #this won't work as we must have both queryset, but i have a model instance and a queryset user_relations=user_relations_data.values("user", "manager", "product_group_category_warranty") users=user_relations.distinct().values_list("user", flat=True) # Add nodes to the graph for user in users: self.G.add_node(user) # Add directed edges to the graph for user_relation in user_relations: self.G.add_edge(user_relation.get('user'), user_relation.get('manager')) # Visualize the directed graph pos = nx.spring_layout(self.G) matplotlib.use('Agg') fig, ax = plt.subplots() # Draw the directed graph with arrows nx.draw(self.G, pos, with_labels=True, node_size=500, node_color='skyblue', font_size=10, font_color='black', arrows=True, ax=ax) # Save the graph as an image plt.savefig('directed_graph.png', format='png') plt.show() except Exception as e: raise Exception(f"{e}") -
why i use enctype='application/json' but CONTENT_TYPE still be application/x-www-form-urlencoded
<form enctype='application/json' action="{% url 'xxx' %}" method="post"> {% csrf_token %} <input type='number' name='bottle-on-wall' value='1'> <input type='number' name='bottle-on-wall' value='2'> <input type='number' name='bottle-on-wall' value='3'> <button type="submit">send</button> </form> CONTENT_TYPE 'application/x-www-form-urlencoded' how can i send the form data as json to server -
How can I process, stream a video and render the results in Django?
I'm currently involved in a real-time machine learning project that seamlessly integrates with Django. In this endeavor, I'm deeply immersed in processing and live-streaming video content. This multifaceted process encompasses the capture of video frames, their real-time processing, and their seamless streaming to a web application. Furthermore, I've integrated the Firebase Realtime Database to facilitate the storage and retrieval of data associated with the video stream. Here's a brief overview of what the code does: Here, I have a generator function called 'generate(camera),' which captures frames and yields them as a multipart stream. Within the 'generate' function, I simultaneously process video frames, detect actions, and yield each frame with a content type of 'image/jpeg.' Upon the completion of video processing, indicated by an end marker, the processed data is stored in a database, and the user is redirected to a results page. def generate(camera): action_labels = ['field_goal', 'pass', 'run', 'touchdown'] actions = {'actions': {}} while True: data = camera.get_frame() if len(data) == 4: frame = data['frame'] results = data['results'] action = data['action_bboxes'] timestamp = data['timestamp'] if len(action) > 0: try: action_result = action_labels[action[0][0]] actions['actions'][timestamp] = action_result # actions.append(action_data) except: pass if frame: yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n' else: … -
Django-import-export library - No such file or directory: '/tmp/tmp5bcxsx9p'
I have a problem with the django-import-export library because when I try to import excel or csv files it gives me error 500, and the error returned is the following FileNotFoundError [Errno 2] No such file or directory: '/tmp/tmp5bcxsx9p' and the error comes from django-import-export library in the file import_export/tmp_storages.py in _open() def _open(self, mode="r"): if self.name: return open(self.get_full_path(), mode, encoding=self.encoding) <---- else: tmp_file = tempfile.NamedTemporaryFile(delete=False) self.name = tmp_file.name return tmp_file this is the code in the Django admin of the model that im trying to import info class ProductForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): qs = super().get_queryset(value, row, *args, **kwargs) return qs.filter(shop__tpc_shop=int(row['ID TIENDA']), sku=row['SKU'].upper().strip()) class StockResource(resources.ModelResource): shop = Field( column_name='ID TIENDA', attribute='shop', widget=ForeignKeyWidget(Shop, 'tpc_shop') ) product = Field( column_name='SKU', attribute='product', widget=ProductForeignKeyWidget(Product, 'sku') ) units = Field( column_name='UNIDADES', attribute='units', widget=IntegerWidget(), default=0, ) threshold_units = Field( column_name='UMBRAL', attribute='threshold_units', widget=IntegerWidget(), default=10, ) location = Field( column_name='LOCALIZACION', attribute='location', widget=OurCharWidget(), default='No location', ) @classmethod def get_error_result_class(self): """ Returns the class used to store an error resulting from an import. """ return SimpleError class Meta: model = Stock use_transactions = True skip_unchanged = True report_skipped = True import_id_fields = ('product',) fields = ('id', 'units', 'threshold_units', 'location') def before_import_row(self, row, row_number=None, **kwargs): row['SKU'] = str(row['SKU']).strip() … -
To know the number of objects being serialized at that time. DRF
I have a serializer which will serialize an object. Is there a way to know if it's serializing one object or multiple objects at that time? I have a serializer and I have a custom method field in that. I need to call one API if it's a single objects it is serializing or if it's serializing multiple objects, I need to call a different API. -
Django/pytest: Requested setting REST_FRAMEWORK, but settings are not configured
I'm working on a Django project and using pytest for testing. I have written a very simple test case - class TestwordOfTheDay(TestCase): def setUp(self): print("Test passed") def test_json_response(self): json_response = { "id": 43, "wordOfTheDayinHindi": "अस्पष्ट", "wordOfTheDayinEnglish": "ambiguous", "wordOfTheDayinEnglish_Usage_Example": "Everyone listened to the weather report, but the forecast was ambiguous and no one knew if it was going to be rainy or sunny today.", "wordOfTheDayinHindi_Usage_Example": "हर किसी ने मौसम के समाचार को सुना था, लेकिन उनका पूर्वानुमान अस्पष्ट था और कोई भी यह नहीं जान पाया कि आज बरसात होगी या धूप खिलेगी।", "date": "2023-10-19" } response = JsonResponse(json_response) self.assertTrue(isinstance(json_response["id"], int)) self.assertRegex(json_response["wordOfTheDayinHindi"], r"[ऀ-ॿ]+$") self.assertRegex(json_response["wordOfTheDayinEnglish"], r"^[a-zA-Z]+$") self.assertRegex(json_response["wordOfTheDayinEnglish_Usage_Example"], r"^.*\b" + re.escape(json_response["wordOfTheDayinEnglish"]) + r"\b.*[.?!]$") self.assertRegex(json_response["wordOfTheDayinHindi_Usage_Example"], r"^.*\b" + re.escape(json_response["wordOfTheDayinHindi"]) + r"\b.*[.?!]$") self.assertEqual(json_response["date"], str(date.today())) However, when I run pytest, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I'm not sure how to resolve this issue. Any help or guidance on how to fix this error would be greatly appreciated. -
Django Programming Error: Cannot Cast Type bigint to uuid
I'm facing an issue while trying to change the data type of a column in my Django model from bigint to uuid in a PostgreSQL database. The error message I'm encountering is: django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...me_studentrest" ALTER COLUMN "id" TYPE uuid USING "id"::uuid -
Mocking instance methods in python unittest
I'm a software developer for several years but new to python. I'm writing a unit test (so no database connection present) that involves a model in Django that accesses another model referenced via a foreign key connection. I want to mock the method that accesses this connection and replace the result with a hard coded response, that is different for each instance though. Here's a minimal example: ### tests/test_MyTestCase.py from unittest import TestCase from djangoapi.models import * class MyTestCase(TestCase): def setUp(self): self.instance1 = MyModel() self.instance2 = MyModel() foreignKey1 = MySubModel() foreignKey1.my_value = 1 # Mock that self.instance1.submodel_set.all() returns [foreignKey1] foreignKey2 = MySubModel() foreignKey2.my_value = 2 # Mock that self.instance2.submodel_set.all() returns [foreignKey2] def testSomething(self): self.assertEqual(self.instance1.get_max_value(), 1) self.assertEqual(self.instance2.get_max_value(), 2) ### models.py from django.db import models class MyModel(models.Model): def get_max_value(self): value = 0 # the return value of self.submodel_set.all() is what I want to mock for model in self.submodel_set.all(): value = max(value, model.my_value) return value class Submodel(models.Model): my_model = models.ForeignKey(MyModel, null=True, on_delete=models.SET_NULL) my_value = models.IntegerField() I tried several combinations of the @patch decorator, Mock() and MagicMock() but could not get it to work. Thank you in advance! -
Unable to import CSV table in a model on PostgreSQL
I am doing a project on Django with database connected to postgreSQL. I did all the commands related to models as makemigrations and migrate so my tables appear on PgAdmin 4 correctly. The problema is for a particular table "Dashboard_país" with 2 columns (id and nombre) I am not able to import csv table, when with the other models importing csv I didnt have any problem. My model Dashboard_país looks like this: class País(models.Model): nombre = models.CharField(max_length=100) class Meta: verbose_name = "País" verbose_name_plural = "Países" def __str__(self): return self.nombre I receive the next error when import my csv: Running command: --command " "\copy public."Dashboard_país" (id, nombre) FROM 'C:/Users/auxer/Desktop/pais.csv' DELIMITER ';' CSV HEADER ENCODING 'UTF8';"" Start time: Thu Oct 19 2023 10:50:53 GMT+0200 (hora de verano de Europa central) \copy: error de procesamiento al final de la l�nea Processing error at the end of the line or something similar on english. I was searching on the internet and didnt find anyone with a similar error so I would be glad if anyone could help me Thanks. I tried import a simple CSV like this: Id;Nombre 1;John 2;Emma 3;Michael but it didnt work I also tried using query tool but commands doesnt … -
Azure Entra + Django SSL to many redirect
I try to connect MS Entra with Azure App. Everything works great on local version but production fail. Depending on the options SECURE_SSL_REDIRECT=False I got AADSTS50011: The redirect URl http:/myapp/auth/redirect specified in the request does not match the redirect URl's configured for the application. Of course in app on Azure I can't set http only https work. If SECURE_SSL_REDIRECT=True and Debug=False I got: To many redirect error. Cookies clean, different computer same error. Local test work with http and runserver In production I use gunicorn 443 port and docker. Cookies clean, different settings and computer. Some advice with gunicorn setting I think -
sock=backend at=error code=H18 desc="Server Request Interrupted"
Issue is, in my api view have some logic, and when a request hit to endpoint, there is two thing happening one is oauth2_provider validating token and other is logic execution for request, so when token validation failes it gatting 403 and it raising heroku\routing sock=backend at=error code=H18 desc="Server Request Interrupted" error and end user getting response as 503 instead of 403. I have implemented token validation system, where i have used django-oauth-toolkit package and deployed on heroku platform. Here, we are having separate Authorization and resource server, i have configured resource server as below mentioned. INSTALLED_APPS = ( ... 'oauth2_provider',) OAUTH2_PROVIDER = { ... 'RESOURCE_SERVER_INTROSPECTION_URL': 'https://example.org/o/introspect/', 'RESOURCE_SERVER_AUTH_TOKEN': '3yUqsWtwKYKHnfivFcJu', # OR this but not both: 'RESOURCE_SERVER_INTROSPECTION_CREDENTIALS': ('rs_client_id','rs_client_secret'), ...} i have used class based view ProtectedResourceView how to avoid this Heroku code=H18 503 getting into end user response and capture 403 and send as end user response if token validation fails with 403. -
Django server is not running suddenly
I had many working projects and suddenly when I tried to run the server using the: python manage.py runserver, I get the following output, and the server doesn't run: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). I have seen similar questions, but in their case the problem was related to connecting to the database, but in my case I'm using sqllite and even tried to start new django project and run the server and I have faced the same issue. -
Why do I get a no such table ERROR in Django with Django-crontab and not with manual execution?
Hello what is my problem? My problem is that when I run a crontab manually in Django with crontab run I can do database queries without problems but when the crontab runs alone I get the error no such table. I have already tried everything possible on my knowledge level and also googled but found no solution i hope you can help me. I marked the ERROR LINE IN CODE def fetch_data_from_iwps(): print_output_in_file("Start 1") print_output_in_file("Start 2") try: iwps = IWP.objects.filter(tracking_on_off=True, IP__isnull=False) # ERROR LINE print_output_in_file(iwps) """ for iwp in iwps: fetch_and_store_data(iwp) pass """ with concurrent.futures.ThreadPoolExecutor() as executor: print("multi") executor.map(fetch_and_store_data, iwps) pass pass except Exception as e: # Behandeln Sie etwaige Ausnahmen oder Fehler hier print("Error00") print_output_in_file(str(e)) pass sys.stdout = sys.__stdout__ print_output_in_file("Ende") pass i have already tried to check the imports and the settings also in the code i have used all possible error and tricks -
Invalid domain name error when trying to send email with django
Please help to resolve this issue: Facing following error when trying to send email in Django on Ubuntu: env/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 92, in open self.connection.starttls(context=self.ssl_context) File "/usr/lib/python3.10/smtplib.py", line 769, in starttls self.ehlo_or_helo_if_needed() File "/usr/lib/python3.10/smtplib.py", line 614, in ehlo_or_helo_if_needed raise SMTPHeloError(code, resp) smtplib.SMTPHeloError: (501, b'5.5.4 Invalid domain name') Email host is Hotmail Using standard settings for Django: EMAIL_HOST_USERNAME = 'x@hotmail.com' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' How to resolve this issue? Checked email settings for Hotmail Receiving email without "https/http" All characters in email address is in lowercase -
Error while installing psycopg2 on Windows - 'UnicodeDecodeError' during dependency resolution
I'm trying to install psycopg2 in a virtual environment for my Django project on Windows, but I'm encountering an error that I can't seem to resolve. The error I'm getting is as follows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 13: invalid continuation byte I've tried several solutions, but none of them have worked. I also saw a person who faced a similar issue on macOS and resolved it by installing OpenSSL with Homebrew and setting certain environment variables. Can you help me understand how to resolve this issue on Windows? Are there equivalents to the macOS environment export commands that I can use on Windows? Here's what I've already tried: [List the steps you've already taken, including the commands you've executed] [Provide any other relevant information about your environment, such as the Python version you're using] -
Dependencies errors using react-admin with ra-data-django-rest-framework
I created a new project using vite and installed react-admin. I have a backend in django so I want to use ra-data-django-rest-framework. But the issue is it's very old and when I try to install it's showing dependency error for react v16. Is there any alternative packages for this? I have REST api in django can I use some other data providers without any issues? -
Django stay on the same site after add item to cart and not append search url to another url
So i encounter 2 problem: First is i want to stay on the same site when add item to cart/favourite The idea is when the user search the product name, there will be list of products in the /search_result and i want user can add product from this list to a favourite db, and still stay in /search_result so they can add another product. Second is when i use search bar in /favourite the /search_url append to it become /favourite/search_url make in invalid My models: class Favourite(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) product = models.ManyToManyField(Product, through='FavouriteItem') class Meta: db_table = "scrape_favourite" class FavouriteItem(models.Model): favourite = models.ForeignKey(Favourite, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class Meta: db_table = "scrape_favouriteitem" My urls: urlpatterns = [ path("", views.search, name="search"), path("search_result", views.search_result, name ="search_result"), path("form/", views.form_view, name="form"), path("products/", views.products_view, name="products"), path("sign-up", views.sign_up, name="sign_up"), path('add-to-favourite/<int:product_id>/', views.add_to_favourite, name='add-to-favourite'), path('remove-from-favourite/<int:product_id>/', views.remove_from_favourite, name='remove-from-favourite'), path('favourite/', views.view_favourite, name='favourite'), ] My views: @login_required(login_url="/login") def add_to_favourite(request, product_id): product = Product.objects.get(pk=product_id) favourite = Favourite.objects.get_or_create(user=request.user)[0] favourite_item = FavouriteItem.objects.get_or_create(favourite=favourite, product=product)[0] # return redirect('/') @login_required(login_url='/login') def remove_from_favourite(request, product_id): product = Product.objects.get(pk=product_id) favourite = Favourite.objects.get(user=request.user) try: favourite_item = favourite.favouriteitem_set.get(product=product) favourite_item.delete() except FavouriteItem.DoesNotExist: pass # return redirect('/favourite') @login_required(login_url='/login') def view_favourite(request): try: newForm = ProductNameForm() favourite = request.user.favourite print(favourite) favourite_items = FavouriteItem.objects.filter(favourite=favourite) … -
How can I use an external CSS to override Bootstrap styles
I am using Bootstrap by directly linking to it over the internet without downloading it to my local files, and the page rendering has no major issues. However, I don't understand why some styles, like the .login-username, cannot be overridden, and they only work when written in the style tag. What might be the issue? main.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'tasks/main.css' %}"> <style> .login-username{ display: flex; } </style> </head> <body> <div class="center-column"> {% block content %} {% endblock content %} <div> </body> </html> It cannot be written in main.css. Writing it inside has no effect. main.css body{ background-color: #638CB8; } input{ width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; } input.title{ border:solid; } .center-column{ width:600px; margin: 20px auto; padding: 20px; background-color: #fff; border-radius: 3px; box-shadow: 6px 2px 30px 0px rgba(0,0,0,0.75); } .item-row{ padding: 20px; margin: 10px; font-size: 16px; background-color:#A1703E; border-radius: 3px; color: #fff; } .btn-warning{ background-color: #ffae19; border-color: #e59400; --bs-btn-color: #fff; --bs-btn-active-color: #fff; --bs-btn-hover-color: #fff; } #id_description{ width:100%; padding:20px; } input.id_complete{ width:100%; } /* login */ .login-username{ display: flex; } login.html {% … -
How to implement CSRF protection for user identification without login in DRF
I'm developing an app like anonymous bulletin board. The app is configured react and django rest framework. To identify user by cookie of uuid, I use custom middleware like this import uuid from django.contrib.sessions.middleware import SessionMiddleware from django.http.request import HttpRequest from django.http.response import HttpResponse class CustomMiddleware(SessionMiddleware): def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: user_id = request.COOKIES.get('user_id', None) if not user_id: max_age = 365 * 24 * 60 * 60 response.set_cookie( 'user_id', str(uuid.uuid4()), max_age=max_age, samesite='lax' ) return super().process_response(request, response) Then I googled how to protect the app from CSRF and couldn't find it. Please teach me the best way of it. regards. I tried to use session and csrf token, but I hovent any idea. -
How to change the value of inlines in an Django Admin form dynamically?
I'm trying to make the display of inline forms dynamic in Django according to the value of the "content_type" column, but I'm not succeeding. I've already tried overriding the get_inlines, get_inline_instance, and, finally, methods, as shown below: class XInline(nested_admin.NestedStackedInline): model = X fields = ["title", "some_field"] extra = 1 class YInline(nested_admin.NestedStackedInline): model = Y fields = ["title", "some_field"] extra = 1 class ZInline(nested_admin.NestedStackedInline): model = Z fields = ["title", "some_field"] extra = 1 class MyModelAdmin(nested_admin.NestedModelAdmin): list_display = ["id", "content_type"] def get_form(self, request, obj=None, **kwargs): if (obj): self.inlines = self.get_inlines() for inline in self.inlines: if obj.content_type.model == "x": self.inlines = [XInline] elif obj.content_type.model == "y": self.inlines = [YInline] elif obj.content_type.model == "z": self.inlines = [ZInline] return super(MyModelAdmin, self).get_form(request, obj, **kwargs) Ps.: that content_type is a ForeignKey of ContentType from from django.contrib.contenttypes.models -
When trying to deploy my Django app on AWS Elastic Beanstalk, I am getting the error "ModuleNotFoundError: No module named 'config.settings'"
I am attempting to deploy my Django app on AWS, but I keep getting errors like those mentioned in the title. I've tried changing the structure of my directory without luck. The below image shows my django.config file, along with the structure of my file directory: Django Directory Structure my django.config file looks like option_settings: aws:elasticbeanstalk:container:python: WSGIPath: lexgen.config.wsgi:application wsgi.py looks like import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') application = get_wsgi_application() I've tried changing my directory structure and moving references to config.settings, but that causes other parts of my program to break and create new error messages. Other answers I've read involve changing the django.config or wsgi.py files, in particular the WSGIPath in django.config, but I haven't been able to crack this just yet. If anyone has any insight into this problem, I'd really appreciate it. Happy to include any other information that may help answer this question. -
How to bypass the TTL of 30 seconds while waiting response of post request from external server
I am building a view in Django , which will send a POST request to chat-gpt API, the problem that I am facing that the response from chat-gpt is taking more than 30 seconds (we are having a long prompts) the idea that I have in mind is: The client sends a request to the server. The server writes the request to a message queue and returns a message ID to the client. Another worker is listening to the message queue. It retrieves the request from the queue, sends it to OpenAI,and then writes the response back to the message queue. The client periodically sends requests to the server to ask for the response using the previously received message ID. The server responds with "pending" until it finds the response in the message queue, at which point it returns the actual response to the client. the problem is that I have no idea how to achieve that ... I am using gke for hosting the application, I already have some cronjob using some views as well any idea how to deal with this will be so much appreciated here is an example of the view request: import openai from app.forms_prompt … -
settings.py not retrieving Django-Environ info server side
my Issue Hello, I am having issues with my website fetching the information from my Django-envrion file to settings.py. I am able to open up localhost:8000 on my dev computer perfectly with the same configuration (just Debug set to off and using the local DB). Although when I boot up my server I have issues logging into postgres, Also debug is set to on despite the environment file being set to 0. There are also some oddities where it might fetch the Database name and Database user as those are in the environment files. Here is the error that shows up (despite debug is off like i mentioned prior although it can read some attributes I believe considiering it knows what database and the name for the user): OperationalError at / connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "DBuser" connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "DBuser" Request Method: GET Request URL: https://[REDACTED].com/ Django Version: 4.2.3 Exception Type: OperationalError Exception Value: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "DBuser" connection to server at "localhost" (::1), port … -
Django + React App: Getting 404 Errors for Static Files
I am currently working on a Django + React web application and I've encountered an issue with serving static files. The Django development server is returning 404 errors for several static files and images, like images "K5.png," "earth.png," and "manifest.json." Yes, the website loads, except for the images. This is how I refer to my images (example): <img src="/earth.png" alt="" className="earth w-fit mx-auto"/> I've configured my settings as follows: STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR_FRONTEND, 'frontend/build/'), ] import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR_BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR_FRONTEND = os.path.dirname(BASE_DIR_BACKEND) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Installed Application 'api', 'rest_framework', 'djongo', 'pymongo', "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", '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', ] CORS_ALLOW_METHODS = ( "GET", ) ROOT_URLCONF = 'project_k5.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR_BACKEND, '../frontend/build')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
Reverse url fails with re_path after migrating to Django 4 from Django 2
After migrating to Djanogo 4 from Django 2 I started having issues with the reverse path urls in templates. The following error was thrown: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with arguments '('MQ', 'bwachb-fa5e0484e188dc10f2573f3eedf2dd11')' not found. 1 pattern(s) tried: ['en/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] I created a test case to reproduce this issue: def test_reverse_activation_url(self): url = reverse('activate', args=['MQ', 'bwachb-fa5e0484e188dc10f2573f3eedf2dd11']) self.assertEqual(url, "/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/") Originally the urlpatterns was like this, and I managed to reproduce the same error running the testcase. urlpatterns += i18n_patterns( Django2: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'), Django4: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'), ) If I change the urlspatters as follows: urlpatterns += i18n_patterns( re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})', core_views.activate, name='activate'), ) The test case will fail because of no trail slash: AssertionError: '/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11' != '/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/' - /en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11 + /en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/ ? + If I change the urlspatters as follows, the test will pass. urlpatterns += i18n_patterns( path('activate/<uidb64>/<token>/', core_views.activate, name='activate'), ) Why is there a difference in the link generated when using re_path and path? Mainly in this case the trail slash. I also tried: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/?$', core_views.activate, name='activate') Which results NoReverseMatch And: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/?', core_views.activate, name='activate') Which results in the link with no trail slash error. Can someone please shed some light into this? I already wasted so many hours... I am currently on Django==4.2.5