Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to translate a variable template ( random value ) in django
I want to build a website using Django. My website supports two languages, English and Vietnamese. In models.py : from django.db import models class Order_product(models.Model): name = models.CharField(max_length = 255) note = models.TextField() status = models.CharField(max_length = 255, choices = [('Pending', 'Pending'), ('Need-Delivery', 'Need-Delivery'), ('Delivery', 'Delivery'), ('Success', 'Success'), ('Return-Order', 'Return-Order'), ('Cancel', 'Cancel')]) In views.py i have code like that from django.shortcuts import render from .models import * def test(request): get_order = Order_product.objects.all() return render(request, 'test/test.html', {'get_order ':get_order}) In template test.html {% for each_order in get_order %} <p> {% blocktranslate %} {{ each_order.status }} {% endblocktranslate %} </p> {% endfor %} after that, i run : python manage.py complimessages. In django.po file i have : msgid "" "\n" " %(each_order.status)s" " " msgstr "" I want to translate the template variable each_order.status based on its value. If the variable each_order.status has the value 'Success,' it should be translated to 'Thành công' in Vietnamese, ... How can I use Django for translation? I've done a lot of research but haven't found a suitable solution. Thank you very much. -
How do I rotate a Paragraph in reportlab in SimpleDoc Template
I have this reportlab pdf generator app I am building and I am using SimpleDocTemplate as my page template. I cannot seem to be able to rotate a Paragraph by 90 degrees as intented. Does anyone have a solution to this? #---- file_number1 = f"<font name='Helvetica' size='11'><b>{parcel.FileNumber}</b></font>" file_number1_style = styles['BodyText_FileNumber'] file_number1_style.leftIndent = -320 file_number1_data = Paragraph(file_number1, file_number1_style) elements.append(file_number1_data) elements.append(Spacer(1, -5)) #---- There is no rotate attribute on Paragraph. Is there another way? -
tying to install mysqlclient in Windows 11 getting an error
I want to install pip install mysqlclient but also pip install mysql on a Windows 11 Machine, I am getting the below error, I have already search to fix this error, but not get successful, how can I install mysqlclient? because I want to migrate my django project data to the mysql database? "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD "-Dversion_info=(2, 2, 0, 'final', 0)" -D__version__=2.2.0 -IC:/mariadb-connector\include\mariadb -IC:/mariadb-connector\include "-IC:\Users\Jamshid\OneDrive\Documents\My Programming Practices\Python\Basic CRM Tool\dcrm\virt\include" -IC:\Python312\include -IC:\Python312\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\cppwinrt" /Tcsrc/MySQLdb/_mysql.c /Fobuild\temp.win-amd64-cpython-312\Release\src/MySQLdb/_mysql.obj _mysql.c src/MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Failed to build mysqlclient ERROR: Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects -
Can't varify access token in middleware nextjs
I am trying to verify my token in nextjs middleware using jose library.But if any case the code gose into the catch block it the enter into a infinite loop and dosen't redirect to the login page.Actually,i have never authenticate token before so i am kind of confused what should i do. This problem specially happened when someone change the access token in the browser.This is my code that i have done so far. import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { jwtVerify } from 'jose'; export default async function middleware(request: NextRequest) { const access = request.cookies.get("access")?.value; const url = request.url; const urlStartWithUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/open-bo-account`; const redirectUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/login/`; if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) { request.cookies.clear() return NextResponse.redirect(new URL('/login', request.url)); } else if (access) { try { const secret = new TextEncoder().encode( "secret key" ); const decodedToken = await jwtVerify(access, secret); if (decodedToken) { return NextResponse.next(); } request.cookies.clear(); return NextResponse.redirect(new URL('/login', request.url)); } catch (error) { const cookiesBeforeClear = request.cookies.getAll(); console.log("Cookies before clear:", cookiesBeforeClear); request.cookies.clear(); const cookiesAfterClear = request.cookies.getAll(); console.log("Cookies after clear:", cookiesAfterClear); return NextResponse.redirect(new URL('/login', request.url)); } } } -
Why is my global dictionary value is changed in different views in Django?
In my Django app I have a global dictionary that stores some instances of a Class. Valu of this dictionary is being changed by one of my Django views. Then I use that global dictionary inside my other views. The problem is, in production, when I access this global dictionary in other views, value of it is changed (global dictionary changes to its initial value). I deployed Django app on Ubuntu server using Gunicorn and Nginx. Here is the scenario: my_global_dict = {} # This is the global dictionary with initial value of empty dict def view1(request): my_global_dict["key0"] = myClass() # Adding my class instance to the global dict ... def view2(request): print(my_global_dict) # Prints: {}. The global dict is empty in this view and others ... I emphasize that there is no problem in the process in the development environment. Also it works with Apache and IIS with ease. The problem I'm facing is after deploying on Gunicorn and Nginx. Thanks in advance! -
django-hitcount not recording ip adresses in hit
So, i'm using django-hitcount to keep track of user hits in my application. the application uses uuid as primary key for id of the books. so, i did a little modification to the django-hitcount code from here. the exact new version isnt compatible so i used it upto a specific commit. the forked repo is here. I only changed the object_pk on the hitcountbase model to uuid and removed the previous id which was used as a primary key. You can check the commit in here Running it on my project it is not recording the ip addresses of the hits and putting in the default 10.0.0.1 ip address on every data it tracks. Did I miss to change something while making it work with uuid? -
Django Convert image format to .webp (ResizedImageField)
I'm trying to use ResizedImageField instead of ImageField in Django to convert image files to .webp format. Most of the images work fine, but I'm having an issue with raw images taken by my iPhone. When I upload these raw images, they are rotated 90 degrees for some reason. However, if I edit these raw images (like cropping them), they are not rotated. I'm using django-resized version 1.0.2. This is my models.py class ArticleImage(models.Model): # upload_file = models.ImageField(upload_to='article/image/%Y/%m/%d/', null=True, blank=False) upload_file = ResizedImageField(size=None, upload_to='article/image/%Y/%m/%d/', quality=95, force_format='WEBP', null=True, blank=False) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='image', null=True) def delete(self, *args, **kargs): # 데이터 삭제 시, 실제 파일도 삭제 if self.upload_file: os.remove(os.path.join(settings.MEDIA_ROOT, self.upload_file.path)) super(ArticleImage, self).delete(*args, **kargs) def filename(self): return os.path.basename(self.upload_file.name) This is my setting.py DJANGORESIZED_DEFAULT_KEEP_META = False DJANGORESIZED_DEFAULT_QUALITY = 95 DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'WEBP' DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'WEBP': ".webp"} DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = False I have tried adding DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = False, but still does not work. -
How do I run code once immediately after an object is created?
I'm working on an internal tool built using Django. Part of what we're doing with this tool is digitizing content from old PDFs. The PDFs have been through some kind of OCR process, but it has left them with frequent doubled or tripled spaces and hard returns at the end of every line. We're using this text to create database objects in Django's built-in admin. Imagine I have a data model like this: import re from django.db import models from django.db.models import CharField, TextField class Widget(models.Model): name = CharField() description = TextField() def fix_description(self): self.description = re.sub(r"\s+", " ", self.description) self.description = re.sub(r"\\n", "\n", self.description) self.description = re.sub(r" *\n *", "\n", self.description) Most of the time, the text in description will be a single paragraph. Occasionally it should contain actual line breaks, which I'd like to denote by typing \n into the description field in Django admin when creating the object. The fix_description method cleans up unintended whitespace exactly as we'd like, and keeps line breaks entered manually. What I'd like is to have fix_description run exactly once when the object is created through the Admin form, and then never again. I don't want to worry about having this code … -
How can I use a variable in the field of m2m?
First I am extracting the model name of the M2M field from the value I get through the loop. Then I am trying to add data to m2m table, but this AttributeError: 'ProductAttributes' object has no attribute 'm2m_model' is coming. attribute = ProductAttributes.objects.get(pk=pk) for key in common_keys: if initial[key] != new_data[key]: # Getting m2m model in lower case m2m_model = apps.get_model(app_label=app, model_name=key)._meta.model_name attribute.m2m_model.add(new_data[key]) Here's the problem attribute.m2m_model.add(new_data[key]) If I directly name the field then it works fine like below: attribute.color.add(new_data[key]) attribute.ram.add(new_data[key]) I want to make it dynamic. Here is my model: class ProductAttributes(models.Model): color = models.ManyToManyField('Color') band_color = models.ManyToManyField('BandColor') ram = models.ManyToManyField('RAM') vram = models.ManyToManyField('VRAM') Thanks in advance, any help would be much appreciated. -
Fuzz-testing Django application with atheris
I'm running my Django-project: cd PycharmProjects/Autopark source venv/bin/activate python3 manage.py runserver This is insides of project's wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'autopark.settings') application = get_wsgi_application() After that I open another tab of my terminal (I'm using Linux Mint) and start my fuzz-test script via the same venv: source venv/bin/activate python3 fuzz_test1.py That's first few strings from that file: import os import django django.setup() from django.test import Client client = Client() And I have an error at django.setup(): Traceback (most recent call last): File "/home/paberu/PycharmProjects/Autopark/fuzz_test1.py", line 4, in <module> django.setup() File "/home/paberu/PycharmProjects/Autopark/venv/lib/python3.10/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/paberu/PycharmProjects/Autopark/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/home/paberu/PycharmProjects/Autopark/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't have any idea of what am I doing wrong. Can you help me get rid of that error? -
mysql: how to resolve duplicate key errot
My django project has a migration that creates a foreign key on a table. When the migrate command is executed, I receive a stacktrace with error : MySQLdb._exceptions.OperationalError: (1061, "Duplicate key name "..." I located the key in table_constraints and in table_constraints_extensions. It doesn't appear to be in any other constraint table. There is one instance of the same key in each table. The foreign key was created, and actually works, but the migration fails to complete due to duplicate keys. I'm just not sure exactly where the duplication is because the FK constraint appears once in each of the tables mentioned above. My project can function without doing anything further, but the migration process will be broken until I fix this in the db. How and where do I fix this problem? delete from table_constratins ... alter table projects_project drop constraint ... -
CSS making boxes too big and taking up all the required space
I'm using Django's HTML scripting to iterate through a list of tags from a ManyToManyField for an article. Getting the information works, but the actual sizing of the borders around the tags ends up being all wrong. The boxes are absurdly big. The titles also aren't where I want them to be, though that is on hold. The CSS is a combination of custom CSS and Tailwind (yes I know that's a bad practice, but I'm lazy). HTML: {% extends 'head.html' %} {% load static %} {% block content %} <h1 class="flex items-center justify-center text-6xl">Articles</h1> <br> {% if articles %} <div class="flex items-center justify-center"> <div class="posts"> {% for article in articles %} <a href="{{ article.get_absolute_url }}"> <div class="article_box"> <span>{{ article.article_title }}</span> <div> {% for tag in article.article_tags.all %} <div class="tag">{{tag}}</div> {% endfor %} </div> </div> </a> {% endfor %} </div> </div> {% endif %} {% endblock %} CSS: .posts { font-size: 20px; display: grid; gap: 4rem; grid-template-columns: repeat(3, minmax(0, 1fr)); padding-left: 12rem; padding-right: 12rem; } .posts div { aspect-ratio: 1; } .article_box { width: 3/12; border: 2px solid black; padding: 0.5rem; } .tag { border: 2px solid black; border-radius: 20%; padding: 0.25rem; margin: 0.15rem; } .tags { display: flex; flex-basis: … -
Is there a way to identify when a 'like' was put on a blog post?
I've got a standard blog post set up where users can like posts. I'd like to be able to work out which posts have had the most likes in a given time frame but I'm not sure how to identify when a like was attributed to a post. My Post model: class Post(models.Model): objects = PostManager() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, default=None, null=True) title = models.CharField(max_length=100) description = models.TextField(max_length=500) date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_like", blank=True) Other posts I've seen with a similar question have a Like model, is there a way I can do what I want using my current model or do I need to create a separate model for it? I was hoping to do something like adding auto_now_add=True to my likes attribute, similar to what I've done with date, but I know that only tells me when a blog post object was created. -
django celery tasks are executed before establishing a websocket connection
The user uploads the file to the form, after which the form with the file is sent to the server, and upon successful validation, I perform the following actions: def form_valid(self, form): storage = FileSystemStorage() file_path = storage.save(form.cleaned_data['file'].name, form.cleaned_data['file']) task = tasks.extract_text_from_pdf.delay(services.full_path(file_path)) return HttpResponseRedirect(reverse('pdf:download_result', kwargs={'task_id': task.id})) I temporarily save the file to the local file system and pass the file path to the celery task. After submitting the task to celeri, I redirect the user to another page where I establish a websocket connection to the server to be notified of the file processing result. In celery tasks, I open a file and perform the necessary actions with it, after which I send a message to the consumer. @shared_task def send_notification(message, task_id): channel_layer = get_channel_layer() room_group_name = f'download_result_{task_id}' async_to_sync(channel_layer.group_send)( room_group_name, { 'type': 'notification_message', 'message': message } ) @shared_task def extract_text_from_pdf(pdf_file_path): with open(pdf_file_path, 'rb') as file: reader = PdfReader(BytesIO(file.read())) text = "" for page in reader.pages: text += page.extract_text() + "\n" text = text.replace('\n', '\r\n') send_notification.delay(text, current_task.request.id) But I encountered a problem - celery tasks are executed faster than the websocket connection is established and as a result the message does not reach the client side. src.pdf_processing.tasks.extract_text_from_pdf[8f535575-803d-4679-8007-7a4404a372c1] succeeded in 0.148360932000287s: None … -
Resolving ImportError: Module "redis.connection" does not define a "HiredisParser" attribute/class
My django project has this issue after I updated my redis to version 5.4.0. It seems that the HiredisParser that I was using in my PARSER_CLASS in the redis configuration could not be found in this update. After taking a look at the change log, it seems the issue is a rename of the HiredisParser class from HiredisParser to _HiredisParser. So a simple change from this: "PARSER_CLASS": "redis.connection.HiredisParser" to this: "PARSER_CLASS": "redis.connection._HiredisParser" should fix the issue. Note that if hiredis package is already installed you can remove the whole line completely in your django cache configuration as it will by default select _HiredisParser if hiredis is installed. Relevant source: https://github.com/jazzband/django-redis/issues/676 -
How to change the value of a field in Django after a while?
I have a user model and I just added a premium field in it, now I want after expiration_date expired, the value of is_premium to change to False and, expiration_date and premium_time to change to none or something like that My user model: class User(AbstractUser): PREMIUM_TIME_CHOICES = ( (1, "1 Month"), (3, "3 Month"), (6, "6 Month"), (12, "12 Month") ) id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) is_premium = models.BooleanField(default=False) expiration_date = models.DateTimeField(blank=True, null=True) premium_time = models.CharField(blank=True, null=True, choices=PREMIUM_TIME_CHOICES, max_length=1) My siganls: @receiver(post_save, sender=account_models.User) def add_premium_time(sender, instance, **kwargs): if instance.is_premium: expiration_date = timezone.now() + timezone.timedelta(days=(instance.premium_time * 30)) instance.expiration_date = expiration_date instance.save() -
Page not found (404)/Request Method: POST
Only the seller should be able to sell the item by clicking the button and no one else can offer a price after that. Also, the winner must be specified here and the winner can view their products by entering the product page and also viewing the winners page. The winners page is also in the layout format and from there we should be able to see the product specifications that are in win.html. But now, by clicking on the button, it shows the error that I wrote. Please tell me what to do to fix it. thanks:) Page not found (404) No List matches the given query. Request Method: POST Request URL: http://127.0.0.1:8000/off/ Raised by: auctions.views.off views.py: @login_required(login_url="login") def win(request, username): try: your_win = List.objects.filter(user = username) except: your_win = None return render(request, "auctions/win.html",{ "user_winlist" : your_win, }) @login_required(login_url="login") def off(request): product = request.GET.get('productid', False) users = Bid.objects.filter(user = request.user) if users == (List.user): product.is_closed = True product.save() return win(request, request.user.username) return product_detail(request,product) product_detail.html: <ul> {% for offer in offers %} <li>{{ offer.user.username }} offered ${{ offer.offered_price }}</li> {% if user.id == user.id %} <form method="post" action="{% url 'off' %}"> {% csrf_token %} <input type="hidden" name="product" value="{{ product }}"> … -
how to generate a list of endoints using a specific func
In my django app I want to keep track of all endpoints that use a particular function inside them. Let's call the function caching_func. I encapsulate my endpoints inside view classes, such as this: class TemplateViewSet(GenericViewSet): @action( detail=False, methods=["GET"], ) def download(self, request, *args, **kwargs): """ Returns a Zip file with all generated template files. """ # Create a HttpResponse with the contents to download response = zip_file_download() # cache response caching_func(response) return response @action( detail=False, methods=["POST"], ) def upload(self, request, *args, **kwargs): """ Accepts an uploaded file """ response = do_upload_work() return response def get_queryset(self): return None You can see that caching_func is invoked inside the download endpoint but not inside the upload endpoint. When the server is started, I want to construct a list of the endpoints that use caching_func, and I want the output to be the full endpoint name, not just the method name. For instance, the snippet below is in the urls.py file of the app: router.register( r"template", TemplateViewSet, basename="download-template", ) urlpatterns = router.urls So if the final endpoint urls are /template/download/ and /template/upload/, then the list of endpoints that use caching_func should be ["/template/download"]. Please describe how you think I can achieve this. -
Django logger not logging log levels below Warning
I am trying to configure logger in the Django Framework. I have changed the logging level to DEBUG in both handler and logger and still the INFO log is not getting logged. It only shows log upto Warning and not further from there. # app/views/test.py # def test() print("#"*10, logger.level,logger.name) #Log level is 10 when printed logger.info("This is an informational message.") logger.debug("This is a debug message.") logger.warning("This is a warning message.") logger.error("This is an error message.") logger.critical("This is a critical message.") Setting.py file log dict LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level':'DEBUG' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', }, 'app': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } Output: WARNING 2023-12-05 07:06:46,934 test This is a warning message. ERROR 2023-12-05 07:06:46,935 test This is an error message. CRITICAL 2023-12-05 07:06:46,935 test This is a critical message. The INFO and DEBUG log level message is not logged. -
How long does the `httpx.AsyncClient` can "live" without closing the event loop?
I have an endpoint in Django that orchestrates a bunch of API calls to other underlying services. I intend to use a long-lived instance of httpx.AsyncClient - which will be ultimately responsible for the API calls. class Api: # for historical reasons, this class has both sync and async methods ... AsyncApi = partial(Api, async_client=httpx.AsyncClient(timeout=30)) class MyViewSet(viewsets.GenericViewSet): @action(...) def merge(self, request: Request) -> Response: ... result = async_to_sync(merge_task)(..., api=AsyncApi(jwt_token=request.auth)) ... I'm doing some tests in a dummy server and I can see that sometimes merge_task captures RuntimeError('Event loop is closed') when calling api (or, ultimately, the long-lived instance of httpx.AsyncClient) so I'd bet that the loop for httpx.AsyncClient is closed after some time and there's no issue with asgiref's async_to_sync. Am I correct? If so, the only solution is to instantiate httpx.AsyncClient on every request? I tried do call merge_task using the endpoint but it captured RuntimeError('Event loop is closed'). The expectation is to not raise any error related to async programming -
Pytest, get IntegrityError when inserting ForeignKey by id
I have such table structure class ParentModel(models.Model): symbol = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=200) class ChildModel(models.Model): parent_instrument = models.ForeignKey( to=ParentModel, on_delete=models.SET_NULL, null=True, blank=True, ) instrument = models.ForeignKey( to=ParentModel, on_delete=models.SET_NULL, null=True, blank=True, ) Then I run my pytest with empty database, where I test such logic try: ChildModel.objects.update_or_create( parent_instrument_id=symbol1, instrument_id=symbol2, ) except IntegrityError: self._create_instrument(symbol1, symbol2) I don't get IntegrityError. ChildModel is just saved without existing ParentModel symbol. Is it possible to avoid such behaviour? -
How can I change the delimiters in .vue file?
I'm trying to implement the signup function with django and vue. Below is the Signup.vue It only displays like {% csrf_token %} [[ form.as_p ]]. How can I show the form? <template> <div> <h1>SignUp</h1> <form method="POST"> {% csrf_token %} [[ form.as_p ]] <div class="mt-3"> <button type="submit" class="btn btn-primary">SignUp</button> </div> </form> </div> </template> <script> export default { delimiters: ['[[', ']]'], data() { return { form: {}, }; }, }; </script> The form is defined by using the CreateForm and the UserCreationForm as below. class SignUpView(CreateView): form_class = SignUpForm template_name = "Signup.vue" success_url = reverse_lazy("home") def form_valid(self, form): response = super().form_valid(form) username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user = authenticate(username=username, password=password, email=email) login(self.request, user) return response class SignUpForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password"] I had used delimiters like {{ }}, so I changed it into [[ ]]. But it didn't fix. -
Django rest Framework
While working on a project I suddenly started receiving this : Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: C:\Users\SayantanDutta\Code\Register2\venv\Lib\site-packages\django\db\models\query.py, line 647, in get Raised during: dj_rest_auth.registration.views.RegisterView Python Executable: C:\Users\SayantanDutta\Code\Register2\venv\Scripts\python.exe This happens when I try to register a user using postman or some other API calls Not sure why the library file is raising this exception? -
How to Integrate GTM with Partytown in Django Template
I am trying to integrate my GTM tag using Django Template. Following is my current html snipped that is working perfectly fine without partytown integration. <head> <script> (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', '<gtm-id>'); </script> </head> <body> <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=<gtm-id>" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> </body> Now i want to integrate it throught partytown approach, something I tried was following but doesnot work <script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID-HERE"></script> <script type="text/partytown"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'YOUR-ID-HERE'); </script> I just replaced my GTM ID in above template, this is the piece of code given in their documentation. If any one can integrate the conventional GTM code into the above partytown snipper please help, Im new to this library. Also note that I have integrated partytown library in my project so that is not a problem. No errors there just dont know how to integrate it. Thanks in advance -
Django site wide caching with vary on Cookie header caching per user response due to third party cookies
I am currently trying to set up the per-site-cache, it all seemed to work fine locally but once I moved it onto test servers with google analytics I noticed that it wasn't serving pages from the cache as expected. After a bit of digging I realised that this was due to another third party app that we are using (and need) that was accessing the session middleware, if the session middleware is accessed then Django will add 'Cookie' to the vary headers: # django/contrib/sessions/middleware.py if accessed: patch_vary_headers(response, ('Cookie',)) HTTP header: Vary: Cookie, Accept-Language The issue I have is that when Django is generating the cache key it is looking at all the cookies that are in the request, including third party ones (e.g. google analytics) which are nothing to do with Django and which do not impact on rendering the view. I don't want to monkey patch the third party Django app that we are using to stop is accessing the session. I could patch the vary headers to remove the vary on cookie header completely but I think that if the session middleware is setting the header then it is probably safer to leave it alone and just filter …