Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding multiple random objects to ManyToManyField, based on user input
I am new to Django and attempt to create a geography game/quiz app. In a first step, the player chooses some game settings (number of rounds, difficulty, region/area). Based on the user's input, I want to assign countries to the user. In particular, I created these two classes in model.py. class Country(models.Model): name = models.CharField(max_length=90) code = models.CharField(max_length=15) subcontinent = models.CharField(max_length=25) subcontinent_code = models.CharField(max_length=15) continent = models.CharField(max_length=25) continent_code = models.CharField(max_length=15) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=90) number_rounds = models.IntegerField(default=10) difficulty = models.CharField(max_length=100, default='easy') area = models.CharField(max_length=100, default='world') countries = models.ManyToManyField(Country) def __str__(self): return self.name I created the corresponding forms.py for user input: class SetGameSettings(forms.ModelForm): class Meta: model = Player fields = ['name', 'number_rounds', 'difficulty', 'area'] labels = { 'name': 'Enter your username', 'number_rounds': 'Number of rounds', 'difficulty': 'Difficulty', 'area': 'Area', } widgets = { 'number_rounds': forms.NumberInput(attrs={'min': 1, 'max': 20}), 'difficulty': forms.Select(choices=[('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard')]), 'area': forms.Select(choices=[('World', 'World'), ('Africa', 'Africa'), ('Asia', 'Asia'), ('Europe', 'Europe'), ('Americas', 'Americas'), ('Oceania', 'Oceania')]), } And this is what views.py looks like: def home(request): if request.method == 'POST': form = SetGameSettings(request.POST) if form.is_valid(): form.save() #direct to next url form = SetGameSettings() return render(request, 'geo/home.html', {'form': form}) Until here, everything works fine. My … -
Data saved in session in a view is not saved in pytest session. Why?
I am making a website with Django and would like to test the data stored in session with pytest. I have a very simple view : def dev_my_view(request): if request.method == "POST": post_data = json.loads(request.body.decode("utf-8")) product_id = post_data["productid"] request.session["basket"] = {"id": product_id} # print(request.session.items()) returns # dict_items([('foo', 'bar'), ('basket', {'id, '99'})]) # as expected response = JsonResponse({"id": f"product number {product_id}"}) return response Here is the test I have written : class TestViewsWithSession(TestCase): def test_my_view(self): session = self.client.session session["foo"] = "bar" session.save() url = reverse("home_page:my_view") response = self.client.post( url, json.dumps({"productid": "99"}), content_type="application/json", ) # print(session.items()) returns # dict_items([('foo', 'bar')]) # Test passes self.assertEqual(response.status_code, 200) # Test passes # response.content = b'{"id": "product number 99"} self.assertJSONEqual(response.content, {"id": "product number 99"}) # Test fails. KeyError: 'basket' self.assertEqual( session["basket"], {"id": "99"}, ) self.assertNotEqual( session["basket"], {"id": "Invalid value"}, ) When I add data to the session in the test (session["foo"] = "bar"), the session contains this data in the view. But, it looks it does not work the other way ... When some data is added to the session in the view (request.session["basket"] = {"id": product_id}), I cannot see this data in the test. Why ? -
404 for static images and media in Django in Production Mode
I am beginner in Django I am trying to run my application on Debug=False mode to simulate the production environment, I have added all the static url, and roots. My program is generating the static images in real-time from the video passed to the application during runtime. This is working as expected in the development mode but I am getting 404 for images and videos in the production mode other stuff like bootstrap and JS are getting loaded fine. Earlier bootstrap and js was also not loading then I installed Whitenose and things start working, but now images and videos and giving 404. Link to the application code: https://github.com/abhijitjadhav1998/Deepfake_detection_using_deep_learning/tree/master/Django%20Application Further to this application, I have added the STATIC_ROOT in the settings.py and added os.system('python manage.py collectstatic --noinput') in the views.py folder to populate the static path with images and videos before sending the response to the html page. But still I am getting the 404, I also checked the file with same name is avaliable in the location. I am getting the below error: Error from the console: Able to load the js, bootstrap but able to load the images and video Code from settings.py that I have added DEBUG … -
Django Celery task doesn't fire in development
I'm trying to make use of periodic tasks but can't make it work. I have this test task # handler/tasks.py from celery import Celery app = Celery() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 2 seconds. sender.add_periodic_task(2, test.s('hello'), name='add every 2') @app.task def test(arg): print(arg) Celery is configured # project dir # salaryx_django/celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'salaryx_django.settings') app = Celery('salaryx_django') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) # salaryx_django/settings.py # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/London' The workers are intiated [2022-04-25 14:57:55,424: INFO/MainProcess] Connected to redis://localhost:6379// [2022-04-25 14:57:55,426: INFO/MainProcess] mingle: searching for neighbors [2022-04-25 14:57:56,433: INFO/MainProcess] mingle: all alone [2022-04-25 14:57:56,452: WARNING/MainProcess] /Users/jonas/Desktop/salaryx_django/venv/lib/python3.8/site-packages/celery/fixups/django.py:203: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('''Using settings.DEBUG leads to a memory [2022-04-25 14:57:56,453: INFO/MainProcess] celery@Air-von-Jonas ready. and Redis is waiting for connections but nothing happens at all.. Sanity Check … -
Daphne doesn't see heroku environment variables
I'm trying to deploy my Django & Channels app to Heroku, everything works fine in the deployment except that Daphne doesn't use any specified environment variables. I have tried to print the value of env variables from settings.py and they are exist and correct, so I think there should be a way to let asgi.py read them from settings.py but I haven't found anything in my search. my settings.py SECRET_KEY = os.environ.get( 'SECRET_KEY', 'django-insecure-pff2j7g9=9^d42-j_7)-u6kw@(%dx^bg+-q!(!cd3hhp$sn1_5') DEBUG = os.environ.get('DEBUG', True) ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '*').split(',') WSGI_APPLICATION = 'mtp.wsgi.application' ASGI_APPLICATION = 'mtp.asgi.application' EVENTSTREAM_STORAGE_CLASS = 'django_eventstream.storage.DjangoModelStorage' DATABASES = {} DATABASES['default'] = dj_database_url.config( default="postgres://postgres:121312@localhost:5432/mtp") my asgi.py import notification.routing import os from django.core.asgi import get_asgi_application from django.urls import re_path as url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mtp.settings') application = ProtocolTypeRouter({ 'http': URLRouter([ url(r'^sse/', AuthMiddlewareStack( URLRouter(notification.routing.sse_urlpatterns) )), url(r'', get_asgi_application()), ]), }) Procfile web: daphne mtp.asgi:application --port $PORT --bind 0.0.0.0 -v2 Heroku variables Thank you. -
Can you explain why this Django syntax worked?
I'm not sure why seller=request.user worked on my end. I didn't assign any "user" variable and yet I still was able to get the user's username. def create_listing(request): if request.method == "POST": listing = Auction_listing( title=request.POST.get('title'), description=request.POST.get('description'), min_bid=request.POST.get('min_bid'), image_url=request.POST.get('image_url'), category=request.POST.get('category'), seller=request.user ) listing.save() return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/create_listing.html") -
NoReverseMatch at /control/newsletter-list/
Working on a college project, close to finishing off a newsletter app but am running into an issue. I am receiving the error "NoReverseMatch at /control/newsletter-list/" as I am trying to create a detail view for the newsletter. I realize I am following an older tutorial so I am having to fix a lot of old code, cant figure this out however. Any help would be appreicated. -
How to save many to many relations
i want to save the many to many relations, but i get this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use users.set() instead. models.py class Department(models.Model): id = models.AutoField(primary_key=True) department = models.CharField(max_length=60) info_grafana = models.TextField() users = models.ManyToManyField(User) views.py class ViewUserAccount(View): """ Description: Страница выбранного пользователя """ def get(self, request, id_account: int, *args, **kwargs) -> render: return render(request, 'settings/UserAccount.html', { 'title': f'Аккаунт пользователя {request.user}', 'account': User.objects.get(id=id_account), 'direction': Department.objects.all() }) def post(self, request, id_account, *args, **kwargs): id_direction = request.POST.get('direction_id') id_project = request.POST.get('project_id') if id_direction: direction = Department.objects.get(id=id_direction) direction.users = User.objects.get(id=id_account) direction.save() if id_project: pass return redirect(request.META.get('HTTP_REFERER')) how should i solve this problem? -
Can't pip install pathlib on M1 Mac
When I run pip install pathlib==1.0.1 I get the following error: error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/4l/rwj9f3x12qs0nbw_dq3prw2c0000gn/T/pip-install-g5u_0nde/pathlib_adb255351e05488f95986f7a8775e1f0/setup.py", line 6, in <module> setup( File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_distutils/core.py", line 109, in setup _setup_distribution = dist = klass(attrs) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/dist.py", line 460, in __init__ for ep in metadata.entry_points(group='distutils.setup_keywords'): File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 999, in entry_points return SelectableGroups.load(eps).select(**params) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 449, in load ordered = sorted(eps, key=by_group) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 997, in <genexpr> dist.entry_points for dist in unique(distributions()) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 609, in entry_points return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 917, in read_text return self._path.joinpath(filename).read_text(encoding='utf-8') AttributeError: 'PosixPath' object has no attribute 'read_text' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. Any idea how to solve the error? Version 1.0.1 is the version I need and I have seen m1 laptops with pathlib version 1.0.1 on them -
Django get JSON object sent from Javascript to Django Views
I need to pass a Json Object value after making an API call to my views.py in order to render in django template. After making an ajax call I'm not able to get the value in django` let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = application.applicationId $.ajax({ type: "GET", dataType: "json", url: `${url}/${kycStatus}`, headers: { 'Content-Type': 'application/json', 'X-API-Key': '', }, data: { senddata: JSON.stringify(), }, success: function(data) { document.getElementById("kyc-status").innerHTML = data.overallResult.status console.log(data.overallResult.status) } })` in my views.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def kycsubmit(request): """ A view to return the index page""" if is_ajax(request=request): if request.method == 'GET': data = request.GET.get('senddata') print(data) return render(request, 'kycsubmit/onboard.html') -
Django i18n External Redirect security issue
(I'm new with Django) I ran an automated scan (OWASP ZAP) to test my application security and it's returning a high risk flag for External Redirect: Automated Scan Alert Looks like it's something to do with the path "/i18n/setlang/" and the parameter "next", like "?next=(redirect)" I set the i18n path like that urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ... ] And this is my HTML <div class="flex justify-items-end"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <form action="{% url 'set_language' %}" method="post" id="form_{{ language.code }}" style="display:inline!important;"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="{{ language.code }}" /> </form> <button class="lang-button" type="submit" form="form_{{ language.code }}" value="Submit"> {% if language.code == "en" %} <img src="{% static 'assets/webfonts/gb.svg' %}" width="30" alt="gb" class="rounded-lg h-5 w-5 mr-3 hover:opacity-75" /> {% endif %} {% if language.code == "es" %} <img src="{% static 'assets/webfonts/es.svg' %}" width="30" alt="gb" class="rounded-lg h-5 w-5 hover:opacity-75" /> {% endif %} {% if language.code == "pt" %} <img src="{% static 'assets/webfonts/br.svg' %}" width="30" alt="gb" class="rounded-lg h-5 w-5 mr-3 hover:opacity-75" /> {% endif %} </button> {% endfor %} </div> I don't know if it's … -
How can I apply logic is the user present in the Frontend Order Model?
I just want If a user Ordered something then the user will be able to rate on the order else can't and will show an error message "You didn't purchase any website". I applied logic 5/6 times in different ways but I couldn't fix the issues. Oeder Model: class Frontend_Order(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE,related_name='user_frontend_order') Service_Type = models.CharField(max_length=250, null=True) Price = models.CharField(max_length=250, null=True) Number_of_Section = models.CharField(max_length=250, null=True) Per_section_Price = models.CharField(max_length=250, null=True) Website_Functionality = models.CharField(max_length=50, null=True) Email = models.EmailField(max_length=50, null=True) files = models.FileField(upload_to="0_frontend_files/", null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, null=True) order_message = models.ForeignKey(Message_Manu,on_delete=models.CASCADE, null=True, related_name="message") def __str__(self): return str(self.pk)+ str(".") + str(self.USer) Rating Model: class Frontend_Rating(models.Model): USer = models.OneToOneField(User,default=None,on_delete=models.CASCADE, related_name="frontend_rating") Rating = models.IntegerField(null=True) Feedback = models.TextField(max_length=250, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) + str("(") + str(self.Rating) + str("stars") +str(")") Order View: def frontend_order_rating(request): if request.user.is_authenticated: if request.method == "POST": frontend_rating = int(request.POST.get('frontend_ratting')) frontend_feedback = request.POST.get('frontend_feedback') try: Frontend_Rating.objects.create( USer = request.user, Rating = int(frontend_rating), Feedback = frontend_feedback ) messages.success(request,f"{request.user.first_name}, Thank You for your feedback!") return redirect("/", userz = request.user) except: messages.error(request,f"{request.user.first_name}, Sorry! You've already given a feedback!") return redirect("/", userz = request.user) else: messages.error(request,"Please login or create an account.") return redirect("/") -
How to get with query nested comments?
I am new to django. I'm trying to deal with queries on nested comments. There is a blog project with adding articles and adding comments to articles. For each comment, you can recursively add a comment, and so on. ├── blog_api │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├──── blog_api/api | ├── admin.py | ├── apps.py | ├── __init__.py | ├── migrations | │ └── __init__.py | ├── models.py | ├── permissions.py | ├── serializers.py | ├── tests.py | ├── urls.py | └── views.py └── manage.py I described the following models api/models.py from django.db import models class Article(models.Model): date_pub = models.DateTimeField(auto_now_add=True) title = models.CharField (max_length = 60, blank=True, default='') text = models.TextField(blank=True, default='') owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE) class Meta: ordering = ['date_pub'] class Comment(models.Model): date_pub = models.DateTimeField(auto_now_add=True) text = models.TextField(blank=False) owner = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE) article = models.ForeignKey('Article', related_name='comments', on_delete=models.CASCADE) parent = models.ForeignKey('self', related_name='reply_set', null=True, on_delete=models.PROTECT) class Meta: ordering = ['date_pub'] api/serializers.py from rest_framework import serializers from api.models import Article from api.models import Comment from django.contrib.auth.models import User class ArticleSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Article fields = ['id', 'title', 'text', 'owner', 'comments'] class UserSerializer(serializers.ModelSerializer): … -
Django - How to automatically change the value by selecting different options
I'm quite noob on jquery, so i'm wondering if there's any method to meet my needs. I've got a select box with different options and how to change the value automatically by clicking different values in the select box? enter image description here enter image description here Which means if i choose the value 1 in the first box, the second box value is 1, and it will turn to 2 automatically by select another option in the first box. How to meet my needs? -
How to send Text box data from frontend to backend in python & django web application
I have dropdown button on my html page, which has 4 option and out of four one is other, and when I select other a text box open. Now I want to send the data to backend from textbox for further operations. I am sharing dropdown button i.e. HTML code <html> <head> <script type="text/javascript"> function CheckColors(val){ var element=document.getElementById('color'); if(val=='pick a color'||val=='others') element.style.display='block'; else element.style.display='none'; } </script> </head> <body> <select name="color" onchange='CheckColors(this.value);'> <option>Choose a option</option> <option value="one">ONE</option> <option value="two">TWO</option> <option value="others">others</option> </select> <input type="text" name="color" id="color" style='display:none;'/> </body> </html> Now I want is that when put text is should go to the python script. also it should update after every letter user give. What I have to update in Vies.py and url.py. Thanks in advance. -
How to add user photo to JWT auth tokens in django?
Is it posible to have an image information added to jwt auth token like any other user data? If it s posible, someone please can you help with the solution I'll highly wholeheartedly appreciate it.. Here's how I added the other user data to the jwt token.. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @class method def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['occupation'] = user.profile.occupation token['biography'] = user.profile.biography I hope this helps, and please if you need any file to help better understand the situation, I'll definitely be glad to submit it.. Thanks In advance. -
Django DRF filtering fields in serializer
I'm new to Django DRF and I'm trying to write a more organized code since the one below lacks the correct approach. I have 2 API endpoints: /api/order/info - which shows all the order fields /api/order/status - which shows only one field At the moment I have two serializers and two views as follows: serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['order_id', 'data', 'status'] class OrderStatusSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['status'] views.py # /api/order/info - retrieves all fields class OrderInfo(generics.RetrieveAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer def get_object(self): try: return Order.objects.get(pk=self.request.data['uuid']) except Order.DoesNotExist: raise Http404 # /api/order/status - retrives just one field, the status class OrderStatus(generics.RetrieveAPIView): queryset = Order.objects.all() serializer_class = OrderStatusSerializer # a serializer just for this def get_object(self): try: return Order.objects.get(pk=self.request.data['uuid']) except Order.DoesNotExist: raise Http404 The problem: the code works as expected, but it is pretty clear that it is duplicate! I'm creating a new serializer for just filtering one field, but I strongly believe that DRF makes this easier in some way. Could you please suggest a better approach? Thanks -
Adding related model in separated page Django Admin
The problem is following: All fields are not displayed when I add model for related model using TabularInline but at another side I don't want to use StackedInline, cuz it seems to be not pretty. So, is it possible to use another page to add model for related model, that it automatically will be added to corresponding Partner. Maybe is it possible to use StackedInline for one reason and TabularInline to another, or something similar? Or override adding link? What exactly do I want Displaying: Adding: -
Webhook listener with csrf
I want to create a webhook listener for a third party app. But fot this i have to use @csrf_exempt . Without using the above my web app isn't allowing the third party app to send the webhook data. It blocks it and says forbidden. My question is if we do it without the csrf token can it cause a security vulnerability? What are the other ways to handle this securely. -
Regular expression to validate US phone numbers using Formik and Yup
I'm trying to validate us phone numbers inside my formik form using yep. I found some information on regex here on stackoverflow but it doesn't seem to be working. I basically need to be able to allow brackets, dashes and spaces aswell as the country code. The backend converts everything into something like this: (123) 123-1234 This is what i tried: validationSchema={Yup.object({ AdministratorCell: Yup.string() .matches(/([0-9]{3})[0-9]{3}-[0-9]{4}/, { message: "Invalid phone number", excludeEmptyString: false, }) })} I'm using https://github.com/google/libphonenumber in the backend for backend validation of those phone numbers which is why i need frontend validation to properly work or the form won't submit in some cases where users forget a number or format the number in a certain way. My issue is with what i tried so far is that i can only add the phone number with a certain formatting or it will not submit to the backend. -
Printing Django session data makes pytest tests fail, why?
I am creating a Django app and trying to write test with pytest. I have a weird issue when testing data stored in session. I have a standard view. def dev_my_view(request): if request.method == "POST": post_data = json.loads(request.body.decode("utf-8")) product_id = post_data["productid"] request.session["basket"] = {"id": product_id} response = JsonResponse({"id": f"product number {product_id}"}) return response This test passes as expected. # TEST PASSES OK def test_my_view_OK(self): the_session = self.get_session() self.set_session_cookies(the_session) url = reverse("home_page:my_view") response = self.client.post( url, json.dumps({"productid": "99"}), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content, {"id": "product number 99"}) self.assertEqual( the_session["basket"], {"id": "99"}, ) self.assertNotEqual( the_session["basket"], {"id": "Invalid value"}, ) But this test fails... # TEST KO def test_my_view_KO(self): the_session = self.get_session() self.set_session_cookies(the_session) print_session_in_tests(the_session) # Session is empty, ok url = reverse("home_page:my_view") response = self.client.post( url, json.dumps({"productid": "99"}), content_type="application/json", ) print_session_in_tests(the_session) # Session is empty, why ? self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content, {"id": "product number 99"}) # The following test fails. KeyError: 'basket' self.assertEqual( the_session["basket"], {"id": "99"}, ) self.assertNotEqual( the_session["basket"], {"id": "Invalid value"}, ) So it looks like the function print_session_in_tests is responsible for that ... Why ? def print_session_in_tests(my_session): print("----------// SESSION (test) //----------") try: for key, value in my_session.items(): print("{} >>> {}".format(key, value)) except: pass print("------- end of printing session ------") pass For information, … -
hmx and django: return HX-Trigger header with json data show error `SyntaxError: JSON.parse...`
I'm following the examples in https://htmx.org/headers/hx-trigger/ my view def my_view(request): res = render(request, 'index.html') res.headers["HX-Trigger"] = ... return res this code works res.headers["HX-Trigger"] = "showMessage" while below code will cause error SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data res.headers["HX-Trigger"] = {"showMessage": "Here Is A Message"} What should I do? -
Django template return POST array
I have an issue about returning data array in POST. I do not find a way to do it... Here the code, I remove not necessary part of the code : View def viewPro(request): if request.method == 'POST': if bool(request.FILES.get('file', False)) == True : ... if analyseType == 'r': ... elif analyseType == 'm': fc, dRect, ctrlRect = ExtractData(file, analyseType) context = { ... 'f' = True, 'fc' = fc, 'dRect': dRect, 'ctrlRect': ctrlRect, } return render(request, 'ctd.html', context) else: ... dRect = request.POST.get("dRect") ctrlRect = request.POST.get("ctrlRect") fc = request.POST.get("fc") UpdateData(fc, dRect, ctrlRect) img_out_path = executectd(..., fc, dRect, ctrlRect) context = { 'filename': img_out_path, } return render(request, 'result.html', context) else: ... (different forms) context = { 'f' = False ... } return render(request, 'ctd.html', context) Template {% if factors %} <br> <div class="card"> <div class="card-body p-5"> <div class="text-center mb-5"> <h2 class="h4 fw-bolder popup"> cf </h2> <h6 class="popup"> <img src="{% static 'assets/help.jfif' %}" onclick="showContextualHelp('cf')"> <span class="popuptext" id="cf"> Fill here the cf </span> </h6> <br> <div class="container"> <div class="row gx-5 justify-content-center"> <table> <thead> <tr> </tr> </thead> <tbody> {% for key, value_list in fc.items %} <tr> <th>{{ key }}</th> {% for value in value_list %} <td><input class="form-control" value="{{ value }}" {{ value }}></td> … -
Subscribe to google and outlook calendar through url causing problems
I'm working on a project using Django Rest Framework and icalendar. I've created an api which provides ics file for download. Users are provided with a url to the download api which they use to subscribe. However they are experiencing unexpected behaviour upon subscription. In case of google calendar it doesn't resync automatically at all. In one instance the calendar was subscribed successfully but there were no events being displayed on google calendar. Can anyone help confirm whether there is an issue with google calendar or am I missing something. for example not generating the file correctly views.py @action(detail=True, methods=['get'], permission_classes=[AllowAny], authentication_classes=[]) def download_file(self, request, *args, **kwargs): instance = self.get_object() ics_data = instance.ics_data file_name = "somefile" response = HttpResponse(ics_data.encode(), content_type='text/calendar') response['Content-Disposition'] = 'attachment; filename=%s.ics' % file_name return response sample url: https://api-mycompany.com/users/11184/calendar/download_file/ sample ics data: BEGIN:VCALENDAR VERSION:2.0 PRODID:-//my company calendar// BEGIN:VEVENT SUMMARY:This Event DTSTART;VALUE=DATE-TIME:20220321T054500Z DTEND;VALUE=DATE-TIME:20220321T070000Z DTSTAMP;VALUE=DATE-TIME:20220419T085236Z UID:113874 DESCRIPTION:Some Event LOCATION:My Studio END:VEVENT END:VCALENDAR -
"django_admin_log" violates foreign key constraint
We have an application that uses custom login Middleware. We authenticate users from the token. The problem is that when this user wants to change any entry in admin panel, it gives an IntegrityError. insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(567) is not present in table "auth_user". because this user is not in auth_user table, we set it to request.user only while authenticate with our external authentication system. how we can solve this issue?