Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you do nested routes in Django using drf-extension
I have a model with fields and I want to get all data from that table that is populated in my psql database back. However, I also want to have a url that gets back all data that meets a specific criteria. So filtering for the data based on url params. These are for certain fields on my model. How can I do this using something like drf-extensions -
how to call custom data from Django User models
im using the built in User model of django and have added few custom fields one of them being the user type, i want to set up conditional statements according to the e_type this is my code. models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib import auth from django.conf import settings class User(auth.models.User,auth.models.PermissionsMixin,models.Model): EMPLOYEE='em' MANAGER='mn' USER_TYPE=[ (EMPLOYEE,'employee'), (MANAGER,'manager'), ] e_type=models.CharField(max_length=2,choices=USER_TYPE,default=EMPLOYEE) no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1), MaxValueValidator(24)],default=24) def __str__(self): return "@{}".format(self.username) views.py from django.shortcuts import render from django.contrib.auth import views as auth_views from .models import * from django.views.generic import TemplateView def home(request): user=request.user.e_type return render(request,"leaveApp/home.html") -
How do i generate an index number to display in the template
This might be a very simple question but i'm very new to django So i'm working on Django book list app and i need to have an index for each book in order. i was using id that was generated by the database at first but then i realized the number jumps from 3 to 10 cause i was deleting some books earlier. How do i generate an index number for every object in the queryset in order? Here's my views just incase def booklist_view(request): queryset = Book.objects.all() bkff = BookListForm() if request.method == 'POST': bkff = BookListForm(request.POST) if bkff.is_valid(): bkff.save() bkff = BookListForm() context = { 'form': bkff, 'arrayobj': queryset, 'index': 0 } return render(request, 'booklist1st/booklist.html', context) and here's my HTML {% for ins in arrayobj %} <div class="data" id="test"> <div class="num"><p>{{ins.id}}</p></div> <div class="title"><p>{{ins.title}}</p></div> <div class="author"><p>{{ins.author}}</p></div> <div class="ISBN"><p>{{ins.isbn}}</p></div> <div class="edit"><a href="#">Edit</a></div> <div class="delete"><a href="#">Delete</a></div> </div> {% endfor %} -
how to write serializer and models in django for my custom output?
Below the json i want to pass from postman and want to store in django models, Please note province_name,email,country_code,phone_number should be save in respected table and addressline1, addressline2, postcode should be save in respected table, how to achieve this in serializer and django model. { "user_id": 3, "designation_id": 1, "province_name": "xxxxxxxxxxx", "email": "xxxxxxxxxxx@gmail.com", "country_code": "54321", "phone_number": "9876543210", "address_line1": "aaaaaaaaaaaaaaa", "address_line2": "aaaaaaaa", "province_id": 1, "district_id": 1, "city_id": 1, "postcode": "12345" } -
Issue in making changes on the site, hosted on pythonanywhere
I'm hosting my blog site on pythonanywhere. I also have a model field for subscribers in the database. The problem is whenever ever I create a new post locally and pull it in pythonanywhere bash console. The local database replaces the production database. Which results in losing all the data provided by the users. How to stop some fields from changing on every pull request? class Category(models.Model): created_on = models.DateTimeField(auto_now_add=True, verbose_name="Created on") updated_on = models.DateTimeField(auto_now=True, verbose_name="Updated on") title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() image_file = models.ImageField(upload_to='media', null=True, blank=True) image_url = models.URLField(null=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) published_date = models.DateTimeField(blank=True, default=timezone.now ,null=True) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ('-published_date',) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_on',) def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) class Subscribe(models.Model): email = models.EmailField() subscribed_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-subscribed_on',) def __str__(self): return 'Subscribed by {} on {}'.format(self.email, self.subscribed_on) -
How to use User Model defined in models.py for Authetication in Django Rest Framework
What I want to do 1.Introducing authentication in Django Rest Framework 2.Doing authentication using User model I defined in as models.Model, not admin-user provided by django by default. Version django : 3.1 djangorestframework:3.11.1 python : 3.7.6 Situation I am trying to creating an app that each user can exchange their items. I use Django in server side, and React in client side. In order to introduce authentication and registration, I created User model in models.py. However, when I try to introducing these features in Django Rest Framework I notice that I may not be able to do that using User I define, perhaps I have to use admin-user django provides. Question __ First of all, can I introduce authentication and registration features using User model I define myself ?__ I found I can edit admin-user itself so I edited it. It doesn't work. Honestly, I don't understand whether I can introduce these features using User model as well. I would like to teach me how to figure it out. And I would like to those who have combined Django and React to teach me some way to realize authentication and registration. Thank you very much. This is my User model. … -
Integrating Stripe Payment gateway with Django Rest Framework (DRF) and use it with Flutter
I want to use Stripe Payment Gateway for my Django Rest Framework (DRF) API which is going to be consumed by my flutter app. I could have used Strip's plugin in Flutter but I think that is not the actual process. I want to know the actual way of integrating payment gateway with a Django Rest Framework API. -
how do you work together on github project but sync databases in the code? Django
Hi How would you go about using the same database in django when working on a web application together via github? New to web apps and collaborating :) thank you! -
How does Django get id on url?
When i clicked my menu url only gets category name and slug cant reach id how can i solve that ? This is the url i get def category_products (request,id,slug): category=Category.objects.all() products=Product.objects.filter(category_id=id) context={'products':products,'category':category,'slug':slug, } return render(request, 'kiliclar.html', context) urlpatterns = [ path('category/<int:id>/<slug:slug>/', views.category_products,name='category_products'), ] template {% recursetree category %} <li class="dropdown"> <a href="/category/{{ node.slug }}" class="nav-link dropdown-toggle arrow" data-toggle="dropdown">{{ node.title }}</a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> <li><a href="#">{{ children }}</a></li> </ul> {% endif %} -
Order of Values from a Django Foreign Key Reverse Lookup
I have two models, Document and DocumentImage. Document has a primary key called document_id, and a foreign key to DocumentImage. Say I have a list of document_ids and I run this query: images = DocumentImage.objects.filter(document__in=document_ids) as a reverse lookup through the foreign key relationship Is it true that images[0] is derived from document_ids[0], and images[1] is derived from document_ids[1], etc? I need to combine each element in images with each element in document_ids, and I want to make sure that I have the correct document_id for that element from images. In other words, I want to do this: for document_id, image in zip(document_ids, images): # associate the document_id with the image and make sure that each image is associated with the correct document_id. Thanks! Mark -
Allow user to view previously submitted form in Django
I made a a web app where the user can submit a form. I want the user to be able to view his submission but I can't figure out how to access the previously submitted data. I keep getting an error related about failing to reverse match failure. The error says Reverse for 'apply_view' with no arguments not found. 1 pattern(s) tried: ['submission/(?P<apply_id>[0-9]+)/$'] Views.py @login_required def apply(request): """Submit application""" if request.method != 'POST': form = ApplicationForm() else: form = ApplicationForm(data=request.POST) if form.is_valid(): new_application = form.save(commit=False) new_application.owner = request.user new_application.save() return redirect('credit_apply:submitted') context = {'form': form} return render(request, 'credit_apply/apply.html', context) def apply_view(request, apply_id): """View and maybe? edit application""" application = Application.objects.get(id=apply_id) if request.method != 'POST': form = ApplicationForm(instance=application) else: form = ApplicationForm(instance=application, data=request.POST) if form.is_valid(): form.save() return redirect('credit_apply:submitted') context = {'application': application, 'form': form} return render(request, 'credit_apply/submission.html', context models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth import get_user_model as user_model User = user_model() # Create your models here. class Application(models.Model): """App para las aplicacions de credito""" first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) business = models.CharField(max_length=100) m_number = PhoneNumberField(max_length=16) email = models.EmailField(max_length=254, unique=True) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name} {self.business}" url pattern path('submission/<int:apply_id>/', … -
how can i filter comments by user and by article with get_context_data Django?
i want to filter the comments by user and by post. would you like to tell me how can i filter the comment using get_context_data. i am getting this error with that code 'NewsDetailView' object has no attribute 'get_object_or_404' how can i solve this issue? models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) commentator = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.article.title views.py class NewsDetailView(LoginRequiredMixin, DetailView): model = Article form_class = CommentForm template_name = 'news/news_detail.html' def get(self, request, *args, **kwargs): self.object = self.get_object_or_404(User, username=self.kwargs.get('username')) self.object = self.get_object_or_404(Article, pk=self.kwargs.get('pk')) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = self.object context['form'] = CommentForm() return context def post(self, request, *args, **kwargs): if request.method == 'POST': form = CommentForm(request.POST) form.instance.article = Article.objects.get( pk=self.kwargs.get('pk')) form.instance.commentator = self.request.user form.save() return redirect('news:news-detail', pk=self.kwargs.get('pk')) else: return redirect('news:news-detail', pk=self.kwargs.get('pk')) -
Django soft resize uploaded Image to multiple sizes and upload to respective folder
I have the following model on my App def image_path(self, filename): return 'app_name/images/{}/{}'.format(slugify(self.name), filename) class Color(models.Model): name = CICharField(max_length=22, unique=True) image = models.ImageField("Image", upload_to=image_path, blank=True) Once the image is uploaded I want to create 3 images size: small (100 by 100), medium (300 by 300) and large (800 by 800) with the soft image crop. Then I want to manage the URL Structure for my upload. For Eg. Original Image URL from "Image" field = 'app_name/images/image_1.jpg' if I upload the image, Then it will produce the following images. small = 'app_name/images/small/image_1.jpg' medium = 'app_name/images/medium/image_1.jpg' large = 'app_name/images/large/image_1.jpg' Can anyone tell me, How can I achieve this on Django. Thanks. -
How do I consume data from Django Rest Framework API with frontend javascript (separate repository)
I can view my api with the Browsable API and I can make calls to my DRF API using postman, but I can't seem to integrate with a frontend. The same goes whether it is deployed or local. These are the headers from the response in Postman: Date →Sat, 05 Sep 2020 23:29:15 GMT Server →WSGIServer/0.2 CPython/3.8.5 Content-Type →application/json Vary →Accept, Cookie Allow →GET, HEAD, OPTIONS X-Frame-Options →DENY Content-Length →185 X-Content-Type-Options →nosniff Referrer-Policy →same-origin These are some of the settings I have implemented for my DRF API settings: ALLOWED_HOSTS = ['*'] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny' ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], } MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ) CORS_ORIGIN_ALLOW_ALL=True Here's a call that I'm attempting to make from my local react project which returns empty: const [data, setData] = useState(); useEffect(async () => { const result = await axios.get( 'http://127.0.0.1:8000/movies/1', { headers: { 'Content-Type': 'application/json' } } ); setData(result); }, []); I've attempted to consume the data with local and remote JS frontends to no avail. -
How to check if value from a field in a table object is equal to specific string in django template language?
I am iterating over all the entries in a django table called Ideas. One field in the table is status, and I want to check if the status is equal to some specific string. I have already checked that I am accessing this field correctly, with idea.status in my case, but I can't find how to compare that entry to a specific string in the django template language docs. I am trying to change a table's cell color based on what is in that cell. Here is what I tried, but to no avail: {% for idea in ideas_list %} ... {% if idea.status == 'Not Started' %} <td style="background-color:red;"> {% elif idea.status == 'Completed' %} <td style="background-color:green;"> {% elif idea.status == 'In Progress' %} <td style="background-color:yellow;"> {% else %} <td> {% endif %} {{idea.status}} &nbsp;</td> ... {% endfor %} My page is still rendering with the status text in the table, suggesting to me that all the if's were failed, which would end in the else condition being met, giving <td>{{idea.status}} &nbsp;</td>, with no cell color, and suggesting to me the problem is in my if statements themselves. -
is there way to add Pagination to html page in Django?
i have problem when i try to add pagination to my home html page , i tried this in my code but i got error .. i tried do this : views.py def home_page(request, template='html_file/enterface.html'): contextt = { 'opratingSystems': OpratingSystems.objects.all(), 'androidgames': AndroidGames.objects.all(), 'androidapk': AndroidApks.objects.all(), 'antivirus': Antivirus.objects.all(), 'pcgames': PCgames.objects.all(), 'pcprogram': PCprogram.objects.all(), } app = pcgames.objects.all() page = request.GET.get('Page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: pcgame = paginator.page(page) except PageNotAnInteger: pcgame = paginator.page(1) except EmptyPage: pcgame = paginator.page(paginator.num_pages) return render(request,template,contextt) in HTML page : <div class="container"> <div class='row'> {% for pcgame in pcgames %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href=" {{ pcgame.page_url }} "> <img src="{{ pcgame.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3 class="font_control_for_home_page_pc_games_name"><a href=" {{ pcgame.page_url }} ">{{ pcgame.name }}</a></h3> </div> {% endfor %} </div> and in the end of html page i added this {% if pcgame.has_previous %} <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page=1">First</a> <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page={{ pcgame.previous_page_number }}">Previous</a> {% endif %} {% for num in pcgame.paginator.page_range %} {% if pcgame.number == num %} <a class="btn btn-info mb-4" href="?Page={{ num }}">{{ num … -
Django- TypeError... post() missing 1 required positional argument: 'listing_id'
I am still pretty new to Python and Django stackoverflow has really being my strength during this journey. I am working on a Django app where car owner will list their fleet of cars and drivers interested in renting them for Taxi or Uber will make a request to rent the cars… i basically have three models at this point the users(car owners and drivers) car listed by owners(models.Listing), and model.Rent (request being made by drivers to rent a car), i have a listView to list all the car available and a detailView for showing details of each car, i have a button on the detailed view, when clicked by a Driver i want it to take the logged in driver request.user instance and the primary key from the car Listing model on the detailed view and save it in the rent model… But i am getting a “TypeError at /listing/1/ (post() missing 1 required positional argument: 'listing_id’)” Below are my view.py, models.py and error messages: I have read through various similar questions here, some suggested using Listing.id instead of Listing.pk… that resulted into a ValueError. With regards to stackoverflow’s rule, i’ve spent about a week trying out suggestions from … -
Django : python manage.py runserver (multiple errors)
I started using Django recently for my first web app following a tutorial on youtube, every thing went fine until this command : $ python manage.py runserver meaning i was able to create a virtual environment and create a project using : $ python3 -m django startproject <projectname>. Here's what my manage.py looks like: """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_blog.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) execute_from_command_line(sys.argv) if __name__ == '__main__': main() Here are some of my different attempts and errors: $ python manage.py runserver Error: File "manage.py", line 22, in <module> main() File "manage.py", line 14, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Attempt n°1: $ python pip install django Error: python: can't open file 'pip': [Errno 2] No such file or directory $ python -m pip install … -
How do I pass the streamed tweets from the Twitter stream API to a Django view?
I want to display some of my streamed tweets (say 10 tweets) on my Django app once the user hit the refresh button. I have succeed building the Django app and setting up a connection with twitter stream API using Tweepy. However I am still stuck on passing on the streamed tweets from Tweepy code to my view on Django App. I have my Django and Tweepy streaming codes running at the same time. Here what I have tried so far... My streaming code responsible of: on_status fetches the tweets from API and fills a specific number of tweets into a list called tweets. get_tweets returns the tweets list and then empty it so that it can be update once again. >>> Stream.py tweets = [] class TwitterStreamListener(tweepy.StreamListener): def on_status(self, status): global tweets if len(tweets)< 10: print(status.text) tweets.append(status.text) def on_error(self, status_code): if status_code == 403: print("The request is understood, but it has been refused or access is not allowed. Limit is maybe reached") return False # Function to return the retrieved tweets and empty the list so that can be filled once again def get_tweets(): global tweets tweets_copy = tweets.copy() tweets = [] return tweets_copy On the other hand, I … -
UserProfile add Post to Wishlist? error FoodListUser didn't return an HttpResponse object. It returned None instead
I got two related issue I guess. I tried to create a wishlist: When I clic the link to add Post (belongs to the main nutri app) to UserProfile whishlist. I got this : The view user.views.FoodListUser didn't return an HttpResponse object. It returned None instead user/models.py class UserProfile(models.Model): wishlist = models.ManyToManyField(Post, related_name='user_wishlist') ... user/views.py def FoodListUser(request, post_id): post = get_object_or_404(Post, pk=post_id) userprofile = get_object_or_404(UserProfile, user=request.user) if request.method == "POST": userprofile.wishlist.add(post) #request.user.userprofile.follow.add(pk) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_wishlist(self): return self.wishlist.count() user/urls.py path('wishlist/<int:post_id>/', FoodListUser, name="foodlist_user"), -
Django + Uvicorn + Gunicorn: object HttpResponse can't be used in 'await' expression
I'm getting this when running django + uvicorn + gunicorn on every request. It's my first time setting this up and it's not clear where things are going wrong, because runserver works fine. Traceback (most recent call last): File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/whitenoise/middleware.py", line 59, in __call__ response = self.get_response(request) File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/asgiref/sync.py", line 139, in __call__ return call_result.result() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/asgiref/sync.py", line 204, in main_wrap result = await self.awaitable(*args, **kwargs) TypeError: object HttpResponse can't be used in 'await' expression -
Django doesn't render images
WebSite Admin Panel First of all sorry for bad english. But i cant see my images on my website. I can see titles descriptions. Can you help me. I checked page resources it links my images and there is no problem. thats exactly where my photos are page resources settings.py STATIC_URL = '/static/' MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') template <ul class="slides-container"> {% for rs in sliderdata %} <li class="text-center"> <img src="{{ rs.image.url }}" alt=""> <div class="container"> <div class="row"> <div class="col-md-12"> <h1 class="m-b-20"><strong>Hoşgeldiniz <br> Site İsmi</strong></h1> <p class="m-b-40">{{ rs.title}} <br> {{ rs.description }}</p> <p><a class="btn hvr-hover" href="#">İncele</a></p> </div> </div> </div> </li> {% endfor %} views.py def index(request): setting = Setting.objects.get(pk=1) sliderdata = Slider.objects.all()[:3] category = Category.objects.all() context={'setting':setting, 'page': 'home','category':category,'sliderdata':sliderdata} models.py class Slider(models.Model): Status = ( ('True', 'Evet'), ('False', 'Hayır'), ) title = models.CharField(max_length=150) description=models.CharField(max_length=255) image = models.ImageField(upload_to='images/', blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Django creates another media folder inside media folder
I'm a beginner with Django and that's exactly what it does. I do just as it was in the documentation but anyway maybe something went wrong? From admin-page I adding\setting-up a product and choosing the 'image', then when I'm saving it creating a thumbnail and trying to save in '/media/uploads/' but instead it's creating another 'media' folder and the image stored in '/media/media/uploads/img.png' when path on site is '/media/uploads/img.png'. Here is the code: /shop/settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # or even 'media/' /shop/urls.py: urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) after that's added, then in my Product model I do: /apps/store/models.py: class Product(models.Model): ... image = models.ImageField(upload_to='media/uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='media/uploads/', blank=True, null=True) ... def save(self, *args, **kwargs): self.thumbnail = self.make_thumbnail(self.image) super().save(*args, **kwargs) @staticmethod def make_thumbnail(image, size=(512, 512)): if not image: return img = Image.open(image) if img.mode in ('RGBA',): # converting image to RGB if it's RGBA img.load() rgb_convert = Image.new('RGB', img.size, 0) rgb_convert.paste(img, mask=img.split()[3]) img = rgb_convert img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'PNG', quality=80) thumb = File(thumb_io, name=image.name) return thumb I tried to change 'upload_to' to 'uploads/' and then it stores files in the right direction but path to it on-site also changes to … -
Implementing a following system and fetching posts of people a user follows in django
I am designing a social media site and have a model of follower/following system that when a following relationship is made the feed will get all the posts by the followers of the user, I have tried to make the model for my user class and the post class as following: Class User(AbstractBaseUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=30) email = models.EmailField(max_length=30, unique=True) contact_no = models.CharField(max_length=15) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Post(models.Model): posted_by=models.ForeignKey(User,on_delete=models.CASCADE) date= models.DateField(auto_now=True) time=models.TimeField(auto_now=True) content=models.CharField(max_length=2000) media=models.ImageField(blank=True) and this is the model that establishes the relationship between two users. class Following(models.Model): user_id = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user_id= models.ForeignKey(User,related_name='followers',on_delete=models.CASCADE) class Meta: unique_together = ("user_id", "following_user_id") But when I try to combine things while calling upon the posts of the concerned user through this code class Feed(): def __init__(self,User): self.following=Following.objects.filter(user_id=User).values('following_user_id') def GetPosts(self): self.post=Post.objects.filter(posted_by__in=self.following) But this returns me an empty list even after creating the objects, If any of you guys could help me with it in anyway, I would really appreciate it. -
Django API: Revoke tokens after a certain amount of request
I am trying to code an API that would receive a string or a list of strings and return my model's predictions. I use token authentication for the ease of use, however, I don't understand/can't imagine how I can limit the amount of requests a user can make on a per month basis. Or give a limited amount of requests to an anonymous user. Should I create a custom permission class ? ### settings.py ## INSTALLED_APPS = [ # basics 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # API 'rest_framework', 'rest_framework.authtoken', # auth 'rest_framework_tracking', # logging ] ## views.py ## class MyAPIView(APIView, LoggingMixin): logging_methods = ['POST', 'PUT'] authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] renderer_classes = [BrowsableAPIRenderer, JSONRenderer, CSVRenderer] parser_classes = [JSONParser, MultiPartParser] def post(self, request, proba=False): query = request.POST.get('q') content = { 'result': "Model predictions." } return Response(content, status=status.HTTP_200_OK)