Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return a group by query via Django REST API?
I have a Django REST API which works perfectly when I want to query some data from the database. Here I have an example: views.py class ProductListAPIView(generics.ListAPIView): def get_queryset(self): # Collect data from products table and filter it queryset = Product.objects.filter(name="Ferrari", date__lte="2022-08-01") # <- Substitute with line below return queryset serializer_class = ProductSerializer authentication_classes = [authentication.SessionAuthentication, authentication.TokenAuthentication] permission_classes = [IsOwnerPermission] serializers.py from rest_framework import serializers from insert_data.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["name","category","date","price"] The output is what I expect i.e. a json response with the content of the database. The problems arise when I try to group the queryset in order to return the average price of a product. By doing some research in the internet I noticed that I just need to substitute the line of code in the views.py script with this: Product.objects.filter(name=params['name'], date__lte=query.date).values('name','category').annotate(price_average=Avg('price')).order_by() I am pretty confident that this does the work, however the API returns an error which I do not know how to fix: AttributeError: 'int' object has no attribute 'pk' I totally have no idea what this refers to. Would you be able to suggest a smart and elegant way to return the average price of a product … -
how to fix the text so that its code is not written?
I created a blog site. But when I create some style for the text in the blog, it is then displayed on the main page. for example, I create bold text when creating a blog example picture and the main page displays the code ex pic2 how to fix this? I created this form using Django code: def add_blog(request): form = AddBlogForm() if request.method == "POST": form = AddBlogForm(request.POST, request.FILES) if form.is_valid(): user = get_object_or_404(User, pk=request.user.pk) category = get_object_or_404(Category, pk=request.POST['category']) blog = form.save(commit=False) blog.user = user blog.category = category blog.save() messages.success(request, "Blog added successfully") return redirect('blog_details', slug=blog.slug) else: print(form.errors) context = { "form": form } return render(request, 'add_blog.html', context) -
Django large CSV export with celery (async)
I am trying to export a CSV file which takes a while to generate. I have written the export CSV view which is successfully working, however I needed to adapt it to use celery for it to work in production with large data volumes. I have written the following code (mostly following https://thoslin.github.io/async-download-with-celery/): View: from tasks import export_report @staff_member_required() def export_status_report(request): task = export_report.delay() return render(request, "admin/poll_for_download.html", {"task_id": task.task_id }) # Check if task is finished def poll_for_download(request): task_id = request.GET.get("task_id") filename = request.GET.get("filename") if request.is_ajax(): result = AsyncResult(task_id) if result.ready(): return HttpResponse(json.dumps({"filename": result.get()})) return HttpResponse(json.dumps({"filename": None})) try: f = open("/path/to/export/"+filename) except: return HttpResponseForbidden() else: response = HttpResponse(file, mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response Task: @app.task def export_report(): date = datetime.now() date = date.strftime("%m/%d/%Y") filename = "reoport"+date+".csv" response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename= "{}"'.format(filename) payouts = Payout.objects.all() writer = csv.writer(response) #instantiate writer # write headers writer.writerow(['Field1', 'Field2', 'Field3']) for payout in payouts: list = [payout.field1, payout.field2, payout.field3] writer.writerow(list) return filename HTML <script> $(function(){ $.ajaxSetup({ cache: false, timeout: 360000 }); var url = "admin/poll-for-download/"; var i = 0; (function worker() { $.getJSON(url+"?task_id=", function(data){ if(data.filename) { var file_url = url+"?filename="+data.filename; $("#content").html("If your download doesn't start automatically, please click … -
Responses is returned as string and not as json - Python
I am trying to send back (get requests) a json but instead is sending a json as string "{"series": [{"name": "Count of Signups", "type": "column", "data": [4, 29, 10]}, {"name": "Average of signups over last 3 Months", "type": "line", "data": [NaN, NaN, 14.0]}], "labels": ["2020-06", "2020-07", "2020-08"]}" The disire result its the same but as json without the quotes (not as string) { "series": [{ 'name': "Count of Signups", 'type': "column", 'data': [4, 29, 10], }, { 'name': "Average of signups over last 3 Months", 'type': "line", 'data': [NaN, NaN, 14.0], }], "labels": ["2020-06", "2020-07", "2020-08"] } here is my code, my view in django: def Apiname(request): start_date = request.GET.get('start') end_date = request.GET.get('end') res = { "series": [{ 'name': "Count of Signups", 'type': "column", 'data': [], }, { 'name': "Average of signups over last 3 Months", 'type': "line", 'data': [], }], "labels": [] } df = pd.read_csv("mycsvfile.csv") mask = (df['MonthYear'] >= start_date) & (df['MonthYear'] <= end_date) df = df.loc[mask] for i, row in df.iterrows(): res['series'][0]['data'].append(row['Count_of_signups']) res['series'][1]['data'].append(row['signups_3mth_moving_average']) res['labels'].append(row['MonthYear']) return HttpResponse(json.dumps(res), content_type="application/json") I tried with to_dict to parse it to json but got the same results, the most strage is that i have another APIs with the same structure and they return … -
How can I paginate a dictionary inside my model?
I have a model and I have a single page for each one. class Group(models.Model): name = models.CharField(max_length=150, unique=True, db_index=True) active = models.BooleanField(default=False) members = models.OrderedDictField(default=dict, blank=True) This is an example of a representation of members. { "Jeon Heejin": "Designer", "Kim Hyunjin": "Baker", "Jo Haseul": "Musician" } However, when I render a page that represents a group, some groups have more than 100 members. So, I want to paginate it, but I am not getting how to paginate a dictionary that is inside a model. I also tried to paginate my Views, but nothing had changed. class GroupView(DetailView): template_name = "tailwind/group_detal.html" model = Group slug_url_kwarg = "group_name" slug_field = "name" context_object_name = "project" paginate_by = 2 def get_object(self, queryset=None): try: return Group.objects.get(name=self.kwargs.get("group_name")) except Group.DoesNotExist: raise Http404 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context And this is the way that I am returning my items. <div class="md:grow mt-6 flex flex-col space-y-8 overflow-x-hidden"> {% for key, value in project.members.items %} <div class="overflow-x-auto"> <div class="mt-4 px-4 py-4 bg-gray-100 rounded-md font-mono"> <div class="overflow-auto"> {{ value | linebreaksbr }} </div> </div> </div> {% endfor %} </div> I am still getting all the items on the same single page, but my goal is to paginate … -
Altering command in Django not working , i want to alter database in django?
I added a new coloumn in table and than run command 1. python3 manage.py makemigrations 2. python3 manage.py migrate it show that nothing to migrate but when i entered data it is showing table not found this is my models.py class name(models.Model): name = models.CharField(max_length=255) role = models.CharField(max_length=255) salary = models.IntegerField() def __str__(self): return f"naam = {self.name} and Kaam = {self.role} and tankhwa = {self.salary}" and this is 0001_initial.py operations = [ migrations.CreateModel( name='name', fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID' ), ), ( "name", models.CharField( max_length=75, ), ), ( "role", models.CharField( max_length=75, ), ), ( "salary", models.IntegerField( ), ), ], ), ] -
django subclass not calling superclass (derived from modelform) clean method
I have a django form (formA) that inherits from modelform. In another app, I have a form that derives from that form (formB). This all works ok, including obtaining fields from the base class formA, but when the clean method is called, it doesn't call the formA clean method. Instead it skips formA, and calls django's modelform.clean. I can create a clean method in formB and this is called, but calling the super().clean() method also steps immediately into django's modelform.clean. Why might this be happening and what do I have to do to get the correct inheritance chain for the clean method? MTIA -
Django auth group permission handling
I use Django auth groups. The groups contain permissions(https://docs.djangoproject.com/en/4.1/ref/contrib/auth/#group-model). Now groups are assigned to users based on their actual role. In my test setup one group contains the permission (market.xyz). This group is assigned to the logged in user. In the debugger I see that the group permission is assigned (line 88) But if I call user.has_perm(per1) I get False (line 87) I can not make sense of this result. Is it necessary to activate the auth group mechanism? Do I have to add some additional Middleware? -
Django - analyze query execution time before it gets executed
I have a web interface(in django), through which I execute sql queries on different MySQL DB servers. Can we analyze query execution time(how much time it will take to return the result set) and the size of result set before it actually gets executed? I am using Django and MySQL DB. If cpu utilization is not much and the result set is in few KBs or bytes then query should get executed. -
Counting object views in a ListView
How is it possible to track how many times an object has been viewed if it is shown in a ListView? Imagine the Facebook feed, I want to know how many times users actually see each post on their feed, without opening it. My only thought so far is making an AJAX call for each post when it comes into the user's view, but that seems like it would be too resource heavy. Or should I aggregate the post views and only make the AJAX call once in a while with a list of posts that have been viewed? Or is there any other better way? (Doing it server-side is not ideal, because I want to know that a user actually read the post, so if they spent at least 2-3 seconds reading it). -
Django API rename Model column from existing DB
I have a column ag_id and I want to show it as foo_ag_id on the returning from endpoint. class Foos(models.Model): ag_id = models.ForeignKey('Bars', on_delete=models.CASCADE, db_column='bars_ag_id') class Meta: managed = False db_table = 'foos' I can't change the column name directly at the DB (external). FROM: { "ag_id": 1, }, TO: { "foo_ag_id": 1, }, -
Can I navigate between iPad web applications running on different systems withou show the Safari's url address bar?
I’m a software developer and I developed a web application for iPad using Django. I have four embedded systems connected to the same network and each system run his web application. I added the apple meta-tags for the full-screen mode, which remove the url address bar of Safari. My problem is that i need to navigate between the system’s pages, but, when I load the page of another system, Safari show the address bar. There is a way to don’t show the address bar when I load a page from another system if it has the apple meta-tag too? I tried to automatically touch the screen on "done" to remove the bar on load, but i cannot find a way to persistent remove this bar. -
Using django form to display data
Im new to django and am doing a django project where the user can book appointment slots. I want the user to input a date from a datepicker and then see the slots available to book on that day. I've tried using get requests but i keep getting errors. These are my models class Slot(models.Model): title = models.CharField(max_length=50) def __str__(self): return f'There is a slot at {self.title}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.ForeignKey(Slot, on_delete=models.CASCADE) booking_date = models.DateField(("Date"), default=date.today) def __str__(self): return f'{self.user} has booked a session at {self.slot.title} on {self.booking_date}' Where I set slots as available times (9-10am etc) These are my views def BookingView(request): form = BookingForm(request.POST or None) if form.is_valid(): form.save() form = BookingForm() context = { 'form': form } return render(request, "bookingapp/book_form.html", context) def DateView(request): form = DateForm(request.GET or None) if form.is_valid(): form.save() form = DateForm() context = { 'form': form } return render(request, "bookingapp/date_form.html", context) These are my Forms This is the form I will use when the user is booking the slot. class BookingForm(forms.ModelForm): class Meta: model = Booking fields = [ 'user', 'slot', ] And this is the form I have so far for the user inputting the date. class DateInput(forms.DateInput): … -
Django requests : response much slower than function itself
My application has performance issues (worsening during busy hours). I've noticed following strange behaviour : When I set up the django enviroment: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings.test") django.setup() and try to run the function itself: views.dataCheckFunction (9277 is entry parameter) for i in range(1,10): zac=datetime.now() views.dataCheckFunction(9227) kon=datetime.now() delta=kon-zac print(delta) It runs as expected and each run takes from 0.7s to 1s However when I try to call same function via for i in range(1,10): zac=datetime.now() views.dataCheckFunction(9227) res = requests.get(url='https://profiextra-test.generali.sk/api/policy/9227/dataCheckFunction/', headers={'Content-Type':'application/octet-stream'}) kon=datetime.now() delta=kon-zac print(delta) The duration of each call is very volatile and it can be from 2.3s to 10s The function makes approx 200 database calls. To reduce the traffic I use Memcache Any idea what can be the cause ? Thanks -
How to implement custom authentication on function based view in django rest framework?
if i have created a custom Authentication class CustomAuthentication(BaseAuthentication): def authenticate(self, request): return super().authenticate(request) how do I implement this in function based views? Normally we can use decorators as from rest_framework.authentication import SessionAuthentication, BasicAuthentication @authentication_classes([SessionAuthentication, BasicAuthentication]) def view(request): pass -
Why am I getting a "Cannot return null for non-nullable field" error when doing a query?
**FOLDER STRUCTURE ** models.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Director filter_fields = { "name": ["exact", "icontains", "istartswith"], "first_directed_episode__name": ["exact", "icontains"], "last_directed_episode__name": ["exact", "icontains"], "age": ["exact"], } fields = "__all__" interfaces = (relay.Node,) types.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) … -
Django filters startswith
filters by creating a very simple site. There is a view and the user searches an object that I added as an admin. Views.py from django.shortcuts import render from .filters import * def home(request): myqs = Kati.objects.all() myFilter = SearchForm(request.GET, queryset=myqs) return render(request, 'home.html', {'myFilter':myFilter}) Models.py class Kati(models.Model): name = models.CharField(max_length=200) product = models.CharField(max_length=200) timi = models.CharField(max_length=200) Filters.py import django_filters class SearchForm(django_filters.FilterSet): class Meta: model = Kati fields = ['name','product','timi'] Html <form action='' method='get'> {{myFilter.form}} <button>OK</button> </form> {%for i in myFilter.qs%} <p>{{i.name}}</p> <p>{{i.product}}</p> <p>{{i.timi}}</p> {%endfor%} It works but is there a way to show an object just by typing the first letter. For example if the name is abcd show the object if you write ab. Like __startswith__. -
Django Celery show return value of task
i have a problem to display the return value of my celery task to the client. Redis is my result backend. I hope someone can help me. Thats the code: tasks.py: @shared_task def create_task(task_type): sleep(int(task_type) * 5) data={ 'test':'test' } return data The task should return the data after sleep for the given time. views.py: def home(request): return render(request, "async_project/home.html") @csrf_exempt def run_task(request): if request.POST: task_type = request.POST.get("type") task = create_task.delay(int(task_type)) return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result, } return JsonResponse(result, status=200) urls.py: from django.urls import path from . import views urlpatterns = [ path("tasks/<task_id>/", views.get_status, name="get_status"), path("tasks/", views.run_task, name="run_task"), path("home", views.home, name="home"), ] settings.py: # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' home.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django + Celery + Docker</title> <link rel="stylesheet" type="text/css" href="/staticfiles/bulma.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> </head> <body> <section class="section"> <div class="container"> <div class="column is-two-thirds"> <h1 class="title">Django + Celery + Docker</h1> <hr><br> <div> <h2 class="title is-2">Tasks</h2> <h3>Choose a task length:</h3> <div class="field is-grouped"> <p class="control"> <button class="button is-primary" data-type="1">Short</button> … -
Using signals in django while extending user model
Basically I have 2 models that are 1 to 1 related with User model, First model in Employee and second one is Customer. I am also using signals for updates #Signal functions inside each model @receiver(post_save, sender=User) def create_customer(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def update_customer(sender, instance, created, **kwargs): if created == False: instance.customer.save() When I register a user it gets duplicated both in customer and employee. Is there a way to prevent this? -
Customize group permissions in django?
I need to make role-based authentication. Firstly, I made group permissions for all my apps. I assigned some of them to role according to role's ability. from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group class Role(models.Model): title = models.CharField(max_length=32) groups = models.ManyToManyField(Group) def __str__(self) -> str: return self.title Here you can a see driver role which has access on some group permissions (in fact they are just names of groups) Now I have a user model: class Users(AbstractUser): role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name='roles', blank=True, null=True) def __str__(self): return (self.username) I don't want to pick group permissions every time when I created a new staff user. I just want to set a role to a user and it should automatically pick all permissions based on selected role's groups. How to customize groups in django models? -
Post a CharField to an ArrayField in from React to Django using Axios
I am trying to create a feature where if a user writes a post the ID of the post goes into an ArrayField in the User model so a list of their writing can be accessed. I introduced a new column in the User database, made the necessary migrations and trialed this feature just saving one post ID which worked fine. The issue arose when I made the model field an ArrayField. Now when I do the POST request I get an error response : "{\"posts_written\":{\"0\":[\"Expected a list of items but got type \\\"str\\\".\"]} Currently I am writing the REQUEST as let newPost = new FormData() newPost.append('title', title) newPost.append('content', content) updatePostList.append('posts_written', id + ',') await API.patch(`/profile/user/${loggedInProfile.id}/update/`, updateArticleList, { headers: { 'Authorization': `Token ${sessionToken}`, 'Content-Type': 'multipart/form-data', }, }) I am unsure of how to write the POST request to work with the ArrayField, I have looked online for answers but can't find anything. Here is the User model class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) profile_image = models.ImageField(upload_to='profile_images', default='/profile_images/DefaultAvatar.png') bio = models.CharField(max_length=500, default='', blank=True, null=True) display_name = models.CharField(max_length=250, blank=True, null=True) articles_written = ArrayField( ArrayField(models.CharField(max_length=36, blank=True, null=True)), ) Thank you -
Django Ninja API framework ValueError: Cannot assign "*": "*.*" must be a "*" instance
My project running Django 4.1 and Ninja 0.19.1. I'm trying to make a post request via Swagger or Postman and getting an error ValueError: Cannot assign "115": "Offer.currency_to_sell" must be a "Currency" instance. Post data is: { "currency_to_sell_id": 115, "currency_to_buy_id": 116, "user_id": 1, "amount": 100, "exchange_rate": 10 } Endpoint in api.py @api.post("/add_offer/") async def add_offer(request, payload: OfferIn): offer = await Offer.objects.acreate(**payload.dict()) return {"id": offer.pk} schemas.py class OfferIn(ModelSchema): class Config: model = Offer model_fields = [ "currency_to_sell", "currency_to_buy", "user", "amount", "exchange_rate", ] What am I doing wrong? I tried different approach with Schema instead of ModelSchema and it worked. class OfferIn(Schema): currency_to_sell_id: int = None currency_to_buy_id: int = None user_id: int = None amount: float -
Django like system
I'm doing a blog project, but I have a problem, I'm doing a liking system on the blog, but it gives an error def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_create(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return reverse('main:post_detail') path('blog/like', views.like_post, name='like-post'), class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) <form action="{% url 'main:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> <button class="btn btn-primary" type="submit"> Like</button> <br> <strong>{{ post.liked.all.count }} Likes</strong> </form> That's the mistake I got. https://prnt.sc/y6AHr4buWReN -
MultiValueDictKeyError for multiple file uploads
Goal: I'm looking to have multiple file upload fields from one model, under one view and in one template. The issue is that I get this error: 'MultiValueDictKeyError' when submitting the post request. I have searched https://stackoverflow.com/search?q=MultiValueDictKeyError+file+upload but none of the responses appear to be applicable - as they only cover one field file uploads. Some context: Not all file uploads are required and some can be blank. The user just uploads whatever files are applicable. models.py def user_directory_path(instance, filename): return 'PDFs/{1}'.format(instance.user, filename) class PDFUpload(models.Model): class Meta: verbose_name_plural = 'PDF Uploads' user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) pas = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) add_pass = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) gas_safe = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) oftec = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) hetas = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) bba = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) forms.py class PDF(forms.ModelForm): class Meta: model = PDFUpload fields = ['pas', 'add_pass', 'gas_safe', 'oftec', 'hetas', 'bba'] widgets = { 'pas': ClearableFileInput(attrs={'multiple': True}), 'add_pass': ClearableFileInput(attrs={'multiple': True}), 'gas_safe': ClearableFileInput(attrs={'multiple': True}), 'oftec': ClearableFileInput(attrs={'multiple': True}), 'hetas': ClearableFileInput(attrs={'multiple': True}), 'bba': ClearableFileInput(attrs={'multiple': True}), } labels = { "pas": "PAS", "add_pass": "Additional PAS (if applicable", "gas_safe": "Gas Safe", "oftec": "OFTEC", "hetas": "HETAS", "bba": "BBA", } views.py @login_required def upload(request): if request.method == 'POST': pdf_upload = … -
In the following code I write the Login API but when I print the user it's give me None result
In the following code I created a Login API but when I hit the request in Postman it's always give me Error Response anyone help me out to rectify the problem. I post all of the code and dependencies so anyone can check and give me the solutions. This is my views.py file from django.shortcuts import render from rest_framework.permissions import AllowAny from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer, RegisterSerializer, UserLoginSerializer from django.contrib.auth.models import User from rest_framework import generics, permissions from rest_framework import status from django.contrib.auth import authenticate,login from django.contrib import auth # from knox.models import AuthToken # Create your views here. from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view #Login Credentials "//Create a Login API in Django?" class UserLoginView(APIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def get(self,request,format=None): serializer=UserLoginSerializer(data=request.data) # print(serializer.is_valid(raise_exception=True)); if serializer.is_valid(raise_exception=True): email = serializer.data.get('email') password = serializer.data.get('password') print(email) print(password) user=authenticate(email=email,password=password) print(user) if user is not None: login(request, user) return Response({'msg':'Login Success'},status=status.HTTP_200_OK) else: return Response({'msg':{'Email or Password Does not match'}},status=status.HTTP_404_NOT_FOUND) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #This is my serializer.py file. class UserLoginSerializer(serializers.ModelSerializer): email=serializers.EmailField(max_length=200) class Meta: model = User fields= ['email','password'] When I hit the request then its always give me error so please check my login api …