Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to detect the logged in user from Keycloak OpenID logout_token on back channel logout?
First let me describe the setup: We have a frontend Angular based product from a different client team (not part of code we can easily modify), and a backend django based API server. The front end logs in to a keycloak server, and when logged in, the backend gets an Auth header with a bearer token in every request. From this, we are able to identify the logged in user as follows (using python-keycloak): ret = keycloak.userinfo(bearer_token) username = ret['preferred_username'] This is obviously very wasteful since it needs an extra network request to keycloak everytime - so we create a django user session instead and use that for session management. Now when it comes to logging out, when the user logs out from the front end, we need to void the django session. I've setup the "Back channel logout URL" on the keycloak realm settings to call some endpoint on the django server. The endpoint gets called on logout, and it gets a "logout_token" value in the arguments. Now I'm not sure how I am supposed to identify which user is logging out based on this token. How can this be done? Thanks in advance... -
I cant use the objects attribute in django project
I created a Projects model class Projects(models.Model): name = models.CharField(max_length=257, unique=True, null=False) description = models.TextField() active_issue_count = models.IntegerField(default=0) # functiona bağlanmalı solved_issue_count = models.IntegerField(default=0) # functiona bağlanmalı is_active = models.BooleanField() start_date = models.DateTimeField() deadline = models.DateTimeField() and I want to use this project model Projects.objects.all() with this code but when I typed in pyCharm shows me this suggestion but while I try to use this model class User(AbstractUser, PermissionsMixin): objects = UserManager() related_group = models.CharField current_project = models.ForeignKey(to='core.Project', related_name='current_project', on_delete=models.PROTECT, null=True) total_worked_project = models.IntegerField(default=0) # functiona bağla active_work_project_count = models.IntegerField(default=0) # functiona bağla REQUIRED_FIELDS = ['email'] ` I can use User.objects.all() without suggestion what should I do anyone can help me ? -
You may need to add an 'await' into your view
I am working on a Django project which fetch status code from websites and save it in the database. I want to make it async otherwise it take too much time and gives an error. So after researching and watching tutorials I came up with this code but it throws the error in title. views.py @sync_to_async async def get_page(session, url, urlMain): async with session.get(url) as response: st_code= await response.status return url, st_code, urlMain @sync_to_async async def create_search(request): form = SearchForm() if request.method == 'POST': name = request.POST['name'] tasks = [] async with aiohttp.ClientSession() as session: for item in data: url = data[item]['url'] urlMain = data[item]['urlMain'] tasks.append(get_page(session, url, urlMain)) results = await asyncio.gather(*tasks) for url, st_code, urlMain in results: if st_code == 200: site_data = SearchResult( url = urlMain, sitename = item, ) site_data.save() context = {'form':form} return render(request, 'index.html', context ) This is the error django shows: Exception Value: The view main.views.SyncToAsync._call_ didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view. -
Read some datetime fields as UTC in Django
I have time zone support as active in my application settings USE_TZ = True So, all my DateTimeFields in my models are transformed from my local time zone to UTC before being saved to database. Question: In some cases, the user enters a datetime field value with day precision only like 2022-10-24 without time part, and I already accepts this format as an input. But in such case, I want to save this value without time zone, so that it will be parsed later without time zone. Why does this cause a problem? If a user enters a value 2022-10-24 and his local time zone is UTC+2, it will be saved in database as 2022-10-23 22:00:00 UTC. Once another user opens the same instance and his local time zone is UTC+1, he will see the value as 2022-10-23 23:00:00 while I want him to see it with the same value that the initial user enters it, so it should be 2022-10-24 00:00:00. Partially Failed Trial: I have tried to handle this in my ModelForm by parsing the entered format, then replacing the time zone info to UTC if it is with day precision. from pytz import UTC datetime_value = datetime_value.astimezone().replace(tzinfo=UTC) … -
Hosting Whatsapp bot Using Pywhatkit with Heroku
I used the Pywhatkit python library to automate sending whatsapp messages, it's working very well in localhost, I realized I have to keep my PC on 24/7 for this to work. So I thought about hosting on Heroku (I don't know if that is possible), so I put it on heroku, but every time I try to run my script in heroku, I get the following error. Heroku Error Traceback (most recent call last): File "/app/test.py", line 2, in <module> import pywhatkit File "/app/.heroku/python/lib/python3.10/site-packages/pywhatkit/__init__.py", line 16, in <module> from pywhatkit.whats import ( File "/app/.heroku/python/lib/python3.10/site-packages/pywhatkit/whats.py", line 7, in <module> import pyautogui as pg File "/app/.heroku/python/lib/python3.10/site-packages/pyautogui/__init__.py", line 249, in <module> import mouseinfo File "/app/.heroku/python/lib/python3.10/site-packages/mouseinfo/__init__.py", line 223, in <module> _display = Display(os.environ['DISPLAY']) File "/app/.heroku/python/lib/python3.10/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DISPLAY' Code (Files) requirement.txt pywhatkit==5.4 test.py import pywhatkit try: pywhatkit.sendwhatmsg_instantly("+1*********", "Hello from NewYork") print("Successfully Sent!") except: print("An Unexpected Error!") -
The FastCGI process exited unexpectedly while deploying Django project on iis windows server
FAST CGI IS NOT WORKING PROPERLY IN DJANGO DEPLOYMENT ON IIS WINDOW SERVER HTTP Error 500.0 - Internal Server Error C:\Users\satish.pal\AppData\Local\Programs\Python\Python310\python.exe - The FastCGI process exited unexpectedly Most likely causes: •IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. •IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. •IIS was not able to process configuration for the Web site or application. •The authenticated user does not have permission to use this DLL. •The request is mapped to a managed handler but the .NET Extensibility Feature is not installed. Things you can try: •Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account. •Check the event logs to see if any additional information was logged. •Verify the permissions for the DLL. •Install the .NET Extensibility feature if the request is mapped to a managed handler. •Create a tracing rule to track failed requests for … -
Get value of primary key before save
Given the following model I am attempting to use the models ID field (a UUID) in the upload_to path but its defined as None, presumably as it hasn't been generated at that point. If I use a UUID field that isn't defined as the primary key it works OK. How do I get the value of the id field at the point picture_path is ran? # models.py class Foo(models.Model) def picture_path(instance, filename): return 'pictures/{0}/{1}'.format(instance.id, filename) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) picture = models.ImageField(upload_to=picture_path, null=True, blank=True) (I know that django will automagically append random chars to avoid duplicate file names, this is a deliberately simplified example, in the real app need to keep each models files in a seperate folder) -
Django profile picture tries to duplicate when updating profile
When a user updates their profile, if they don't change their profile picture, it tries to resave in a recursive manner. user/ profile_pics/ image1.jpg user/ profile_pics/ image2.jgp models.py def create_path(instance, filename): return os.path.join( str(instance.user.id), 'profile/logo', filename ) class Member(models.Model): profile_pic = models.ImageField(upload_to=create_path, null=True) profile_pic_thumbnail = models.ImageField(upload_to=create_path, null=True) def __str__(self): return str(self.user) def save(self, *args, **kwargs): if not self.make_thumbnail(): # set to a default thumbnail raise Exception('Could not create thumbnail - is the file type valid?') super(Member, self).save(*args, **kwargs) def make_thumbnail(self): image = Image.open(self.profile_pic) image.thumbnail((500, 500), Image.ANTIALIAS) thumb_name, thumb_extension = os.path.splitext(self.profile_pic.name) thumb_extension = thumb_extension.lower() thumb_filename = thumb_name + '_thumb' + thumb_extension if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' elif thumb_extension == '.gif': FTYPE = 'GIF' elif thumb_extension == '.png': FTYPE = 'PNG' else: return False # Unrecognized file type # Save thumbnail to in-memory file as StringIO temp_thumb = BytesIO() image.save(temp_thumb, FTYPE) temp_thumb.seek(0) # set save=False, otherwise it will run in an infinite loop self.profile_pic_thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=False) temp_thumb.close() return True forms.py class CreateMemberProfileForm(ModelForm): class Meta: model = Member fields = ('profile_pic') widgets = { 'profile_pic': ImageUploaderWidget(), } views.py class UpdateProfileView(UpdateView): model = Member form_class = UpdateMemberProfileForm template_name = 'update_profile.html' success_url = reverse_lazy('dashboard') updateprofile.html <form class="dropzone" enctype="multipart/form-data" method="post"> {% csrf_token %} … -
Adding several schema encoding URLs in Django REST framework swagger-ui.html template
I have the swagger-ui.html file in a Django (v4.1.2) app as follow (taken from the Django REST framework doc): <!DOCTYPE html> <html> <head> <title>Swagger</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css"> </head> <body> <div id="swagger-ui"></div> <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url 'yaml-schema' %}", url: "{% url 'json-schema' %}",<!-- This is what I naturally want to add --> dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", requestInterceptor: (request) => { request.headers['X-CSRFToken'] = "{{ csrf_token }}" return request; } }) </script> </body> </html> I have defined two paths defining the schema in the urlpatterns list in my main url.py, one for a YAML encoded version and the other for a JSON encoded version of the schema: (...) from drf_spectacular.views import ( SpectacularYAMLAPIView, SpectacularJSONAPIView, SpectacularSwaggerView, ) (...) # OAPI 3 urlpatterns = [ ... path( rf"{API_BASE}schema/yaml/", SpectacularYAMLAPIView.as_view(), name="yaml-schema", ), path( rf"{API_BASE}schema/json/", SpectacularJSONAPIView.as_view(), name="json-schema", ), path( rf"{API_BASE}docs/", SpectacularSwaggerView.as_view( template_name="swagger-ui.html", url_name="yaml-schema" ), name="swagger-ui", ), ] drf_spectacular.views doc: https://drf-spectacular.readthedocs.io/en/latest/drf_spectacular.html#module-drf_spectacular.views I would like to add two links on top of the swagger API doc page, one per schema encoding: But when I add the line url: "{% url 'json-schema' %}", in the swagger-ui.html file, there is only the last … -
How to save different javascript codes in a blog application?
I have a blog using vue.js as frontend framework, Django as backend framework and postgressql as database. I want to have games among my blog posts text so each post has different js code (vue component). What is your solution to structure my database? -
How to mix python and javascript in the server side
I'm creating an application that needs to pull certain data to show it to the user. This data is pulled via a JavaScript function that ideally I'd like to have on the server side, not on the source code of the page. The flow should be: User chooses 1 parameter in the website and clicks ok Send a POST request to Django with that parameter Django's view uses that parameter to pull another 4 parameters from the Django database Somehow use this 4 parameters in the JavaScript function to get some timeseries data Pass this data from JavaScript to the view, and from the view update the browser's template without the user refreshing the page How can I pass the 4 parameters from Python to the JS function, and then the result of the JS function back to Python? The reason I need to use JavaScript and not Python for retrieving that data is because JS has a specific library that would make my life so much easier. -
Django Send Email form, how to add value from another model established via foreign key
I am trying to create a Ticket form which sends Email. Everything is working fine, but there is a foreign key field, I am pulling data from it in this ticket, I am not able to include that in the email body. views.py def createTicket(request): form = TicketForm(request.POST) if request.method == 'POST': if form.is_valid(): subject = "Ticket Email" body = { 'customer': form.cleaned_data.get('customer'), 'subject': form.cleaned_data.get('subject'), 'priority': form.cleaned_data.get('priority'), 'details': form.cleaned_data.get('details'), } message = "\n".join(body.values()) form.save() try: send_mail(subject, message, 'from_email', [form.cleaned_data.get('technician_email')]) except BadHeaderError: return HttpResponse('Invalid Header') return redirect('/') context = {'form': form} return render(request, 'ticket_form.html', context) models.py class Ticket(models.Model): PRIORITY = ( ('normal', 'Normal'), ('urgent', 'Urgent') ) STATUS = ( ('pending', 'Pending'), ('hold', 'Hold'), ('closed', 'Closed') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) technician = models.CharField(max_length=255, null=True) technician_email = models.CharField(max_length=255, null=True) subject = models.CharField(max_length=255, blank=True, null=True) priority = models.CharField(max_length=255, blank=True, null=True, choices=PRIORITY) details = models.CharField(max_length=2000, blank=True, null=True) class Customer(models.Model): company_name = models.CharField(max_length=255, null=True) Customer_type = models.ManyToManyField(Customertype, blank=True) first_name = models.CharField(max_length=255, null=True) last_name = models.CharField(blank=True, max_length=255, null=True) Now the foreignkey fiend "customer", I am unable to obtain data, what is the correct method to pull value from this field. I am getting below error: Exception Type: TypeError Exception Value: sequence item 0: expected str … -
django row sql query in multi model
I want to use blow query in my django but I select multiple model in my query and I don't know what should I set for ? in my code ?.objects.row("SELECT * from Backup,auth_user, Account_asset where Backup.AssetName=Account_asset.Asset_name and auth_user.id = Account_asset.user_id and auth_user.username = admin") I need type that can query on whole models -
UnboundLocalError when simply adding a logic check
Good day fellas, sometimes computer logic really is just unbearable... Can someone do me the courtesy of explaining why this code works: def forecast_view(request): if request.method == 'POST': city = request.POST['city'] city_capitalized = city.capitalize() safe_string_city = urllib.parse.quote_plus(city) #language = request.POST['language'] #units = request.POST['units'] #url = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&lang='+language+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b&units='+units).read() res = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+safe_string_city+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b').read() json_data = json.loads(res) data = { 'country_code': json_data['sys']['country'], 'coordinates': str(json_data['coord']['lon']) + ' ' + str(json_data['coord']['lat']), 'weather': json_data['weather'][0]['main'], 'description': json_data['weather'][0]['main'], 'icon': 'http://openweathermap.org/img/wn/' + json_data['weather'][0]['icon'] + '@2x.png', 'wind': json_data['wind']['speed'], 'temperature': json_data['main']['temp'], 'pressure': json_data['main']['pressure'], 'humidity': json_data['main']['humidity'], 'city': city_capitalized, } else: city = '' data = {} return render(request, 'weather/forecast.html', data) But then as I add a simple logic check I get the UnboundLocalError if request.method == 'POST': if request.POST.get("filters"): pass elif request.POST.get("get_info"): city = request.POST['city'] city_capitalized = city.capitalize() safe_string_city = urllib.parse.quote_plus(city) #language = request.POST['language'] #units = request.POST['units'] #url = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&lang='+language+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b&units='+units).read() res = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+safe_string_city+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b').read() json_data = json.loads(res) data = { 'country_code': json_data['sys']['country'], 'coordinates': str(json_data['coord']['lon']) + ' ' + str(json_data['coord']['lat']), 'weather': json_data['weather'][0]['main'], 'description': json_data['weather'][0]['main'], 'icon': 'http://openweathermap.org/img/wn/' + json_data['weather'][0]['icon'] + '@2x.png', 'wind': json_data['wind']['speed'], 'temperature': json_data['main']['temp'], 'pressure': json_data['main']['pressure'], 'humidity': json_data['main']['humidity'], 'city': city_capitalized, } else: city = '' return render(request, 'weather/forecast.html', data) How does it make any sense? I am not assigning or ressigning anything! Thanks for the help … -
Django Heroku OperationalError no such table: posts_post
I'm reading Django 4.0 for Beginners book by William S. Vincent https://djangoforbeginners.com/. Chapter 4 builds a simple Message Board App and deploys to Heroku. Running the app locally works with no problems. A simple webpage is returned. And all the tests are completed with no problems also. Pushing the code to Heroku is straightforward, and no errors are encountered. But once the code is live at Heroku, it doesn't like what ran on my localserver with no problems. Heroku error message: no such table: posts_post <!-- templates/home.html --> <h1>Message board homepage</h1> <ul> {% for post in post_list %} <li>{{ post.text }}</li> {% endfor %} </ul> I'm not quite sure what this error is trying to tell me. The code looks fine, so the issue must be elsewhere. And I don't understand how Django can run locally with no issues, but then Heroku doesn't like it. Initially I thought that the Python Black "Format on Save" was messing with the HTML indentation (4 characters vs 2 characters). I disabled Black's Format on Save and set indentation to 2 characters in the templates/home.html file. This also worked locally, but ended in the same error at Heroku. I followed all the steps in … -
Python django cant activate virtual enviroment
I can't activate virtual enviroment and get 'cannot be loaded because running scripts is disabled on this system' I tried to write 'activate' and './activate' but both dont work -
How to search by parts of an entered word in Django and PostgreSQL
I'm writing a site on Django and I'm making a book search system based on their title, and I have a problem, I want to make it so that even if the user enters only part of the title, all books with this part in the title are displayed For example: User entered "Pyth" and recieves all books where title contain "Python" "Pyth" -> "A Byte of Python" This is my search_page_view: def search_page_view(request): query = request.GET.get("q") search_vector = SearchVector('title') search_query = SearchQuery(query) search_rank = SearchRank(search_vector, search_query) search_set = Book.objects.annotate(search=search_vector, rank=search_rank).\ filter(search=query).order_by("-rank") context = {'search_set': search_set} return render(request, 'search/search_page.html', context=context) But it works only if you enter a full word, for example Python Maybe someone knows how I can add such functionality? -
JavaScript request to get Form model from Django
as my first project by myself, for a web dev course I am building a "clone" of a famous password manager. It is a Django single page web app, using vanilla JavaScript for async request and content management. Preface: I created a model for the Login instance table class Login(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=80, blank=False, null=False) username = models.CharField(max_length=80, null=True, blank=True) password = models.CharField(max_length=80, null=True, blank=True) notes = ... folder = .... And from Django I was able to pass it through to the page as an empty ModelForm with correct formatting class LoginForm(ModelForm): class Meta: model= Login fields = ('title', 'username', 'password', 'note', 'folder', 'protected', 'favorite',) widgets = { 'password': PasswordInput, 'note': Textarea(attrs={'rows':6, 'placeholder':"Add notes here..."}), } it submits and saves it correctly. Problem I am now trying to add the possibility to edit the saved form without reloading, so I would need to create a textarea for each field, precompiled with the current value to be submitted. I started trying to build the same thing from JavaScript when the button is clicked, building a template for each of the 7 field it has, and entering the current value as the textarea value, e.g. const titlearea = … -
Display selection field in Django template
I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this: from django.db import models class Consumer(models.Model): SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) size = models.CharField(max_length=2, choices=SIZES) And I did in my view and template like this (Learned from one tutorial) ***view with combined queries*** def staff_filter(request): qs = Consumer.objects.all() size= request.GET.get('size') # I have some other queries in between .... if is_valid_queryparam(size) and size!='Choose...': qs = qs.filter(size=consumer.get_size.display()) return qs def filter(request): qs=staff_filter(request) context={ 'queryset':qs, 'consumer':consumer.objects.all() } return render(request, 'filter.html',context) **template*** <div class="form-group col-md-4"> <label for="size">size</label> <select id="size" class="form-control" name="size"> <option selected\>Choose...</option> {% for size in consumer.get_size.display %} <option value="{{ size }}">{{size}}</option> {% endfor %} </select> </div> How should I correct it? Thanks! Display selection field in Django template -
"Can't start a new thread" error while running django server in gunicorn
I am running a django server in gunicorn. I noticed after creating a certain number of threads it cannot start new thread. This is my gunicorn service file: So, I tried to see the status of the gunicorn service file: sudo systemctl status medai-app.service output : It's showing the limit of tasks is 1143. I want to know how to increase this number. How is it determined as I did not find any configuration setting to tune this. My user's maxproc limit is 5000. The number of threads that's been created doesn't decrease, why? Shouldn't they be killed after finishing a task? -
use regex validator in django modelforms
i want to use regex validator for name field in model form i want users just can type english in this field and if they want type with another language get a error thank you help me how do that thanks -
Django's dumpdata only dumping auth permission and contenttypes data
I use local Postgres on the dev environment and deployed my app to Heroku with Postgres as well. I migrated my database, and now I want to load my data. The app works fine on Heroku, but without data. I have different settings files for dev and prod - with local Postgres and Postgres on Heroku correspondingly. I have my data on dev Postgres, and when I launch the app on dev - I see the data. To dump data I set my dev settings where dev database settings are: ./manage.py dumpdata --indent=4 --settings=app.settings.dev > data3.json I see that only data from auth.permission and contenttypes.contenttype are there: [{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, "fields": {"name": "Can delete log entry", "content_type": 1, "codename": "delete_logentry"}}, {"model": "auth.permission", "pk": 4, "fields": {"name": "Can view log entry", "content_type": 1, "codename": "view_logentry"}}, {"model": "auth.permission", "pk": 5, "fields": {"name": "Can add permission", "content_type": 2, "codename": "add_permission"}}, {"model": "auth.permission", "pk": 6, "fields": {"name": "Can change permission", "content_type": 2, "codename": "change_permission"}}, {"model": "auth.permission", "pk": 7, "fields": {"name": "Can delete permission", "content_type": 2, … -
Rewrite top menu by DeleteView
I have a section 'About' which is rarely updated. I want each time this section is updated, the popup menu is re-generated. Thanks to Lucas Grugru see my previous question, I've partially solved the problem, but not fully. I rewrite the menu in my views which change the structure of the section (specifically, PageUpdateView and PageDeleteView). For this, I rewrote their standard get_success_url method, assuming that, it is the one which implements at the very last moment of page update / deletion (or not?). In this method, I select all objects (pages with their prefetched subpages), then generate an HTML code with the 'render_to_string' function, and then write it to a file. With PageUpdateView this works fine, but when I use PageDeleteView, the deleted page is not removed from the top menu. It happens because when I select objects with a queryset (see the code below), the deleted object is still there. about_list = Page.objects.filter(parent=None).order_by("order")./ annotate(num_subs=Count('subs')).prefetch_related( Prefetch( 'subpages', Page.objects.annotate(num_subs=Count('subs')), 'subpage') ) Of course, I could exclude this object by its slug name (exclude(slug=self.kwargs['slug'])), but I suspect that there should be a more proper way to update a menu once the structure of the site changes. -
"detail": "JSON parse error - Expecting ',' delimiter:
I dont know what is wrong with json, trying to pass a post request but its giving me this error ' "detail": "JSON parse error - Expecting ',' delimiter: line 3 column 34 (char 36)" ' This is what i passed as my post request { "song" :{"artiste": ["first_name": "Kizz", "last_name": "Daniel", "age": 30], "title": "Buga", "likes": 3}, "content": "chilled music" } My model: class Song(models.Model): artiste = models.ForeignKey(Artiste, on_delete=models.CASCADE, null=True) title =models.CharField(max_length=100) date_released = models.DateTimeField(auto_now_add=True, null=True) likes = models.IntegerField() # artist_id = models.CharField(max_length=50, null=True) def __str__(self): return self.title class Lyrics(models.Model): song = models.ForeignKey(Song, on_delete=models.CASCADE) content = models.TextField() rest_framework serializer: class LyricsSerializers(serializers.ModelSerializer): song = SongSerializers(many=True) class Meta: model = Lyrics fields = ["song", "content"] rest_framwork Api views: class lyricsApiView(APIView): def get(self, request): lyrics = Lyrics.objects.all() serializer = SongSerializers(lyrics, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = LyricsSerializers(data=request.data) if serializer.is_valid(): artiste = serializer.validated_data.pop('artist') artiste_create = Artiste.objects.create(**artiste) song = serializer.validated_data.pop('song') song_create = Song.objects.create(**serializer.validated_data, artiste=artiste_create) lyrics_create = Lyrics.objects.create(**serializer.validated_data, song=song_create) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django CSRF token in template outdated after login
Django allows adding CSRF token to webpage by rendering it to the template with {% csrf_token %} Now here is the situation. I have two tabs opened with public pages of my website which don't require login, and is viewing them as anonymous user. Both tabs of course share the same CSRF token. Now I perform user login using tab 1. This triggers rotation of the CSRF token and updates the cookie with the new token. This means the CSRF token rendered to the webpage of tab 2 is now outdated. So any further POST or AJAX requests sent from tab 2 will return 403, making my website on tab 2 behave incorrectly until I reload the page. Does this mean, that to avoid this problem I should never rely on {% csrf_token %} and always retrieve csrf token from the cookie before posting any ajax requests? This sounds a little strange so maybe I'm missing something. I was expexting {% csrf_token %} to be a reliable source of the csrf token, but seems like it is not.