Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python code inside django to print current copyright year
If i am writing the below html code to print the current year for my django project it is printing the whole content instead of the year only. ©Copyright xyz {% new "Y" %} Output : ©Copyright xyz {% new "Y" %} -
Deny using non owners Foreign Keys while creating object
I have a model Brand: class Brand(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=25) And I have a Clother: class Clother(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.PROTECT) name = models.CharField(max_length=25) Also I have a regular CreateAPIView. How can I let my User use brands as Foreign Keys only owned by himself? Thanks! -
Django Rest Framework: Without Model
I'm working on creating a RESTAPI using DRF(Django Rest Framework). API just receives the users twitter handle and returns his twitter data. Here, I'm not using model here because it's not required. Should I use a serializer here? If so why? Now I'm able to return the data without using a serializer. Moreover, My API is not web-browsable. How should I make it web-browsable: which is one of the best features of DRF. -
is django compressor default on django install?
Is django compressor default on django install? I have been having an issue with whitenoise and django. I keep getting this error: ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' now all the research I have done points that it may be a whitenoise (im using heroku) and a issue with django compressor. But I do not remember installing such a tech. Is it by default? One of the work arounds suggested is to replace django compressor with another. But how? Actively researching this, if anyone has had this issue before would appreciate a work around. -
Django form data attributes foreign key
I am not able to get the values of foreign key World. I want to use the Language and Population as data attribute in the form. models.py class World(models.Model): country = models.CharField(max_length=200) Language = models.CharField(max_length=200) Population = models.IntegerField() class Traveller(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) Travelling_to = models.ForeignKey(World,on_delete=models.CASCADE) view.py def index(request): form = countries_form() if request.method == 'POST': form = countries_form(request.POST) if form.is_valid(): saved_form = form.save(commit=True) return render(request,'receipt.html',{'upform':saved_form}) else: print("form is not valid") return render(request,'index.html',{'form':form}) index.html <label for="name">name : </label> {{ form.name }}<br> <label for="contact">Address : </label> {{ form.address }}<br> <select class="countries"> {% for li in form.Travelling_to %} <option value="{{ li.country }}" data-Population="{{ li.Population }}" data-Language="{{ li.Language }}">{{ li.country }}</option> {% endfor %} </select> <p>Selected countries Language <span class="selected-lang"></span></p> <p>Selected countries Population <span class="selected-popu"></span></p> jquery $(document).ready(function(){ $(.countries).change(function(){ var selected = $(this).find('option:selected') $('.selected-lang').html(selected.attr("data-Language")) $('.selected-popu').html(selected.attr("data-Population")) }).change() }) -
Django media url including app url
My media URL is showing good in HTML like href="media/Properties/1/scaled_3714427_10513837_VyyZzt3.jpg" but it is not displaying images because when I'm clicking on the image it is being redirected with new URL http://domain/dashboard/media/Properties/1/scaled_3714427_10513837_VyyZzt3.jpg dashboard should not be in URL urlpatterns = [ path('admin/', admin.site.urls), url(r'', include('search.urls')), # url(r'^siteadmin/', admin.site.urls), url(r'^dashboard/', include('search.urls')), url(r'^owner/',include('owner.urls')), # url(r'^scrap/',include('scrap.urls')), url(r'^favicon.ico$', RedirectView.as_view( # the redirecting function url=staticfiles_storage.url('images/fevi_icon_logo.ico'), ), name="favicon" # name of our view ), ] if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
pytest doesn't get my django database
I want to check my objects in my test codes, but failed to get my databases. I checked my databases are exist. I expected result > assert apk == 100 E assert 3 == 100 How can I fix this problem? test_api.py @pytest.mark.django_db def test_get_end_result_count(): apk = Apk.objects.all().count() user = User.objects.all().count() black = Detect_Result.objects.all().count() suspicious = Detect_Result.objects.filter(end_result='suspicious') assert 1 == 1 assert apk == 100 assert user == 1000 assert black == 3 assert list(dict.fromkeys(suspicious)).count() == 2 pytest.ini [pytest] DJANGO_SETTINGS_MODULE = config.settings.local python_files = test_*.py addopts = --reuse-db --nomigrations terminal result ============================== test session starts ============================== platform linux -- Python 3.5.2, pytest-3.6.2, py-1.5.3, pluggy-0.6.0 Django settings: config.settings.local (from ini file) rootdir: /home/inetcop/onvaccine, inifile: pytest.ini plugins: django-3.3.2, celery-4.1.0 collected 2 items onvaccine/api/test_api.py F [ 50%] onvaccine/apks/tests/test_views.py . [100%] =================================== FAILURES ==================================== ___________________________ test_get_end_result_count ___________________________ settings = <pytest_django.fixtures.SettingsWrapper object at 0x7f08e9aaad30> @pytest.mark.django_db def test_get_end_result_count(settings): apk = Apk.objects.all().count() user = User.objects.all().count() black = Detect_Result.objects.all().count() suspicious = Detect_Result.objects.filter(end_result='suspicious') assert 1 == 1 > assert apk == 100 E assert 0 == 100 onvaccine/api/test_api.py:15: AssertionError ====================== 1 failed, 1 passed in 0.53 seconds ======================= -
sum of two variables in django
I am trying to get the sum of 'a' and 'b' and display it with each post. But I am getting the error - 'Count' object has no attribute 'split'. Can someone please help. Thanks def get_queryset(self): a = Count('blogger__posts__title') b = Count('blogger__posts__likes') return (Blog.objects.filter(date__lte=timezone.now()) .order_by('-date') .annotate(score=Sum(F(a)+F(b),output_field=FloatField())) ) -
Django: mulitselect options not prepopulating in html
I'm using django-multiselect. On the html, all of the items are showing, but the ones that are already checked are not showing that they are checked. I was looking at the documentation, but it's coming prechecked. In particular this line of code isn't working: {% if value in checked_role %}checked="checked"{% endif %} Can someone see what I did wrong? html {% for value, text in form.role.field.choices %} <div class="ui slider checkbox"> {{ value }}{{ text }} <input id="id_role_{{ forloop.counter0 }}" name="{{ form.role.name }}" type="checkbox" value="{{ value }}" {% if value in checked_role %}checked="checked"{% endif %}> <label>{{ text }}</label> </div> {% endfor %} models.py aaa= 1 bbb= 2 ccc= 3 ddd= 4 eee= 5 ROLE_CHOICES = ( (aaa, 'AAA'), (bbb, 'BBB'), (ccc, 'CCC'), (ddd, 'DDD'), (eee, 'EEE'), ) class myClass(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) role = MultiSelectField(choices=ROLE_CHOICES, default=True) -
JSON Models Django
Tenho os seguintes Models: class Estado(models.Model): nome = models.CharField('Estado', max_length=30) uf = models.CharField('UF', max_length=2) class Cidade(models.Model): municipio= models.CharField('Municipio', max_length=50) estado = models.ForeignKey(Estado, on_delete=models.DO_NOTHING) Como faço uma fixture .json para eles? Para adicionar os Estados, fiz assim: [{ "model": "comum.estado", "pk": 1, "fields": { "uf": "AC", "nome": "Acre" } }, ...etc... ] Para adicionar as cidades, tentei fazer assim, mas não funcionou: [{ "model": "comum.cidade", "pk": 1, "fields": { "municipio": "Afonso Cláudio", "estado": 8 } }, ...etc... ] O que devo fazer? -
How can I write my own decorator in Django?
My models.py file is as follow: from django.contrib.auth.models import User class Shopkeeper(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # ... class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # ... And I have some views which only Customers can access after login, but Shopkeepers cannot. And vice versa. How can I write decorator for such task? -
Python why does this `in` comparison evaluate False?
I've have a department model that is related to employees by member and manager relationships. A given employee can be both a member and a manager of a department. (Pdb) department.members <myfork.relationship_manager.ZeroOrMore object at 0x111038860> (Pdb) department.managers <myfork.relationship_manager.ZeroOrMore object at 0x111038898> When I look at both models, I can see the same object (Pdb) department.managers[0] <Employee: {'uid': '31a81dd0d89d440fbdace372eede5558'... (Pdb) department.members[0] <Employee: {'uid': '31a81dd0d89d440fbdace372eede5558'... So why is the second statement false? Is it some kind of fingerprint that I can't see? (Pdb) member in department.members True (Pdb) member in department.managers False If I can get it to evaluate as true I can cut a few dozen lines out of my views. -
Serializing a non django model with Django Rest Frame
I am trying to build a django model with DRF that either sends a object state payload after creation, or an error payload. When I try to do something similar, then I get the following error message: File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation self.child.to_representation(item) for item in iterable File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp> self.child.to_representation(item) for item in iterable File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 510, in to_representation fields = self._readable_fields File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 376, in _readable_fields field for field in self.fields.values() File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 997, in get_fields serializer_class=self.__class__.__name__ AssertionError: Class ErrorSerializer missing "Meta" attribute My models are given below: class BaseModel(models.Model, object): # Encapsulates all error objects. errors= [] def add_error(self, error_object): """Appends the error to the list of errors.""" self.errors.append(error_object) class Meta: abstract = True app_label = 'game' class GameRegistration(BaseModel): """Instance of this class represents the user playing the bowling game.""" game_id = models.CharField(max_length=32, help_text='Unique bowling game id', primary_key=True, default=functools.partial(random_string, char_length=16)) # I will set the request.user to set the details later on, but not now. user_name = models.CharField(help_text='unique username', … -
How to order by a django property, or alternative solutions
Ok, so I'm new to django and not sure if I'm approaching this correctly, but here goes: I have a class of incidents, and source of incidents, where you can have multiple sources for a single incident. class Incident(models.Model): iid = models.IntegerField(primary_key=True) person = models.ForeignKey('Person', on_delete=models.SET_NULL, null=True) @property def first_reporteddate(self): return self.source_set.aggregate(first=Min('datereported'))['first'] class Source(models.Model): sid = models.IntegerField(primary_key=True) incident = models.ForeignKey('Incident', on_delete=models.SET_NULL, null=True) url = models.TextField(validators=[URLValidator()]) datereported= models.DateTimeField(null=True, blank=True) When a new incident is created, I want to require that a source is also created. I want to give users the option to sort the Incident model by either the ID, the person, or the earliest incident source datereported. Is it possible to have a model sorted by a property (in this case first_reporteddate), or does it need to be a field? How should I go about structuring this process? -
Django disable trailing slash
I'm using Django 2.0.6 (using the development server for now) and am having issues with automatic trailing slashes being appended to URL's. My goal is to have a URL structure as follows: /teams/ => Index view for all teams /teams/create => Form view to create a new team (note the lack of trailing slash) /teams/xyz/ => Index view for team with slug xyz /teams/xyz/delete => Form view to delete team xyz (require confirmation, etc) The problem is that, somewhere in Django framework, a trailing slash is automatically being appended to 'create' URL's. Because of this, the router the attempts to load the team index page for a team with slug 'create'. Obviously, a workaround would be to stop using slugs and use ID's, but that seems like an unnecessary concession. Looking around, it seems that setting APPEND_SLASH to False should tell CommonMiddleware to stop appending slashes, but this didn't help. Is there a way to easily accomplish my URL scheme and, if not, what's the idiomatic Django way to do this? urls.py: from django.urls import path urlpatterns = [ path('create', views.create, name='create'), path('<slug:team_slug>/', views.view, name='view'), path('<slug:team_slug>/invite/', views.invite, name='invite') ] settings.py: APPEND_SLASH = False MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
How to make django page reload when pressed back button of browser
How to force a page to reload when back button is pressed? I tried some javascript, jquery code but they didn't work. -
SOCIAL_AUTH_LOGIN_ERROR_URL not working Django 2.0.6
I am working in a web app for my organization (lets say 'students.uni' and 'academics.uni') My organization uses Google services so those are google domains and I want to limit the acces to the app only for those domains using 'social_django' I am working with Django 2.0.6 and Python 3.6.5 I am using this to limit the acces to the app, works good: SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['student.uni', 'academics.uni'] Works good when I do log-in or register with an allowed account, but, when the domain of the account is not allowed I want to redirect or send the user to another page to let him know what happened. I have been trying with: SOCIAL_AUTH_LOGIN_ERROR_URL = 'principal' But I can't get it to work since I keep getting either a AuthForbidden exception or a 500 error if I set DEBUG = False Any suggestion on how should I proceed in order to redirect or send a message when the domain is not allowed? Many thanks Some code: Settings.py (not all, but relevant code) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.user', 'apps.inv', 'apps.sol', 'social_django', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for … -
Django Custom Tag - Tag Not Registered
I've referred extensively to some of the great answers at Django: 'current_tags' is not a valid tag library , but can't solve the problem with any permutation of the suggested solutions. Here's the vanilla structure in my project folder: templatetags -> __init__.py -> custom_tags.py I have the line {% load custom_tags %} in my html file, which extends base.html. In settings.py, "project_name" is included in INSTALLED_APPS. Like mif suggests, I try python manage.py shell. Without altering settings, I get ImportError: cannot import name 'custom_tags'. If I add the entry project_name.templatetags.custom_tags to INSTALLED_APPS, then my aforementioned attempt to launch the shell fails with two exceptions: AttributeError: module 'demos.templatetags' has no attribute 'custom_tags', and ModuleNotFoundError: No module named 'demos.templatetags.custom_tags'. custom_tags.py is quite simple: from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter def str_concat(a): return str(a) + " eyy" #register.filter('str_concat', str_concat) I've run the file (with python custom_tags.py) with that last line commented and uncommented. I've also touch 'd both custom_tags and init. I've also relaunched the dev server numerous times (via ctl+c and python manage.py runserver). Also, I've confirmed that the two imports in custom_tags work fine and are successfully installed in the venv. -
Django Rest Framework parsing an array of FormData
Here is my Serializer class. I am hoping to have one to many relationship with UserSerializer to SnapCapsulesSerializer. I have allow for SnapCapsule to be added to UserSerializer, so each User will have access to its snapcapsule. Here is the link I am referencing on creating relational Serializers. http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers class UserSerializer(serializers.HyperlinkedModelSerializer): snapcapsules = SnapCapsuleSerializer( many=True, read_only=True, allow_null=True, ) class Meta: model = User fields = ('snapcapsules', 'url', 'username', 'email', 'password') write_only_fields = ('password',) def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], ) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): assert (validated_data), "No data recieved." for capsule in validated_data.get("snapcapsules", []): snapcapsulea = instance.snapcapsules snapcapsule = SnapCapsule.object.create(user=instance.username, **capsule) snapcapsule.save() snapcapsules.append(snapcapsule) instance.snapcapsules = snapcapsule instance.save() return instance Here is frontend request. For whatever reason, django validatedData is empty when sending sending the request in this format. I believe FormData does know what to do with an Array. (MyForm is a installed FormData class) I tried JSON.stringify(capsule) as well, and it did not work. Can I append an array to 'formdata' in javascript? export default class CapsuleForm extends React.Component { constructor (props) { super(props); this.state = { userUrl: this.props.auth.domain + "/users/" + this.props.userID + "/", dateToPost: moment().add(1, "m"), image: null, caption: "", redirect: … -
Calling user follow/follower list in Django Templates
Hi Djangonauts, I am trying to get the user follows list(example like Instagram 'A' follows 'B') in the templates. I have tried almost everything I am not able to call it in the templates. What am I doing wrong My models (It's a monkey patch to the Django User model) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) … #other profile fields class Contact(models.Model): user_from = models.ForeignKey(User, related_name='supporter') user_to = models.ForeignKey(User, related_name='leader') def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) My views (not sure if this is correct) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) context['follows'] = Contact.objects.filter(user_from__isnull=False, user_from__username__iexact=self.kwargs.get('username')) context['followers'] = Contact.objects.filter(user_to__isnull=False, user_to__username__iexact=self.kwargs.get('username')) return context My Templates {{user}} follows {{user.supporter.count}} members #This works shows the correct number {% for contact in Contact.objects.all %} {{contact.user_to.username}} # I am not able to get this part to work {% endfor %} -
Getting a different set of data every page refresh in Django
I'm looking to get the next x items in a query set in Django every page refresh. Example: x is a list of number's that I use to choose from the query set. As in for i in x: q = Django.objects.filter(name=name)[i] x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I would like to get item's [0, 1, 2, 3, 4, 5]. then on the next page refresh get item's [6, 7, 8, 9, 0, 1]. Notice that the list rolls over from the end to the beginning if there are not 6 more item's. So far I'm getting the length of the Query set then using x % 6 to see if I don't have to modify the list It would also be nice if this is multi user friendly Example of multi user: x is the same as above. When user 1 loads the page they get [0, 1, 2, 3, 4, 5]. Now user 2 loads the page and gets [6, 7, 8, 9, 0, 1]. User 1 now reloads and gets [2, 3, 4, 5, 6, 7] and so on and so forth. -
Populate form from database on given input
I have this form that I want to populate whenever the user does an input on the first field. (it would be even better if there is a search button next to it, and make the query when pressing it) I am generating the form inheriting from ModelForms: class agregarTutorForm(ModelForm): class Meta: model = Tutor exclude = ['fecha_alta'] This is the html code: <div class="container"> <div class="row"> <div class="col"> <form method="post" novalidate>{% csrf_token %} {% include 'common/form_template.html' with form=form %} <button type="submit" class="btn btn-primary">Agregar</button> </form> </div> </div> </div> And here it is the default form_template im using: {% load widget_tweaks %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} … -
AttributeError: module 'foodtaskerapp.apis' has no attribute 'customer_get_meals'
this is the error shows in my terminal AttributeError: module 'foodtaskerapp.apis' has no attribute 'customer_get_meals' i did wright this code in my urls.py *url(r'^api/customer/restaurants/$', apis.customer_get_restaurants), url(r'^api/customer/meals/(?P<restaurant_id>\d+)/$', apis.customer_get_meals), url(r'^api/customer/order/add/$', apis.customer_add_order), url(r'^api/customer/order/latest/$', apis.customer_get_latest_order),* and this how i defined it in apis.py def customer_get_meals(request, restaurant_id): meals = MealSerializer( Meal.objects.filter(restaurant_id = restaurant_id).order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"meals: meals"}) -
Django dynamicaly add field from dictionary value
I'm trying to refactor some code to be DRY I have an importer that imports from an API that has keys that are different than the destination. Working code look like this this_event = AnEvent() wp_event = Requests.get('someurl').json() if 'title' in wp_event.keys(): this_event.title = wp_event['title'] if 'description' in wp_event.keys(): this_event.description = wp_event['description'] ... and so on What I am trying to do is this scrape_fields = [ { 'wp' : 'description', 'django' : 'description' }, { 'wp' : 'title', 'django' : 'name' } ... etc ] for field in scrape_fields: if field['wp'] in wp_event.keys(): # I knew this would not work when I wrote it but not sure what to do this_event[field['django']] = wp_event[field['wp']] But Django throws an exception 'AnEvent' object does not support item assignment Any one able to advise on how to assign to a field dynamically like this? -
How to use redis to cache the list of relevant articles as values mapped with the articles' id as key in django?
models.py from django.db import models from django_pandas.managers import DataFrameManager # Create your models here. class BcContent(models.Model): asset_id = models.PositiveIntegerField() title = models.CharField(max_length=255) alias = models.CharField(max_length=255) title_alias = models.CharField(max_length=255) introtext = models.TextField() state = models.IntegerField() sponsored = models.IntegerField() sectionid = models.PositiveIntegerField() mask = models.PositiveIntegerField() catid = models.PositiveIntegerField() created = models.DateTimeField() created_by = models.PositiveIntegerField() created_by_alias = models.CharField(max_length=255) modified = models.DateTimeField() modified_by = models.PositiveIntegerField() checked_out = models.PositiveIntegerField() checked_out_time = models.DateTimeField() publish_up = models.DateTimeField() publish_down = models.DateTimeField() images = models.TextField() urls = models.TextField() attribs = models.CharField(max_length=5120) version = models.PositiveIntegerField() parentid = models.PositiveIntegerField() ordering = models.IntegerField() metakey = models.TextField() metadesc = models.TextField() access = models.PositiveIntegerField() hits = models.PositiveIntegerField() metadata = models.TextField() featured = models.PositiveIntegerField() language = models.CharField(max_length=7) xreference = models.CharField(max_length=50) admin_push = models.IntegerField() author_id = models.PositiveIntegerField(blank=True, null=True) meta_title = models.CharField(max_length=255) og_title = models.CharField(max_length=255) og_description = models.TextField() lifestage_period = models.CharField(max_length=255) fb_post_id = models.CharField(max_length=255) is_instant_article = models.IntegerField() instant_article_text = models.TextField() objects = DataFrameManager() class Meta: managed = False db_table = 'bc_content' Views.py from django.shortcuts import HttpResponse from .models import BcContent import os import re from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords stop = set(stopwords.words('english')) import functools from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english", ignore_stopwords =True) from django.conf import settings from rest_framework.decorators import api_view from rest_framework.response …