Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue Django Migrations Tree - Deployment Pythonanywhere
guys I have been having this issue when managing Django migrations on deployment, and I would like yo know what approach should I take: I am developing an application using Django and I am using Pythonanywhere to deploy the webapp, I am using sqlite as the database. I understand the Django Migrations work like a tree or a sequence (001, 002), but every time I make a change in a field locally it works fine because the tree have been save and the sequence have not changed, but when deploying the changes through github (having deployed the webapp and calling the migrations and migrate command, which creates another migrations files and sequence), usually I got an error indicating that the migration tree is broken; so I have to go to the app's migration folder and delete them and call again the migrations and migrate command. This is causing me a lot of problems due that I do not want to mess with schema of the database and loss the information. So, It is just me or anyone else is having this issue the migrations tree, not only on pythonanywhere but on others servers. Thank you guys! -
How do I use the Django rest framework to prolong a JWT session token?
I'm using Django 3.2 with the django.auth.contrib app and djangorestframework-jwt==1.11.0. How do I prolong/reissue a new session token upon receiving a request for an authenticated resource and validating the user can access that resource? I use the following serializer and view to login the user and issue the initial token class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): username = data.get("username", None) password = data.get("password", None) user = authenticate(username=username, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except User.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'username':user.username, 'token': jwt_token } class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'User logged in successfully', 'token' : serializer.data['token'], } status_code = status.HTTP_200_OK return Response(response, status=status_code) I have this in my settings file to keep the session to 1 hour initially JWT_AUTH = { # how long the original token is valid for 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), } The client submits the session token … -
How settings Redis not working in channels Layer?
I am trying to use django_redis's RedisChannelLayer as django channels's channel layer backend. Which results in the websocket opening and closing instantly. But it work fine with In memory channel layer. CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } -
Tempus Dominus DatePicker in Django showing one day less when I get the data for edit
I have a Table with all my data, and when I try to edit one row I catch all data to a form, but the datepicker is showing ALWAYS one day less than the one entered. How can I solve this?. I read something about the DateTime from JS but I didn't find anything to solve my problem. This is how the data is displayed in my table: And in my form this is how it is received when I clicked the edit button (SubTotal, Calculated IVA and Total are in 0, ignore it, It is not relevant :D ): Form.py from datetime import datetime from django.db.models.base import Model from django.forms.fields import DecimalField from django.forms import * from core.erp.models import Sale from tempus_dominus.widgets import DatePicker class SaleForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Sale fields = '__all__' widgets = { 'cli': Select( attrs={ 'class': 'form-control select2' } ), 'date_joined' : DatePicker( options={ 'maxDate': datetime.now().strftime('%Y-%m-%d'), 'useCurrent': True, 'collapse': False }, attrs={ 'append': 'fas fa-calendar', 'icon_toggle': True, } ), 'subtotal': NumberInput( attrs={ 'class':'form-control', 'disabled' : True, 'autocomplete': 'off' } ), 'iva': NumberInput( attrs={ 'class':'form-control' } ), 'total': NumberInput( attrs={ 'class':'form-control', 'disabled': True, 'autocomplete': 'off' } ) } exclude … -
does it make sense to use django urls for view test?
im new to django and im working on a webesite and i want to right unit tests for it and im kind of confused how to do it. does it make any sense to get urls from django its self and test their views? from django.test import TestCase from django.urls import get_resolver from kernel.settings.base import TEMPLATES_DIR class ViewNameViewTest(TestCase): Site_urls= list(set(v[1] for k,v in get_resolver().reverse_dict.items())) Site_urls= [i.replace('\\','') for i in Site_urls] Site_urls= [i.replace('/','') for i in Site_urls] Site_urls= [i.replace('$','') for i in Site_urls] def test_url_exists(self): for i in self.Site_urls: with self.subTest(line= i): response = self.client.get(f'/{i}/') self.assertEqual(response.status_code, 200) also other tests like if view uses correct template which acquires url names... my url examples: urlpatterns = [ path('about/', aboutView.as_view(),name='About'), ] so is this the correct way of doing it or should i use static files? -
How do I get website to display local time?
If I run this in VS Code, it gives me the correct local time: from time import strftime time = strftime("%H:%M %p") print(time) But if I use the same code in a Django project, my website displays a time which is 8 hours behind local time. from time import strftime,localtime def time_display(request): context = { "date":strftime("%b %d, %Y",localtime()), #DOESN'T DISPLAY LOCAL TIME "time1": strftime("%H:%M %p",localtime()), #DOESN'T DISPLAY LOCAL TIME "time3": strftime("%H:%M %p"), #DOESN'T DISPLAY LOCAL TIME } return render(request,'time_display.html',context) How do I fix it to display correct local time where the webpage is being viewed? -
Django: How to locate caller of the "/device/event" route?
I am using Datadog to understand the frequency of the routes in a Django project. Datadog reports that the most frequent route is /device/event, and I have no idea what this route is or what is calling it. How would a person figure out its origin or where it's defined? -
count each occurrences when date falls within a range
I am trying to count each time the value of month in created_on falls within different months, using this django orm below: result_qs = Model.objects.all().annotate( spring=Count(Case(When(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1))), summer=Count(Case(When(ExtractMonth("created_on") in [6, 7], then=1))), fall=Count(Case(When(ExtractMonth("created_on") in [8, 9, 10, 11, 12], then=1))), year=ExtractYear("created_on") ) I'm getting the error When() supports a Q object, a boolean expression, or lookups as a condition. When I apply Q notations to one of the cases, such as: spring=Count(Case(When(Q(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1)))), cannot unpack non-iterable bool object Any suggestions? -
Why we need to setup AWS and POSTgres db when we deploy our app using Heroku?
I'm building a web api and the training video that I follow at first deploy everything locally then after making sure everything works he is transfering all static files to AWS and for DB he switches from SQLdb3 to POSgres. django portfolio I still don't understand this part why we need to put our static files to AWS and create POSTgresql database even there is an SQLdb3 default database from django. I'm thinking that if I'm the only admin and just connecting my GitHub from Heroku should be enough and anytime I change something in the api just need to push those changes to github master and that should be it. Why after deploying everything locally we are moving to AWS and Postgres setup and do the things from the beginning. Still not get it! Can anybody explain this ? Thanks -
Forms in Django. Drop-down list
In a django (python) project, I have a foreign key model that reflects a form to fill out. Is it possible to make it so that if the user does not find his option in the drop-down list, he has the opportunity to fill in this field, but with his own option (respectively, with saving to the database). And in the future this option will be shown in the drop-down list. Like in the picture. https://i.stack.imgur.com/APDr5.png So that the user can create a new tag if it is not in the drop-down list. What should be applied to implement this idea? What can be found in the documentation? -
Backend and Frontend in Docker work locally but not remotely
Problem I have three Docker containers: a backend, a frontend and an nginx container that handle requests. When I run it on my computer (windows laptop with docker engine), everything works perfectly. I can see the call are made in the logs of the containers: reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET /static/js/bundle.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET /static/js/vendors~main.chunk.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET /static/js/main.chunk.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:01 +0000] "GET /favicon.ico HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:01 +0000] "GET /manifest.json HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - … -
Why is the View returning None when I navigate to the payment page in Django?
The rest of the application is working well but a problem arises when I navigate to the payment page, the app returns None. I can't figure out where the error is. This is the payment_page.html, the error arises when I try to access this page {% extends 'customer/base.html' %} {% load bootstrap4 %} {% block head %} <script src="https://js.stripe.com/v3/"></script> {% endblock %} {% block main %} {% if not request.user.customer.stripe_payment_method_id %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> Let's add your credit / debit card to <strong>Create a Job</strong> <button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <b class="text-secondary">Your Credit / Debit Card</b> <style> .StripeElement { height: 40px; padding: 10px 12px; width: 100%; color: #32325d; background-color: white; /*border: 1px solid transparent; */ border: 1px solid #cfd7da; border-radius: 4px; } .StripeElement--focus { border-color: #80bdff; box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, .25); } .StripeElement--invalid { border-color: #fa755a; } .StripeElement--webkit-autofill { background-color: #fefde5 !important; } </style> <div class="card bg-white mt-2 mb-5"> <div class="card-body"> {% if request.user.customer.stripe_payment_method_id %} <div id="change-card" class="input-group"> <input type="text" class="form-control" disabled value="**** **** **** {{request.user.customer.stripe_card_last4}}"> <div class="input-group-append"> <form method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger">Remove</button> </form> </div> </div> {% else %} <form id="setup-form" data-secret="{{ … -
Updating many to many model in Django Rest Framework
I have the following models: class Settings(models.Model): ... category = models.ManyToManyField( Category) hsk = models.ManyToManyField( HSKLevels) class Meta: db_table = 'settings' I can quite easily update my main table via REST. The problem is that I cannot figure out how to update the hsk table with REST. class HSKLevels(models.Model): level = models.PositiveIntegerField(primary_key=True) label = models.CharField(max_length=50) value = models.CharField(max_length=50) class Meta: db_table = 'hsk_levels' This is my serializer: class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ["user","traditional","category", "hsk","audio_download","show_read","show_pinyin","char_size","pinyin_size","start_date","end_date","speed","volume", "char_colors", "pinyin_colors", "global_dash","first_tone","second_tone","third_tone","fourth_tone","fifth_tone","word_selection","limit_selection","hsk_selected","sentence_selection","mem_limit_selection","show_outline","show_character","show_hint_after_miss"] depth = 1 With this setup, I am able to add many to many connections, but I cannot delete any many to many connections. What I'd prefer is if a given connection isn't present - is to delete it. So I'd have a JSON object like this (or alternatively, an array, I am not picky): hsk: { hsk1: true, hsk2: true, hsk3: true, hsk4: true, hsk5: true, hsk6: true, hsk7: true, hsk8: true, hsk9: true, hsk9plus: true, }, And if one of these values is false or not present, it gets deleted. -
Django & Leaflet & modal fade
Can someone send me an example of programs (views.py, urls.py, template ...) which uses class = "modal fade" to introduce latitude and longitude of a PointField, then search if this point exists with the filter command and display it on a map. I inform you that I use Django and Leaflet. Thank you so much. -
display multiple selected checkboxes ticked in update form in django
In my create form i have saved certain values of season_interest as summer, winter in my database now these values should be shown ticked in update form let us consider my forms.py as SEASON_INTEREST_CHOICES = ( ('Spring','Spring'), ('Summer','Summer'), ('Autumn','Autumn'), ('Winter','Winter'), ('Year round','Year round'), ) class HorticlutureUpdateForm(BetterModelForm): season_interest = forms.MultipleChoiceField( required=False,label=('Season of Interest'), widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}), choices=SEASON_INTEREST_CHOICES, ) here is my models.py class Items(models.Model): SEASON_INTEREST_CHOICES = ( ('Spring','Spring'), ('Summer','Summer'), ('Autumn','Autumn'), ('Winter','Winter'), ('Year round','Year round'), ) season_interest = models.CharField(max_length=200,blank=True, null=True,verbose_name='Season of Interest') When i am using widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}) in updateform it is showing all the choices as ticked rather than the values that are saved in database(i.e clay, chalk only should be ticked in updateform display) Currently it is showing in this way in update form How i need the image to be in update view of item in chrome -
How to pass variable to Django Paginator()'s per_page parameter so all album tracks can be displayed on one page?
I am building a web app music player using Django with Postgres as the database. My setup right now displays the first song for each album. As one clicks through the play button, the view changes to the first track of every album. I would like to display all the tracks for any given album on a single page. A single page would display these objects: From Album: album_title, artist, artwork_file and from Track: track_title and audio_file for each track in the album To do this I need to supply an integer to the self.per_page parameter in Django's Paginator class. Currently it is set to 1. The number of tracks changes depending on album, so I want to pass this as an integer as a variable (Album.number_tracks). The trouble is I can't create a queryset to iterate through and pass each iteration into self.per_page because the Paginator function takes all of the objects at once rather than object by object. So I can't use any conditional loops like: queryset = Album.objects.all() number_of_tracks = [a.number_tracks for a in queryset] How can I display all tracks from any given album on a single page, no matter the number of songs? Here are … -
js file doesn't work in the code inside the .html() function
When i press a button (cart quantity button) the js file call an ajax function that upload all the cart contents and replaces it with the items inside "res.data". Ajax function: $.ajax({ url:'/update_quantity_instant/', data:_newdata, dataType:'json', success:function(res){ console.log(res); $('#cart-total').text(res.cartItems); $('#boxcart').html(res.data); } }) the js function starts like this: jQuery(document).ready(function($){ $(".update-cart").on('click', function(){ This is the return function inside the views.py file: t=render_to_string('ajax/quantity-cart.html',{'data1':items, 'data2': order}) return JsonResponse({'data':t, 'cartItems': cartItems}) the js file responds only the first time I press the button, I tried to add the js file tag also in the new html file where the ajax function loads the items, the code works but I get this error in the console: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. Probably because the file is loaded several times. -
One of my Bollean field is displayed as select (Unknow/Yes/no) instead of checkbox
I have a error I could not fix. I have many boolean fields in a form and all arer displayed as checkbox except one that is displayed as select list models.py class Psychosocial2(Invalidite): """ A class to create a psychosocial 2 instance. """ ide = models.AutoField(primary_key=True) ... ps2_res_pdr = models.BooleanField('Pas de réponse', null=True, blank=True) <- correctly displayed ps2_res_nap = models.BooleanField("NA", null=True, blank=True) <- displayed as a select forms.py ... self.fields['ps2_res_nap'] = forms.BooleanField(label = 'NA',required=False) ... template <tr> <td></td> <td colspan="2"> {{ form.ps2_res|as_crispy_field }} {{ form.ps2_res_pdr|as_crispy_field }} {{ form.ps2_res_nap|as_crispy_field }} <-- </td> </tr> -
local variable 'utilisateurs_serializer' referenced before assignment
` @api_view(['GET', 'POST', 'DELETE']) def utilisateur_list(request): if request.method == 'GET': utilisateurs = Utilisateur.objects.all() firstname = request.GET.get('firstname', None) if firstname is not None: utilisateurs = utilisateurs.filter(firstname__icontains=firstname) utilisateurs_serializer = UtilisateurSerializer(utilisateurs, many=True) return JsonResponse(utilisateurs_serializer.data, safe=False) elif request.method == 'POST': utilisateur_data = JSONParser().parse(request) utilisateur_serializer = UtilisateurSerializer(data=utilisateur_data) if utilisateur_serializer.is_valid(): utilisateur_serializer.save() return JsonResponse(utilisateur_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(utilisateur_serializer.errors, status=status.HTTP_400_BAD_REQUEST) ` Error -
Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432?
Hello I occured an error like in title during composing Django web app. I get this error Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? I have no idea how can i solve it, I have already, restarted Postgresql database and docker but I neither of these work. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fitshopuser', 'PASSWORD': 'fitpass', 'HOST': 'localhost', 'PORT': '5432', } } docker-compose.yml version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=fitshopuser - POSTGRES_PASSWORD=postgres ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
Need to add User fields in Order [Django]
I have model for Order and OrderItem class Order(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField() phone = models.CharField(max_length=15) adress = models.CharField(max_length=100) comment = models.TextField() created = models.DateField(default=datetime.date.today()) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity Have Forms for Anonymous User (all fields) and User - only adress and comment fields. class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ('first_name’, 'last_name', 'email', 'phone', 'adress', 'comment') class OrderUserCreateForm(forms.ModelForm): class Meta: model = Order fields = ('adress', 'comment') And I have views for Anonymous User: def my_order(request): context = {} cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() context['order'] = order else: form = OrderCreateForm() context['form']=form return render(request, 'my-app/order.html', context) My problem: How to make a view for an active user so that the fields 'first_name’, 'last_name', 'email', 'phone' are taken from the user??? And for user form class OrderUserCreateForm(forms.ModelForm) or maybe class OrderUserCreateForm(forms.Form)? Or is it possible … -
Pytest patch field's default attribute for inherited django model
I have the following model in common/models.py: from django.db import models from uuid import uuid4 class BaseModel(models.Model): guid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) class Meta: abstract = True In app/models.py I have the following: from django.db import models from common.models import BaseModel class Entity(BaseModel): name = models.CharField() In tests I tried to patch uuid4 in the following ways: def test_model_create(mocker): # Given mock_guid = mocker.patch("uuid.uuid4", return_value="some-guid") # When entity = Entity.objects.create(name="test_name") # Then mock_guid.assert_called_once() assert "some-guid" == entity.guid mock_guid.assert_called_once() returns not called. What can be the issue here? -
Django to_python method of custom models.DateTimeField not receiving the correct value
I have a ModelForm based on a model which includes a customized DateTimeField. The only customization is to override the to_python method so I can convert the 'AM/PM' formatted string into a 24 hr time format that Django will validate. I specified a DateTimeInput widget on the form so I could format into AM/PM notation (format=('%m/%d/%Y %H:%M %p')), which I initialize to the current datetime. The form displays correctly, eg '10/10/2021 04:33 PM' but when the to_python function of the custom field is called, the value passed to it does not include the time; only the date. Also, I don't understand why the to_python method of that field is called (twice) when a listener on another field creates an AJAX call rather than when the Submit button is clicked. I looked at the request data sent when the Submit is clicked, and it does have the full '10/10/2021 04:33 PM'. (I realize the actual conversion in to_python to handle the AM/PM is not done at all; I haven't gotten that far yet). I tried using several popular datetimepickers instead, but none of them solved this problem. models.py: class ampmDateTimeField (models.DateTimeField): def to_python(self, value): print ('initial_date_time = ',value) # Here is … -
How to fix the problem createview is missing a queryset
I'm getting this error CreateBlog is missing a QuerySet. Define CreateBlog.model, CreateBlog.queryset, or override CreateBlog.get_queryset(). It seems like Django thinks that I'm using CreateView without specifying a model. However, my view does define a model. can anybody tell where i am wrong here is view.py file from django.shortcuts import render from django.http import HttpResponseRedirect from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView) from .models import Blog,Comment,Likes from django.urls import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin import uuid # Create your views here. def blog_list(request): return render(request, 'App_Blog/blog_list.html', context = {}) class CreateBlog(LoginRequiredMixin, CreateView): models = Blog template_name = 'App_Blog/createblog.html' fields = ('blog_title', 'blog_content', 'blog_image') def form_valid(self,form): blog_obj = form.save(commit = False) blog_obj.author = self.request.user title = blog_obj.blog_title blog_obj.slug = title.replace(" ","-") + "-" + str(uuid.uuid4()) blog_obj.save() return HttpResponseRedirect(reverse('index')) here is urls.py file from django.urls import path from . import views app_name = 'App_Blog' urlpatterns = [ path('', views.blog_list, name = "blog_list"), path('write/', views.CreateBlog.as_view(), name = "blog/create_blog/"), here models.py file from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name= "Put a title") slug = models.SlugField(max_length = 264, unique=True) blog_content = … -
Django rest framework: Cookies lost after page refresh
i am facing issue with cookies. My login cookies lost when my page redirects to profile page after loggin in. I can see my cookies being set after login success but then they lost when page redirects. profile page fetches the profile first by hitting a get request. Please help me. Its only happening in production not in development server. My backend and frontend has different domains. My login view - class LoginView(APIView): def post(self,request,format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'], ) response.set_cookie( key = "tokenvalidate", value = data["access"][0:len(data['access'])//2], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = False, samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'], #setting this cookie for logout functionality. frontend can remove this non httponly cookie using js in logout function. #if this cookie is not sent in request then the authorization will be failed. ) csrf.get_token(request) response.data = {"Success" : "Login successfully","data":data} return response else: return Response({"No active" : "This account is not active!!"},status=status.HTTP_404_NOT_FOUND) else: return Response({"Invalid" : "Invalid username …