Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Function for returns X times same result
Im new at python and django, i need this function for work if someboyd can help me i'll appreciate it so much. This function has to return in a json file all the different results with the function 'for' but instead it returns 1 result X times the same one X times. @login_required def oferta_reporte_json(request): ofertas_efectiva = OfertaEfectiva.objects.count() ofertas_efectivas = OfertaEfectiva.objects.filter(oferta__completa=True, oferta__activa=True, oferta__finalizada=True) nombre_ofertas = [] # ocurrencias = 0 for efectiva in ofertas_efectivas: nombre_oferta = dict() postulado = dict() entrevistado = dict() seleccionado = dict() entrevistados = [] postulados = [] seleccionados = [] cand_seleccionados = ListaFinal.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) seleccionados_ids = cand_seleccionados.values_list('interesado_id', flat=True) cand_postulados = Postulados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=seleccionados_ids) postulados_ids = cand_postulados.values_list('interesado_id', flat=True) cand_entrevistados = Entrevistados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=postulados_ids) #DATOS #MÉTODO PARA VER CUANTAS OFERTAS NO TIENEN 1 ATRIBUTO# # if efectiva.oferta.region is None: # print(efectiva.oferta.id), # print(efectiva.oferta.titulo), # print(efectiva.oferta.nombre_empresa) # ocurrencias = ocurrencias + 1 # print("TOTAL = " + str(ocurrencias)) nombre_oferta['id_oferta'] = efectiva.oferta.id nombre_oferta['titulo_oferta'] = efectiva.oferta.titulo nombre_oferta['nombre_completo_owner'] = efectiva.oferta.owner.first_name + ' ' + efectiva.oferta.owner.last_name nombre_oferta['descripción'] = efectiva.oferta.descripcion nombre_oferta['cargo'] = efectiva.oferta.cargo nombre_oferta['vacantes'] = efectiva.oferta.vacantes nombre_oferta['nombre_empresa'] = efectiva.oferta.nombre_empresa nombre_oferta['descripción_empresa'] = efectiva.oferta.descripcion_empresa nombre_oferta['cultura'] = efectiva.oferta.cultura_empresa nombre_oferta['negocio'] = efectiva.oferta.negocio_empresa nombre_oferta['funciones'] = efectiva.oferta.principales_funciones nombre_oferta['industria'] = efectiva.oferta.industria.nombre nombre_oferta['linea_funcional'] = efectiva.oferta.linea_funcional.nombre nombre_oferta['nivel_cargo'] … -
Django for loop working on one template page, but disappears elsewhere?
I have written a Django for loop that iterates over each instance of my Supplier model to render each instance in my navigation bar. However for some reason it only outputs on one of my templates and not the main page. This is the loop in question: <ul class="nav-drop"> {% for supplier in suppliers %} <li> <a href="{% url 'supplier' pk=supplier.pk %}">{{ supplier.name }}</a> </li> {% endfor %} </ul> here is my views.py file: from django.shortcuts import render from . models import Supplier # Create your views here. def suppliers(request): suppliers = Supplier.objects.all() context = {'suppliers': suppliers} return render(request, 'suppliers/suppliers.html', context) def supplier(request, pk): supplier = Supplier.objects.get(id=pk) context = {'supplier': supplier} return render(request, 'suppliers/supplier.html', context) from django.urls import path from . import views urlpatterns = [ path('suppliers/', views.suppliers, name='suppliers'), path('supplier/<str:pk>/', views.supplier, name='supplier') ] and the model in question: class Supplier(models.Model): name = models.CharField(max_length=200, blank=True, null=True) logo_image = models.ImageField(null=True, blank=True, upload_to='models/', default="models/default.jpg") marketing_image = models.ImageField(null=True, blank=True, upload_to='models/', default="models/default.jpg") description = models.TextField(blank=True, null=True) short_description = models.TextField(max_length=200, blank=True, null=True) social_facebook = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_instagram = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id … -
Is it a good practice to use variables by 'with' tag in django template on global scope
I need to use more times some custon variables (e.g. one of them) with total=business.employees.count But I have a very lot of lines in my code and I think is constant use of them in different parts is not good. So is it good to insert these tags at the very beginning and close at the very end of the file? For example {% load static %} {% with total=business.employees.count %} <html> a lot of lines of code </html> {% endwith %} I need some advice -
Is there a solution to "does not appear to have any patterns in it." problem?
Have a nice day! While I was building my django project, I faced this error. Error: The included URLconf '<module 'posts.urls' from "D:\Created apps\My project\posts\urls.py">' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. So, here's given my project files. -------- posts/urls.py: ---------- ` from django.urls import path from .views import BlogListView, BlogDetailView url_patterns = [ path('', BlogListView.as_view(), name='index'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), ] ` ----------- posts/views.py: ----------- ` from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class BlogListView(ListView): model = Post template_name = 'index.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' ` ------------- config/urls.py: ---------- ` """config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) … -
how do I get value of dictionary 1 by key of dictionary 2 in Django templates
I have 2 dictionaries dict1 and dict2. I'm trying to get the value by the dict1 key to the dict2 key but it getting nothing, is there any way to get the value of dict2 by the dict1 key? always both dictionaries will be the same length? dict1 = {0:[1,2,3],1:[4,5,6]} dict2 = {0:'data1',1:'data2'} {% for key, value in dict1.items %} {{dict2.key}} {% endfor %} -
I ruined the admin page, how do I fix it? ( Django 4.1 )
I have followed the steps from the django tutorial ( https://docs.djangoproject.com/en/4.1/intro/tutorial01/ ) and once I'd finished all the steps I stopped developing the project for 2 weeks at least without giving it much thought. Once I've decided to check how the pages were looking like that's when I found this: The admin page And I don't know how I did it. Here's how the documentation looks like: meuSite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ migrations/ static/ templates/ admin/ base.html polls/ detail.html index.html results.html __init__.py admin.py apps.py models.py tests.py urls.py views.py db.sqlite3 manage.py SETTINGS: meuSite/settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] URLS: # meuSite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("polls/", include('polls.urls')), ] # polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:question_id>/', views.DetailView.as_view(), name='detail'), path('<int:question_id>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] If there's something else that I didn't show that may have the root of the problem, please tell me I tried solving it by deleting the templates/admin directory, but it didn't change how the page looks -
How can I send verification email on Django when user update email id using signals.py
how can I send verification emails on django using signals.py when a user updates the email id on the Custom profile model? This is my signals.py for updating the User model. I want to send a confirmation email when the user updates their email id. @receiver(post_save, sender=models.Profile_user) def update_auth_user_model_handler(sender, instance, created, **kwargs): if created: return user_instance = instance.user user_instance.first_name = instance.first_name user_instance.last_name = instance.last_name user_instance.email = instance.email user_instance.save() I want to send confirmation email to the new email when an user updates his email id before saving it to the User model on Django -
is there an efficient way of preventing the same email addresses registered with the different capitalizations sign up in django?
In views.py if User.objects.filter(email = email).exists(): messages.info(request, 'Email already in use') return redirect('signup') Django only checks if the exact email with the exact capitalization exists so for example if there is johndoe@yahoo.com in the user object and I signup with jOHNDoe@yahoo.com instead of telling it that email already in use it creates another user for the gmail with it's unique capitalization. admin user panel -
How to delete follow id base on both user_id and following_user_id using Django Rest Framework?
Okay, here's the thing I'm already able to create userfollowing relationship based on both the current user(user_id) and the user that is being followed (following_user_id). But what I want to do is to be able to delete a specific user_id and following_user_id following relationship by the id that was generated when the relationship was first established. Here's my code for better understanding. Thanks in advance for your help, which I will really appreciate. My UserFollowing Model class UserFollowing(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="following") following_user_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="followers") created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user_id','following_user_id'], name="unique_followers") ] ordering = ["-created"] def __str__(self): return f"{self.user_id.name} follows {self.following_user_id.name}" My UserFollowing Views class UserFollowingView(generics.ListCreateAPIView): # permission_classes = (IsAuthenticatedOrReadOnly,) serializer_class = UserFollowingSerializer queryset = UserFollowing.objects.all() class DeleteFollowView(generics.RetrieveDestroyAPIView): # permission_classes = (IsAuthenticatedOrReadOnly,) serializer_class = UserFollowingSerializer queryset = UserFollowing.objects.all() -
Page not found 404 django
Tengo este problema enter image description here y no se que hacer, he intentado algunas cosas pero no ha funcionado. Este es el archivo urls.py: enter image description here Creo que el problema esta en ese archivo pero no sabría como solucionarlo -
IntegrityError at /signup/ UNIQUE constraint failed: accountss_doctor.user_id
I'm trying to signup as Doctor but I got the following issue . raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: accountss_doctor.user_id this is my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True) name = models.CharField(_('الاسم :'), max_length=50) surname = models.CharField(_(' اللقب :'), max_length=50) subtitle = models.CharField(_('نبدة عنك :'), max_length=50) address = models.CharField(_("المحافضة :"), max_length=50) this is my views.py class DoctorSignupForms(UserCreationForm): username = forms.CharField(label="الاسم") first_name = forms.CharField(label="الاسم الاول") last_name = forms.CharField(label=" الاسم الاخير") number_phone = forms.CharField(label=" الهاتف") email = forms.EmailField(label="البريد الالكتروني") password1 = forms.CharField( label=" كلمة المرور", widget=forms.PasswordInput(), min_length=8) password2 = forms.CharField( label="تاكيد كلمة المرور", widget=forms.PasswordInput(), min_length=8) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'number_phone') @transaction.atomic def save(self): user = super().save(commit=False) user.email = self.cleaned_data.get('email') user.is_doctor = True user.save() doctor = Doctor.objects.create(user=user) doctor.username = self.cleaned_data.get('username') doctor.number_phone = self.cleaned_data.get('number_phone') doctor.save() return doctor I heard that it's because of the relation which it has to be foreinkey instead of one to one but I want every doctor have … -
reset id whenever a row deleted in django
i wanted to start id from 1 . whenever a row deleted it skips that number and jump to next number. like in this image it skips number from 1-6 and 8. i want to set it as 1,2,3 this is my models.py class dish(models.Model): id = models.AutoField(primary_key=True) dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to. dish_date = models.DateField() def __str__(self): return self.dish_name this is views.py def delete(request, id): dishs = dish.objects.get(id=id) dishs.delete() return HttpResponseRedirect(reverse('check')) -
How can I delete all user data when deleting profile on Django using signals.py
how can I delete all user data when deleting a user profile on Django using signals.py? I am trying to delete a custom user model using Django and when the profile is deleted I want to delete all data of that user using signals.py how can I create it? @receiver(post_delete, sender=models.Profile_user) def delete_auth_user_model_handler(sender, instance, *args, **kwargs): user_instance = instance.user user_instance.delete() I want to delete blogs of the user-written when the profile is deleted -
DRF - How to using serializer to load related data
I have a self related table Employee, and Project table has foreignkey to related to Employee table. class Employee(models.Model): eid = models.CharField(primary_key=True, max_length=10) name = models.CharField(max_length=10) pmid = models.ForeignKey('self', models.RESTRICT, related_name='team_member', blank=True, null=True,) class Project(models.Model): pid = models.CharField(primary_key=True, max_length=10) description = models.CharField(max_length=100) teamleaderid = models.ForeignKey(Employee, models.RESTRICT) and serializers.py class SubEmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): team_member = SubEmployeeSerializer(many=True, read_only=True) class Meta: model = Employee fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' depth = 1 views.py class ProjectList(generics.ListAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer I hope when request ProjectListView I can get teamleaderid with team_member data but I don't know why team_member not show in my response. [ { "pid": "p1", "description": "p1 project", "teamleaderid": { "eid": "1", "name": "n1", "pmid": null, ###### how to show below data ### # "team_member": [ # # { # # "eid": "5", # # "name": "n5", # # "pmid": "1" # #} # ################################# } } ] -
How to remove or disable unwanted languages in Django 4.1.1
I had a question about translations in Django... So I have a project with 4 languages defined in my settings.py LANGUAGES = [ ('en', _('English')), ('fr', _('French')), ('de', _('German')), ('it', _('Italy')), ] now I want to disable all languages except english, so I've been searching in google how to do it, and find this post on SO => enter link description here, than I tried to comment all languages except english, after that I've done ./manage.py makemigrations => ./manage.py migrate migrations went without any error, BUT in my language list they didn't dissapear... also I've been find code that as I think forms this list... I changed thare hardcoded langlist from language_list = ['en', 'it', 'de', 'fr'] to language_list = settings.LANGUAGES and also nothing happened with my UI language list choices... So, question: how properly I can disable unwanted languages in my Django application; P.S I'm new in python and Django at all, so please can anyone help me with this? -
400 bad request in "POST" request in django react
i have react component in were im posting data in djnago back end. but it always gives me 400 bad request as response and in backend console too. here is my code. ` import axios from 'axios' import React, { useEffect, useState } from 'react' import { Button } from 'react-bootstrap' import API_URL from './BackendDefaustUrls'; import {useNavigate, useParams} from "react-router-dom" const AddProduct = () => { const [Image , setImage] = useState(null) const [Name , setName] = useState("") const [Price , setPrice] = useState("") const [Description , setDescription] = useState("") const [Category , setCategory] = useState("") const navigate = useNavigate() const {id} = useParams() const getProduct = async () => { await axios.get(API_URL+`api/${id}/`).then(response => { return response.data }).then(data => { setName(data.name) setImage(data.image) setPrice(data.price) setDescription(data.description) setCategory(data.category) }) } useEffect(()=>{ getProduct() },[]) const AddProductInfo = async () =>{ let formField = new FormData() formField.append('name',Name) formField.append('price',Price) formField.append('description',Description) formField.append('category',Category) if (Image != null) { formField.append('image',Image) } await axios({ method: 'POST', url: API_URL + `api/`, data:formField }).then(response => { console.log(response.data); navigate("/") }) } return ( <div> <div className='container'> <div className="w-75 mx-auto shadow p-5"> <h2 className="text-center mb-4">Add A Student</h2> <div className='form-group'> {/* image */} <label>Select Image To Upload</label> <input type="file" name="image" className='form-control form-control-lg' onChange={e=>setImage(e.target.files[0])} /> </div> … -
How to add message box to admin panel
I have added my custom action that performs sending message to users. But I don't know how can I put my message where. So how can I add message field to my admin panel and connect to my custom action button? -
Django; Can't Access to Other Models inlineformset_factory Fields
I have a successfully working inlineformset_factory form. I create this model with a button and inherit the data in it from another model. However, I was not able to access the inlineformset_factory fields in the other model. def create_offer_button(request): if request.method == "POST": post = request.POST.get("post_pk") obj = RequestModel.objects.get(pk=post) if obj.is_accepted: OfferModel.objects.create(request_model_name=obj, request_title=obj.request_title, delivery_time=obj.delivery_time, shipping_country=obj.shipping_country, shipping_address=obj.shipping_address, preferred_currency=obj.preferred_currency, shipping_term=obj.shipping_term, delivery_term=obj.delivery_term) obj.is_offer_created = True obj.save() return redirect(request.META.get("HTTP_REFERER")) How can i access to RequestModel's inlineformset_factory fields? I tried many methods but I could not reach the formset fields of the inheritance model. -
Django: Object is not saved to DB when submitting form with CreateView
I have a CreateView to create artists but when submitting the form, nothing happens. models.py class Artist(models.Model): name = models.CharField(max_length=222, unique=True) slug = models.SlugField(unique=True, null=True) age = models.PositiveIntegerField(null=True,blank=True) location = models.CharField(max_length=222, null=True, blank=True) bio = models.TextField(null=True,blank=True) booking_fee_per_hour = models.PositiveIntegerField(verbose_name="Booking Fee per hour") def __str__(self): return self.name views.py class ArtistsAddView(views.CreateView): template_name = 'add_artist.html' model = Artist fields = '__all__' success_url = '/' templates -> add-artist.html <form method="post" action="{% url 'artist add' %}"> <p>{{ form.name.label_tag }} {{ form.name }}</p> <p>{{ form.age.label_tag }} {{ form.age }}</p> <p>{{ form.location.label_tag }} {{ form.location }}</p> <p>{{ form.bio.label_tag }} {{ form.bio }}</p> <input type="hidden" name="next" value="{{ next }}"> <button>Submit</button> {% csrf_token %} </form> I intentionally hid 2 of the fields: slug and booking_fee_per_hour. I would like to make them available only for admins. If I write: <form method="post" action="{% url 'artist add' %}"> {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}"> <button>Submit</button> {% csrf_token %} </form> then the artist is saved to the DB but also the normal user can see slug and booking_fee_per_hour. Could you please help me? -
TinyMCE referer header missing in Django
I am using TinyMCE to write text with markup in my Django project. Im am displaying the TinyMCE editor on a user page where they can type text with markup. This works just fine. However: The editor prompts the following message when displaying the page: We’re unable to check your domain because the referer header is missing. Please read the Guide on how to ensure your referer header is present, so we can then customize your editor experience. I can't seem to figure out what is missing and how to fix it. Any help would be much appreciated! In my models I implement the TinyMCE as follows: bottle_info = HTMLField() -
How to Override CreateModelMixin corrctly
I want to override CreateModelMixin with my own class which derived from ModelViewSet this is the class i want to override class CreateModelMixin: """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {} in the first instinct, I want to override only the create function with a different serializer but would it be more correct to override perform_create? if someone can guide me how it is the most correct way to override that will be much of help thank you -
How can i pass validated data to another custom validator class in DRF?
I Have this kind of serializer.py class PostSerializer(serializers.ModelSerializer): title = serializers.CharField(validators=[TitleValidator()]) slug = serializers.CharField(validators=[SlugsValidator()], max_length=100, required=False) and i have two class validators for this fields class TitleValidator: MIN_TITLE_LENGTH = 20 def __call__(self, title: str): if len(title) < self.MIN_TITLE_LENGTH: raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}") return title class SlugsValidator: def __call__(self, slug): # Get title here return slug How can I pass the validated title into SlugValidator class? I've tried to pass data directly to the TitleValidator instance, but the only thing I can get is the field itself, not an actual value. Another way was to pass data inside validate() method, but seems like custom class validators are executed first, and i' getting an error that the title argument is not provided. Is there any way I can achieve this? -
Bootstrap 5.0 Navbar Dropdown not working
I couldn't make the dropdown on my navbar work. When I click on it nothing happens. What might be the problem? I checked similar posts but couldn't find a solution. Am I missing a script or something? layout.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <nav class="navbar" style="background-color: #e6e2c2;"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="{% static 'potbs/potbs.png' %}" alt="Logo" width="50" height="30" class="d-inline-block align-text-top"> Pat on the Back Studios. </a> <div class="navbar-expand" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Profile </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Profile</a></li> <li><a class="dropdown-item" href="#">Earned Badges</a></li> <li><hr class="dropdown-divider"></li> <li><a class="nav-link" href="{% url 'logout' %}">Log Out</a></li> </ul> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> </li> {% endif %} </ul> </div> </div> </nav> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script> </body> </html> -
How to send JWT REFRESH TOKEN as http only cookie in django?
I am using Django(REST FrameWork, SimpleJWT) and React for my project. For autentication I am using JWT method. According to some articles, storing and sending REFRESH TOKEN in HttpOnly Cookie is the a best and secure way. Since I am learning WebDevelopment I can't able to find any source to about it. This is my views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer def post(self, request, *args, **kwargs): try: response = super().post(request) except InvalidToken: return Response({'Invalid or expired token'}) refresh_token = RefreshToken.for_user(request.user) response.set_cookie('refresh_token', refresh_token, httponly=True) return response class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer class LogoutView(generics.CreateAPIView): def post(self, request): refresh_token = request.data['refresh_token'] token = RefreshToken(refresh_token) token.blacklist() return Response({'Logout':'Successfullly'}) as you can i even tried to over write the post method in MyTokenObtainPairView. This is my urls.py path('api/login/', MyTokenObtainPairView.as_view(), name="token_obtain_pair"), path('api/token/refresh/', TokenRefreshView.as_view(), name="token_refresh"), path('api/register/', RegisterView.as_view(), name="auth_register"), path('api/logout/', LogoutView.as_view(), name="logout"), This is my settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(hours=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=2), } I am expecting a way to … -
API to get all pincodes inside a radius
I'm working on a python application where we need to get all the pincodes within a specific radius. We have a base location and a radius of 10Km is drawn from this base pincode. Do we have any API where this can be achieved? FYA - Mainly looking for Indian PostalCodes.