Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generating OpenAPI Schema in Django Rest Framework: URL Keyword in Update ViewSet
I'm trying to do something that should be pretty straight forward but I'm running into a problem that I can't make heads or tails of. I'm hoping someone can help me sort it out. I've created some API endpoints using DRF. Naturally, I have Create, Update, Retrieve, and Delete endpoints that I've constructed with the django_rest_framework.generics. I need to send some extra data into the Serializer from the ViewSet on both the CreateAPIView and UpdateAPIView. To accomplish this, I've extended the get_serializer_context() method on those ViewSets. I'm now trying to create OpenAPI documentation for those said endpoints. However, when I run generateschema in the manage.py it returns an error. This error occurs in each of the UpdateAPIViews where I've extended the get_serializer_context() method. An example of this error is shown below. AssertionError: Expected view UpdateStaffViewSet to be called with a URL keyword argument named "staff_id". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. Naturally, we'd think that I goofed the URL keyword or the lookup_field, just as the error states. Unless I'm looking over something obvious though, I just cannot see what the issue is. These endpoints function perfectly when tested using curl or postman. … -
Heroku not completing a django view?
So basically I have a django project thats deployed to heroku. My problem is that I have a view which is to perform multiple functions that are located in a different file. The issue here is that only the first two functions actually get completed. All the other functions do nothing and eventually heroku times-out. The weird thing though is that the first two functions are done within like 5 seconds but the other functions don't do anything. Here is a simplified version of the view if that helps. def music(request): user_search = request.POST.get('search').capitalize() if models.Song.objects.filter(Search=user_search): searchcreateobject(request) # this is a function in other file else: models.Song.objects.filter(Search=user_search).all().delete() searchcreateobject(request) # this is a function in other file Rock(request) # this is a function in other file Rap(request) # this is a function in other file return redirect(reverse('musicresult')) My best guess why this is happening is because maybe the file which contains all the functions is too large(its like 500 lines) and git simplies it and chops it up kinda like how it does on github. Im probably way off but please help this is really odd. The view actually works perfectly and as intended on my local server but heroku isn't … -
Django Model instance with variable
This is the only way I can get the value I need: User1.types1.r_q2.label I want to make it dynamic by replacing field name and textChoices with variable. How can I get it done? Models.py: class User1(models.Model): class r_q1(models.TextChoices): r_q2 = 'r_q2', 'second question' r_q3 = 'r_q3', 'third question' t_greeting = 't_greeting', 't_greeting' f_passport = 'f_passport', 'Contact with a human f_passport' r_q1 = models.CharField ( 'How can I help you, today?1', max_length=200, choices=r_q1.choices, blank=True, null=False ) This works but when I replace only fieldname: User1.types1[x].label When I do it for textChoices name it doesn't work and raise error: User1[y][x].label error: Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'ModelBase' object is not subscriptable Sidenote: I have many textChoices in my models.py. I didn't include them as they are not important here. -
Django сложение данных
У меня есть модели class Information(models.Model): full_name = models.TextField(null=False, verbose_name='ФИО южика') located = models.IntegerField(null=False) date_start = models.DateTimeField(auto_now_add=True, blank=True, verbose_name='Начало работы') date_end = models.DateTimeField(null=True, verbose_name='Конец работы') free_passenger = models.IntegerField(default=0, verbose_name='Бесплатных') child_passenger = models.IntegerField(default=0, verbose_name='Детских') age_passenger = models.IntegerField(default=0, verbose_name='Взрослых') age_and_child = models.IntegerField(default=0, verbose_name='1 детский 1 взрослый') age_and_2child = models.IntegerField(default=0, verbose_name='1 взрослый 2 детских') age2_and_child = models.IntegerField(default=0, verbose_name='2 взрослых 1 детский') age2_and_2child = models.IntegerField(default=0, verbose_name='2 взрослых 2 детских') different = models.TextField(null=True, verbose_name='Разное') class Meta: verbose_name = 'Статистику' verbose_name_plural = 'Статистика' class AllState(models.Model): date = models.DateField(auto_now_add=True, blank=True, verbose_name='Дата') free_passenger = models.IntegerField(default=0, verbose_name='Бесплатных') child_passenger = models.IntegerField(default=0, verbose_name='Детских') age_passenger = models.IntegerField(default=0, verbose_name='Взрослых') age_and_child = models.IntegerField(default=0, verbose_name='1 детский 1 взрослый') age_and_2child = models.IntegerField(default=0, verbose_name='1 взрослый 2 детских') age2_and_child = models.IntegerField(default=0, verbose_name='2 взрослых 1 детский') age2_and_2child = models.IntegerField(default=0, verbose_name='2 взрослых 2 детских') different = models.TextField(null=True, verbose_name='Разное') class Meta: verbose_name = 'Общая статистика' verbose_name_plural = 'Общие статистики' Вопрос состоит в том как суммировать общее кол-во по столбикам за день из Information в AllState, например я имею число 20 в трех строках базы данных в столбиках 2 взрослых 2 детских и мне нужно перевести уже 60 в 1 строку которая относиться к данному дню в AllState, тоесть суммировать все строчки за день и записать их в нужные столбики в AllState -
Migrations are not applying to specific model
The problem is whenever I try to migrate changes, migrations does'nt applying to this specific app which is named as Userinfo. The messege in my terminal is Operations to perform: Apply all migrations: admin, auth, books_details, contenttypes, sessions Running migrations: No migrations to apply. And that app is not listed in my above list also i don't know what could be the reason Models.py of that app from django.db import models import os # from django.conf import settings def upload_rename(instance,filename): exe=filename.split('.')[-1] filename=instance.user_name+'.'+exe try: os.remove(os.path.join('images','profile_image',instance.user_name,filename)) except: pass return os.path.join('profile_image',instance.user_name,filename) class Userinfo(models.Model): ''' User info ''' user_name = models.CharField(max_length=30, unique=True, null=False,primary_key=True) full_name = models.CharField(max_length=50, null=False) user_email = models.EmailField(max_length=254) college_name = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) profile_img = models.ImageField(upload_to=upload_rename, blank=True) ''' The Change I added ''' varified_user =models.BooleanField(default=False) Admin.py of that app from django.contrib import admin from .models import Userinfo admin.site.register(Userinfo) please any can help with this??? -
page is loading very slow in django
Hello I have a webproject which I am hosting, the problem is that a specific page is loading very slow. The reason is I guess the Jquery code where I am iterating through the lectures and I have more then 1200 lectures. I normally showed all lectures and filtered them with searching and then I thought it could be faster if I show nothing and only show it when someone is searching but it is still slow. Here is my html. Thank you in advance. html {% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"><h1 style="text-align:center;">Not Dağılımları</h1> <hr> </div> <div class="container"> <div class="form-group pull-right"> <input type="text" class="search form-control" placeholder="Ara"> </div> <span class="counter pull-right"></span> <table style="background-color:white;"class="table table-hover results"> <thead> <tr> <th >Hoca</th> <th>Fakülte</th> <th >Ders</th> </tr> <tr class="warning no-result"> <td><i class="fa fa-warning"></i> Sonuç Yok</td> </tr> </thead> <tbody> </tbody> </table> </div> <script> $(document).ready(function(){ $(".search").keyup(function () { $('tbody').find('tr').remove(); var searchTerm = $(".search").val().toLowerCase(); if (searchTerm.length>2){ list=[] {%for lec in lecturer_list%} if( '{{lec}}'.toLowerCase().includes(searchTerm)){ $('tbody').append('<tr><td><p><a style="text-decoration:none;color:#002855;" href="{% url 'distribution:lecturer_distribution' slug=lec.slug%}">{{lec.lecturer}}</a></p></td><td><p>{{lec.faculty}}</p></td><td style="color:white;">{%for ders in lec.lecture.all%}<a style="text-decoration:none;color:#002855;" href="{% url 'distribution:lecture_distribution' slug=ders.slug%}">{{ders.lecture}}</a>,{% endfor%}</td></tr>'); } {%endfor%} } }); }); </script> {% endblock content%} -
How can I add additional company fields when creating a new user using Stripe with Angular and Django?
I am working on my application with the Django backend and the Angular frontend and I am gonna use Stripe. At this point everything seems to be working properly however I have some doubts how can I automatically collect all needed information associated with chosen company to send new invoice at the beginning of each subscription month. At the moment I do everything like shown below. The problem is that in Angular the form has no additional fields like company name, address etc. Any ideas what information I need and how can I collect them automatically (without manually update in Stripe dashboard) to be able to create a correct invoice? Django: try: customer = stripe.Customer.create( email=user.email, source=request.data['token'] ) except stripe.error.CardError as e: try: decline_code = e.json_body['error']['decline_code'] except: decline_code = e.json_body['error']['code'] if decline_code in decline_status: return Response( {'error': True, 'message': decline_status[decline_code]}, status=status.HTTP_403_FORBIDDEN) else: return Response( {'error': True, 'message': 'Your card was declined.'}, status=status.HTTP_403_FORBIDDEN) subscription = stripe.Subscription.create( customer=customer.id, items=[ { 'plan': 'my_plan', 'quantity': request.data['amount'], }, ], # collection_method='charge_automatically', expand=['latest_invoice.payment_intent'], ) -
SPF not working with django, back arrow not changing page
I'm using spfjs, refer to this link - http://youtube.github.io/spfjs/ but when I click the back arrow after clicking on the link with the `.spf-link' class and going to that page, it doesn't change the page, it only updates the title. <script src="https://cdnjs.cloudflare.com/ajax/libs/spf/2.4.0/spf.js"></script> <script> spf.init(); </script> <li class="is-inline"><a href="{% url 'signup' %}" class="spf-link">Sign Up</a></li> -
Reverse for '' not found. - Django
I'm a beginner at Django/programming in general. I have a problem with a redirecting url button on one of my HTML pages. Basically I have a collection page where one can add plants. Once a plant has been added, more details can be added to that plant. My CreateViews have been created, when I want to add the button to add details to an existing plant I get a reverse for not found error once I open the plant page. The bold part in the html code is where I'm getting the error from. models.py class PlantDetail(models.Model): """This class contains various types of data of added plants""" """links the details to one plants""" from datetime import date plant = models.ForeignKey(Plant, on_delete=models.CASCADE) date_purchased = models.DateField(default=date.today) notes = models.TextField() def __str__(self): """Return the detail input from the user""" return self.notes def age(self): """Return the age of the plant in days""" age_days = datetime.date.today() - date_purchased return age_days.days def get_absolute_url(self): return reverse('detail', args=[int(self.plant_id)]) urls.py urlpatterns = [ # Landing page path('', views.home, name='home'), # Collection page path('collection/', login_required(CollectionListView.as_view()), name='collection'), # Detail page for a plant path('collection/<int:plant_id>/', views.detail, name='detail'), # New plant creation page path('collection/add/', login_required(PlantCreateView.as_view()), name='plant-create'), # Add details to an existing plant … -
Is there a way to disconnect the post_delete signal in simple history?
I need to bulk_create the historical records for each object deleted in a queryset. I've coded it correct I think as follows. def bulk_delete_with_history(objects, model, batch_size=None, default_user=None, default_change_reason="", default_date=None): """ The package `simple_history` logs the deletion one object at a time. This does it in bulk. """ model_manager = model._default_manager model_manager.filter(pk__in=[obj.pk for obj in objects]).delete() history_manager = get_history_manager_for_model(model) history_type = "-" historical_instances = [] for instance in objects: history_user = getattr( instance, "_history_user", default_user or history_manager.model.get_default_history_user( instance), ) row = history_manager.model( history_date=getattr( instance, "_history_date", default_date or timezone.now() ), history_user=history_user, history_change_reason=get_change_reason_from_object( instance) or default_change_reason, history_type=history_type, **{ field.attname: getattr(instance, field.attname) for field in instance._meta.fields if field.name not in history_manager.model._history_excluded_fields } ) if hasattr(history_manager.model, "history_relation"): row.history_relation_id = instance.pk historical_instances.append(row) return history_manager.bulk_create( historical_instances, batch_size=batch_size ) The problem though is I need to disconnect the post_delete signal so that a historical record isn't created by simple history before i do it all at once. I've tried this but it doesn't work. models.signals.post_delete.disconnect(HistoricalRecords.post_delete, sender=Customer) Where Customer is just a class I'm using to test this utility function. Can anybody advise? Thanks in advance. Asked the question on their github page also - https://github.com/jazzband/django-simple-history/issues/717 -
i keep getting error 404 while trying to create a blog using django with the djangogirls tutorial
i keep getting an error (404) page when i run my server for a django when i click the link to a post detail. I think nothing is wrong with my code so i need help to locate why i'm getting the error. this is my views.py from django.http import HttpResponse from .models import Post from django.utils import timezone # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('created_date') return render(request, 'blog2app/home_post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog2app/postdetail.html', {{'post': post}}) this is my appname\urls.py from django.urls import path from . import views urlpatterns = [ path(r'^$', views.post_list, name="homepage"), path(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), ] this is my projectname/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path(r'^admin/$', admin.site.urls), path(r'^$', include('blog2app.urls')), ] this is my home_post_list.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for post in posts %} <p><h4>Published: {{ post.published_date }}</h4></p> <h1><strong><a href="{% url 'post_detail' pk=post.pk %}"> {{ post.title }} </a></strong></h1><br> {% endfor %} </body> </html> this is my detailpost.html <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if post.published_date %} {{ post.published_date }} {% endif %} <h1>{{ post.title }}</h1> <p>{{ post.body|linebreaksbr }} </body> </html> ```[this is … -
Get all Foreign Keys of a Foreign Key in Django
For example, If there was a model Bookshelf which had a foreign key to a model Books that was accesible by bookshelf.books, and the Book model has a foreign key Author (accesible through book.authors), how would I get all the authors from a Bookshelf? I could do: author_qs = QuerySet(Author) for book in my_bookshelf.books.all(): author_qs |= book.authors.all() But I doubt this is very efficient. Any help is much appreciated. (If it matters, I'm using Postgres) -
NoReverseMatch at /notes/create/ Reverse for 'notes_list' with no arguments not found. 1 pattern(s) tried: ['notes/list/(?P<username>[^/]+)$']
I don't know how can i add link of user notes list in side bar. the error is coming in the given following lines of template pages/base_stuff/side_bar.html <li class="active treeview"> <a href="{%url 'notes:notes_list' notes.author.username %}"> <i class="fa fa-dashboard"></i> <span style='font-weight: normal;'>Your Notes</span> </a> </li> notes/urls.py app_name = 'notes' urlpatterns = [ path('list/<str:username>',views.NotesListView.as_view(),name='notes_list'), ] notes/views.py class NotesListView(LoginRequiredMixin,ListView): login_url = '/accounts/login/' model = Notes context_object_name = 'notes_data' # paginate_by = def get_queryset(self): user = get_object_or_404(auth.models.User, username=self.kwargs.get('username')) return Notes.objects.filter(author=user).order_by('-create_date') -
How to add multiple images to a model?
Wagtail My model code: class HomePage(Page): images = models.ImagesField(max_count = 20) // How to do it right? content_panels = Page.content_panels + [ ImagesChooserPanel('images'), ] How it should look Please help! -
Django external API requests (question mark / ampersand)
I'm trying to get the result of an APi. The thing is I don't really know how to make it like that: https://api.spoonacular.com/food/images/analyze?apiKey=MY_KEY&imageUrl=IMAGE_URL. When I do it manually everything works. apiKey works with ? imageUrl works with & Assume I got a Post model and inside of this model I got a field url_image. if self.url_image: url = "https://api.spoonacular.com/food/images/analyze" querystring = {"imageUrl":self.url_image} headers = { 'apiKey': "MY_KEY" } result = requests.request("GET", url, headers=headers, params=querystring) if result and len(result): self.fat = result[0]['fat']['value'] self.proteines = result[0]['protein']['value'] self.glucides = result[0]['carbs']['value'] super().save(*args, **kwargs) The thing is with this code I can not access to it because the order is not good. Do you have any similar post you can advice me to read in order to understand how I can make API_KEY as ? and imageURL as & -
OSError: [Errno 9] Bad file descriptor in oauth2client on Ubuntu 20.04
This code below runs fine on my macOS 10.15.6. However, when I deployed the code on an Ubuntu 20.04-server I'm getting OSError: [Errno 9] Bad file descriptor class Command(BaseCommand): def handle(self, *args, **options): credentials = ServiceAccountCredentials.from_json_keyfile_name( self.get_json_file_path(), ['https://www.googleapis.com/auth/analytics.readonly']) self.http_auth = credentials.authorize(Http()) service = build('analytics', 'v3', http=self.http_auth) print(service) def get_json_file_path(self): return settings.BASE_DIR + "/onf/" + "google_client_secrets.json" I'm running the same python versions on macOS and the Ubuntu server: macOS 10.15.6 Python 3.8.2 (default, Aug 25 2020, 09:23:57) [Clang 12.0.0 (clang-1200.0.32.2)] on darwin Ubuntu 20.03 Python 3.8.2 (default, Aug 25 2020, 09:23:57) [Clang 12.0.0 (clang-1200.0.32.2)] on darwin Any ideas on what's going wrong here? -
Django Rest Framework: How to render data from database with specific object id
I'm building a project in Django Rest Framework where users get to see the list of shoes or the detail of the shoe. When I enter the url to list all the shoe it display correctly, when I enter the url with the id of the object, the HTML displays nothing. Here is my model class shoes_brand(models.Model): brand = models.CharField(max_length=15) class Meta: db_table = 'Brand' verbose_name='Brand' verbose_name_plural = 'Brands' def __str__(self): return self.brand class shoe(models.Model): name = models.CharField(max_length=15) foot_size = models.DecimalField(max_digits=3, decimal_places=1) price = models.DecimalField(max_digits=4, decimal_places=2) quanity = models.DecimalField(max_digits=3, decimal_places=0) available = models.BooleanField(default=False) brand = models.ManyToManyField(shoes_brand) def __str__(self): return self.name My view from .models import shoe, shoes_brand from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.response import Response from rest_framework.views import APIView class list_object(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'rest/list.html' def get(self, request): queryset = shoe.objects.all() context = { 'object' : queryset } print(context) return Response(context) class detail_object(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'rest/detail.html' def get(self, request ,pk): queryset = shoe.objects.get(pk=pk) context = { 'object' : queryset } print(context) return Response(context) My url from django.urls import path from .views import list_object, detail_object app_name = 'shoes_app' urlpatterns = [ path('list/', list_object.as_view(), name="List_all"), path('detail/<int:pk>/', detail_object.as_view(), name="Detail_object"), ] My serializer class ShoeSerializer(serializers.ModelSerializer): class Meta: model = … -
Why we use dj_rest_framework on Django ? Sorry is that flop question . Please help me to understand this
I can use serializers.py and permission.py from the rest. However, I don't get it about rest. Many forms show me about dj_rest_framework used for API. -
how to use custom fonts in django-ckeditor?
first time i am using ckeditor in django project. i want to use custom font family in django-ckedtor. i have spent lots of time to about that but it's not working. if anybody know about using custom font in django-ckeditor. please tell me? settings.py CKEDITOR_CONFIGS = { 'default': { 'contentsCss': ["body {font-size: 18px;}", '{% static "desk/fonts/Nafees-Nastaleeq/css/font.css/"'], 'font_formats': 'Nafees Nastaleeq; Andale Mono = andale mono, times Arial Black = arial black, Comic Sans MS = comic sans ms, sans-serif', 'width': 'auto', 'toolbar': [ ['Bold', 'Italic', 'Underline'], ['Font', 'FontSize', 'TextColor', 'BGColor'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] ], } } -
AJAX is not passing hard-coded data
In index.js I have: $("#weather_form").on("submit", function(event){ event.preventDefault(); $.ajax({ url: "/weather/", type: "POST", data: {type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"}, dataType: "json", contentType: "json", success: function (data){ alert("success"); }, error: function(xhr,errmsg,err) { alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText); } }); }); I'm getting the following error: So we know it's going into the error function of the AJAX call because of the popup. But why? I specifically hard-coded the JSON values to pass. Things I've tried, but to no avail: data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"}) -
Django and amazon aws s3 bucket, static and media, how to setup correctly?
i am configuring aws s3 for my django project, i have seen various tutorials but i am not sure if i configured it properly. Some infos that might be useful: My IAM user is in a group with a AmazonS3FullAccess policy; I enable public access to my bucket; I updated the bucket CORS configuration according to this heroku tutorial. <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> policy bucket: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my_bucket/*" } ] } these are my configurations. are safe or need to do some further configuration? Thank you very much! -
POST data using XMLHttpRequest
I've the following endpoint in django that I send data to, in order to be saved to disk: if request.method == 'POST': fout = open('leak.txt', 'a') leak = request.POST['leak'] fout.write(leak) fout.close() return HttpResponse('<h1>ok</h1>') return HttpResponse('<h1>Post data here</h1>') Then I send the following sample data (which includes character like { } ;) to it: var xhttp = new XMLHttpRequest(); xhttp.open("POST", "http://127.0.0.1:8000/leak/", true); xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhttp.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE && this.status >= 200) { console.log(this.responseText) } }; let str = "leak=function(){ eval(1+2); var x = 3;}" //data sent xhttp.send(str); But only "function(){ eval(1 2)" is saved at the endpoint. How should I format the string in java-script before sending in order to receive everything properly? -
search a calculated field django?
So i have a secret in code and use sha256 encode it in logs. so i need to search this in admin i have tried annotation but it does not work so i want to add a calculated field so i don't keep redundant data is but property decorated functions in django cannot be searched in admin. Is there any other ways to do this? this is the annotation way: def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset |= self.model.objects.annotate(sha256_search=sha256_hash("key")).filter(sha256_search__contains=search_term) return queryset, use_distinct and i get the error: TypeError: QuerySet.annotate() received non-expression(s): 2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683. this is the property field witch i cannot add to the: @property def sha256_key(self): return sha256_hash(self.key) -
Django error ''Page not found (404)'' even objects exists in database
Well i am getting 404 error even my user exist in database i tried to solve this but i couldn't can you guys help me. I really need help. notes/views.py class NotesListView(LoginRequiredMixin,ListView): login_url = '/accounts/login/' model = Notes context_object_name = 'notes_data' # paginate_by = def get_queryset(self): user = get_object_or_404(auth.models.User, username=self.kwargs.get('username')) return Notes.objects.filter(author=user).order_by('-create_date') if i comment out the user line and in return line i replace user variable with user primary key than it shows all notes related to that user. But obviously i can't use same primary key in views or every user so i need to grab specific user and show him its notes list. and I am unable to do this. I need little help can you guys help me.? -
Django Stateless API
I am trying to understand the excat meaning of stateless and found this in Google and I have a small doubt. I have a Django API which fetches some data from PostgreSQL database and returns the same. How is this API stateless, as it is relying on external database?