Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL parameters vs query parameters in Django
I've looked around for a little while now and can't seem to find anything that even touches on the differences. As the title states, I'm trying to find out what difference getting your data via url path parameters like /content/7 then using regex in your urls.py, and getting them from query params like /content?num=7 using request.GET.get() actually makes. What are the pros and cons of each, and are there any scenarios where one would clearly be a better choice than the other? Also, from what I can tell, the (Django's) preferred method seems to be using url path params with regex. Is there any reason for this, other than potentially cleaner URLs? Any additional information pertinent to the topic is welcome. -
Django 1.8 - generic class GenericRelation?
I know that: import django.contrib.contenttypes import generic is no longer working in Django 1.8, so what would be the replacement of: identifier = generic.GenericRelation('Identifier')? -
Initializing Django data on Angular front-end
How do I connect the data from my Django model to my Angular scope? I've seen several answers but none seem to be perfect: Most answers say my django view should only take care of loading the template and omit the model data, which can instead be retrieved and filled in by the frontend with http requests, thus "moving the work load to the client's browser" I fail to see how that is better than just having the server render the data into the page? The server still ends up responding to the REST call with all the data so why not just pass it while the rest of the page is being sent? The way i see it my server has to send two HTTP responses instead of one in this case. Django view could include unique element ID's on the elements so they can be accessed using DOM selectors such as angular.element or jqLite, etc. Yet it is often warned that angular controllers shouldn't be accessing the DOM, instead use angular directives. This kind of makes sense but if I have a page with many similar elements (like a forum with many comments), I don't see how directives … -
Django: need to send list of states along with companies within those, and their photos to a template. Struggling
So in the template there are two for loops: -for state in states -for partner in state.partners along with these variables which will be outputted to the template: {{state.display}} {{partner_img}} {{partner}} I'd really appreciate any feedback! Sorry i'm a relatively new programmer, so I apologize if this is a noob question. def partner(): """Show partner name/logo in their state""" # use a namedtuple for each company from collections import namedtuple Partner = namedtuple('Partner', company_name) foo = Partner(mls_name='balh') foo.mls_name bar = {'alabama': {}, 'maine': {}, 'north_carolina': {}, 'alabama' : {}, 'arizona' : {}, 'california' : {}, 'colorado' : {}, 'florida' : {}, 'georgia' : {}, 'iowa' : {}, 'illinois' : {}, 'indiana' : {}, 'louisiana' : {}, 'maine' : {}, 'michigan' : {}, 'missouri' : {}, 'mississippi' : {}, 'montana' : {}, 'north_carolina' : {}, 'new_jersey' : {}, 'nevada' : {}, 'new_york' : {}, 'ohio' : {}, 'oklahoma' : {}, 'pennsylvania' : {}, 'rhode_island' : {}, 'south_carolina' : {}, 'tennessee' : {}, 'texas' : {}, 'virginia' : {}, 'west_virginia' : {}, 'wisconsin' : {}, 'canada' : {}, } state1 = {name, index_name, partners} state_list = [state1, state2] -
How to point a HyperlinkedRelatedField at a view under a namespace
I have created an url which is in a router.register, and in my serializer I'm using a HyperlinkedRelatedFieldwhen I have write the view_name, it gives me an error here is mi code: My serializer.py class OptionHyperSerializer(HyperlinkedModelSerializer): game = HyperlinkedRelatedField( view_name="api:game-details", lookup_field = "id", many=False, read_only=True ) class Meta: model = Option fields = ('id','title','image','position','game') urls.py router = DefaultRouter() //This is the url that I want router.register(r'game', views.GameListDetails, base_name="game-details") urlpatterns = [ url(r'^option/$', views.OptionList.as_view(), name="option_list"), url(r'^option/(?P<id>\d+)/$', views.OptionList.as_view(), name="option"), #url(r'^game/(?P<id>\d+)/$',views.GameDetails.as_view(), name="game"), url(r'^schedule/$',views.ScheduleList.as_view()), url(r'^', include(router.urls), name="api") ] So how can I set in the HyperlinkedRelatedField the ´view_name´ when my view would be router.register(r'game', views.GameListDetails, base_name="game-details") which is called in url(r'^', include(router.urls), name="api") Note:I have seen in the documentation that supposed to be ´view_name:apigame-details´ the namespace of the inclide url and the ase name of the register bu it does not work -
Django: Excluding objects from Same Model
Here's my code, objects = Games.objects.filter(...)[:5] items = Games.objects.exclude("Exclude all 5 "GAMES" contained in variable 'objects') How can I do that? -
Django Rest Framework SearchFilter - no filtering or search control in API
The docs for Django Rest Framework's SearchFilter are clear, so I must be missing something simple. I have the following code, but no searchable API - the search controls do not appear in the browsable API, and requests appended with ?search= are not filtered: views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() #django.contrib.auth.models.user serializer_class = UserSerializer filter_backends = (rest_framework.filters.SearchFilter,) search_fields = ('username', 'email') serializers.py class UserSerializer(serializers.HyperLinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'id', 'email') I have tried supplying a list to search_fields rather than a tuple, and I have tried removing the viewset-specific filter_backends argument and providing a default in settings.py. The example in the docs shows this SearchFilter being used with a generic ListAPIView rather than a ModelViewSet as I am doing. Maybe I am missing something because of that, but I can't think what it might be. How can I make my ModelViewSet work with SearchFilter? -
ListView making queryset based on parameter
I've a ListView which is making a list of items, say, products. And i want to conditionally change this queryset by sending a parameter from template. Say i want to filter something on supplier_id or something else like date. Should i create a new view for each situation or extending the base ListView changin only my queryset depending on condition or i should use only one ListView and process each situation depending on passing argument, so class ProductListView(ListView): ... def get_queryset(self): return Supplier.objects.all() class ProductBySupplierListView(ProductListView): def get_queryset(self): return Supplier.objects.filter(supplier=self.kwargs['sup']) or class ProductListView(ListView): ... def get_queryset(self): if self.kwargs['sup']: return Supplier.objects.filter(supplier=sup) else: return Supplier.objects.all().annotate(prd_cnt=Count('product')) Or there may be some better pattern for handling multiple conditions sorting problems. -
Django first app
I have some problems with my first django app (its name is magghy). I'm at the start of development. So, I have: magghy/urls.py: from django.conf.urls import * from magghy import views from . import views app_name = 'magghy' urlpatterns = [ # esempio: /magghy/ url(r'^$', views.index, name='index'), #esempio: /magghy/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex: /magghy/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex: /magghy/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] In magghy/views.py: from __future__ import unicode_literals from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from .models import Choice, Question from django.template import loader from django.urls import reverse #visualizzare domande e argomento specifico - collegare con modulo magghy.urls def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) #visualizzare pagina html secondo schema index.html oppure html 404 (eccezione) def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('magghy/index.html') context = RequestContext (request, { 'latest_question_list': latest_question_list, }) return HttpResponse(template.render(context)) #visualizzare pagina 404 def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) In mysite/urls.py: from django.conf.urls import * from … -
Why is this regex code not working
Working on a Django app Here's my urls.py urlpattterns = [url(r'^(?P<leagueId>[0-9]+)/(?P<year>[0-9]+)/(?P<team>[\S]+)/$', views.team_detail, name="team_detail"),] An example url would be along the lines of: http://localhost:8000/123456/2017/Johnny%20Rocket/ I tried playing around with Pythex, but I couldn't get the urls to match Note: The variables passed are /{number}/{year}/{name} The name can consist of alphanumeric characters and whitespaces. -
Django - CSRF verification failed - send data from form on static website to my django app
My setup: A static website as landing page served via aws S3 (welcome.mydomain.com). A django app (django-1.8 with python 2.7) accessible via a subdomain (app.mydomain.com). I would like to add a contact form which is part of my static website and which sends the contact form info to my django server to be processed. I do not want to add the contact form as a template to my django app because I am using different style sheets and resources and don't want to mix them between the servers. The view processing the form data is just adding this data to an email and sending this to an internal email address. I get a 403 csrf verification failed error because the form does not include the csrf token. I could now exempt the view receiving the request from the csrf verification but I am not sure which security risks this poses. I am not sure if I am not understanding the csrf attacks and dangers or if I am looking at this problem the wrong way. All my searches and all the answers to django-csrf related questions have not helped me so far. Here are my questions: Is there a better … -
DRF JWT Don't require token on OPTIONS-requests
How can you make JWT not check and require a token when user does an OPTIONS-request? I have defined my own options(self, request, *args, **kwargs) method, but as long as the permission_classes = [isAuthenticated] is enabled, the user is asked to provide login credentials... The API we are using in React to interact with DRF has to do an OPTION-request, which does not contain any headers. When it does not get a 200 code back, it does not perform the actual request to the server... -
Different thing is shown in html
I wanna show most newest value of test_date User model. I wrote in views.py @login_required def test(request): test_score = User.objects.filter(user=request.user).order_by('test_date')[0] return render(request, 'test.html',{'test_score': test_score}) in models.py class User(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") test_date = models.IntegerField(max_length=100,null=True) score = models.IntegerField(max_length=100,null=True) in test.html <h3>Your score is <h2 class="one"> {{ test_score.score }} </h2> </h3> If test day is 2017/03/03,20170303 is registed in test_date of User.And test score is registed in score(for example,if score is 60,60 is registed) The kind of data of user・test_date・score is many in same user.For example,the data is Tom 20170809 60 Tom 20170810 100 Tom 20171010 30 in that case test.html is <h3>Your score is <h2 class="one">30</h2> </h3> But now,test.html is <h3>Your score is <h2 class="one">60</h2> </h3> 60 is first registed data ,so current my system shows it .I think test_score = User.objects.filter(user=request.user).order_by('test_date')[0] get most newest (biggest) data Tom 20170810 100 because of Django document.What is wrong in my code?How should I fix this? -
AWS Elastic Beanstalk - separate configurations for different environments
I am using Amazon Web Services (AWS) Elastic Beanstalk for hosting my Django/Python web application. I have two environments created in Beanstalk - production and acceptance (staging). My web app source code is in version control in git. Deployment config files are located in the .ebextensions directory at the root of git repository, as described here. I have 2 separate Django config files for my application: conf/acceptance.py and conf/production.py. How do I set DJANGO_SETTINGS_CONFIG environment variable separately for each environment. I have tried editing it in beanstalk web ui, but it is resets when I redeploy. What can I do? -
django Can't use Max and Count the same field in back-to-back annotations
I would like to count the number of max deployment__release_id per device_id. I have the following: release_breakdown = DeviceDeployment.objects \ .values('device_id') \ .annotate(release_id=Max('deployment__release_id')) \ .values('release_id') and it gives me what I expect which is a query set list: <QuerySet [{'release_id': 352}, {'release_id': 352}, {'release_id': 352}, {'release_id': 352}, {'release_id': 352}, {'release_id': 352}, {'release_id': 352}, {'release_id': 351}, {'release_id': 351}, {'release_id': 352}]> How ever when I want to get the count of the above with: release_breakdown = DeviceDeployment.objects \ .values('device_id') \ .annotate(release_id=Max('deployment__release_id')) \ .values('release_id') .annotate(rcount=Count('release_id')) I get the following error: Cannot compute Count('release_id'): 'release_id' is an aggregate What I want is <QuerySet [{'release_id': 352, 'rcount': 7}, {'release_id': 351, 'rcount': 2}]> How can I get this -
How to weigh the data queryset count for paging policy?
I have a User model that has 20 count field: class User(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=40) # sha1 real_name = models.CharField(max_length=12, null=True,blank=True) phone = models.CharField( max_length=11) email = models.EmailField(blank=True, null=True ) qq = models.CharField(max_length=10, null=True, blank=True) address = models.CharField(max_length=64, blank=True, null=True) id_card = models.CharField(blank=True, null=True, max_length=18, validators=[RegexValidator(regex='^.{18}$', message='身份证长度必须为18', code='nomatch')]) id_card_img_front = models.CharField(max_length=256, blank=True, null=True) id_card_img_back = models.CharField(max_length=256, blank=True, null=True) nickname = models.CharField(max_length=16, blank=True, null=True) profile = models.CharField(max_length=256, blank=True, null=True, default=' ') usertype = models.ForeignKey(to='UserType', default=1, blank=True) user_c_type = models.CharField(max_length=4, null=True) fixed_phone = models.CharField(max_length=16, null=True) fax = models.CharField(max_length=16, null=True) main_bussiness = models.CharField(max_length=16, null=True) main_industry = models.CharField(max_length=16, null=True) company_name = models.CharField(max_length=32, null=True) company_address = models.CharField(max_length=32, null=True) province = models.CharField(max_length=32, null=True, default="--省--") town = models.CharField(max_length=32, null=True, default="--市--") # 省市县 country_level = models.CharField(max_length=32, null=True, default="--县--") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, null=True, default=1) And in my Django project, I want to use Paginator to realize paging for user list. Because the count of my user in my database is no more than 10,000 rows. So, whether I can get all of the user in my database then paginate them? user_all = models.User.objects.all() paginator = Paginator(user_all, 10) try: user_list_page = paginator.page(page_number) except PageNotAnInteger: user_list_page = paginator.page(1) except EmptyPage: user_list_page = … -
Python URL command export to .xlsx file
I have one command that gives all urls of my project. And i want to export this command to xlsx file. Any ideas? In print message should be url command Thanks guys in advance. urls.py (Here command that gives all urls) from django.conf.urls import RegexURLPattern, RegexURLResolver from django.core import urlresolvers from django.core.management import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **kwargs): urls = urlresolvers.get_resolver() all_urls = list() def func_for_sorting(i): if i.name is None: i.name = '' return i.name def show_urls(urls): for url in urls.url_patterns: if isinstance(url, RegexURLResolver): show_urls(url) elif isinstance(url, RegexURLPattern): all_urls.append(url) show_urls(urls) all_urls.sort(key=func_for_sorting, reverse=False) print('Total urls:', len(all_urls)) print('-' * 220) for url in all_urls: print('| {0.regex.pattern:100} | {0.name:50} | {0.lookup_str:70} |'.format(url)) print('-' * 220) export_test.py (Export command) import xlsxwriter # Create a workbook and add a worksheet workbook = xlsxwriter.Workbook('Test2.xlsx') worksheet = workbook.add_worksheet() # Add a bold format bold = workbook.add_format({'bold': True}) # Write header worksheet.write('A1', 'URL', bold) worksheet.write('B1', 'Class', bold) expanses = ( ['TestUrl.com', 'TestClass'], ['TestUrl2.com', 'ExcelClass'], ['TestUrl3.com', 'OrderClass'], ['TestUrl4.com', 'TransferClass'], ) row = 1 col = 0 for item, cost in (expanses): worksheet.write(row, col, item) worksheet.write(row, col + 1, cost) row += 1 workbook.close() I think it should be in print message -
Ajax filter in django not showing in HTML
I'm not sure if my Ajax implementation is right. Using Django built in tags, the objects I am passing using Ajax is not showing up on my template HTML page. view_results.html <div> <input id="search" name="search" type="text" class="query-search form-control input-sm" style="width:350px;" placeholder="Search route name..."> </div> <div class="overflow"> <div class="list-group"> {% if results|length %} {% for r in results %} <a href="#" class="list-group-item"><strong>{{ r.route_id }}</strong> <br> {{ r.route_long }}</a> {% endfor %} {% else %} Not found {% endif %} </div> </div> Javascript $(function() { $('#search').keyup(function() { $.ajax({ type: "GET", url: "/search/get_routes/", data: { 'search_text' : $('#search').val() }, success: function(data){console.log(data)}, dataType: 'html' }); }); }); views.py def trails_view(request): trails = Trail.objects.all() trails_json = serialize('geojson' , trails, fields=('trails_type', 'trails_id', 'wkb_geometry',)) trails_geojson = json.loads(trails_json) trails_geojson.pop('crs', None) trails_geojson = json.dumps(trails_geojson) return render(request, '/view_trails.html', {'trails':trails, 'trails_geojson':trails_geojson}) def get_trails(request): if request.method == "GET": search_text = request.GET['search_text'] if search_text is not None and search_text != u"": search_text = request.GET['search_text'] results = Trail.objects.filter(trails_id__contains=search_text) else: results = [] return render(request, '/view_trails.html', {'results': results}) urls.py url(r'^view/', views.routes_view, name='routes_view'), url(r'^search/get_routes/', views.get_routes, name='get_routes'), I am wondering if trails_view and get_trails is the reason of the function not showing up the results upon ajax call. I tried printing out the contents of results in … -
How can I set path to load data from CSV file into PostgreSQL database in Docker container?
I would like to load data from CSV file into PostgreSQL database in Docker. I run: docker exec -ti my project_db_1 psql -U postgres Then I select my database: \c myDatabase Now I try to load data from myfile.csv which is in the main directory of the Django project into backend_data table: \copy backend_data (t, sth1, sth2) FROM 'myfile.csv' CSV HEADER; However I get error: myfile.csv: No such file or directory It seems to me that I tried every possible path and nothing works. Any ideas how can I solve it? This is my docker-compose.yml: version: '3' services: db: image: postgres environment: POSTGRES_USER: myuser POSTGRES_PASSWORD: mypassword django: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
I noticed that this Django Rest Framework commit broke my project when upgrading from 3.6.3 to 3.7.0. Here's the relevant part of the model that is now broken: class MarketingPlan(models.Model): promotion = models.ForeignKey(Promotion, null=True) class MarketingPlanSerializer(serializers.ModelSerializer): promotion = serializers.CharField( source='fk_promotion.id', read_only=False, allow_null=True) class Meta: model = MarketingPlan fields = ('promotion',) Accessing the data attribute of this serializer, when the Promotion foreign key is None >> mp = MarketingPlan.objects.first() >> MarketingPlanSerializer(mp).data rest_framework/fields.py", line 100, in get_attribute instance = getattr(instance, attr) AttributeError: 'NoneType' object has no attribute 'id' So whereas get_attribute used to skip None, now it goes searching for the .id attribute of the related field promotion in my particular case, even when it's None. What's the workaround for this? -
django smart select like selects with two models
I have models like below class ResultModule(models.Model): exp = models.ForeignKey(ResultExperiment) coupling_name = models.CharField(max_length=150) module_name = models.CharField(max_length=150) class ResultParam(models.Model): module = models.ForeignKey(ResultModule) param_name = models.CharField(max_length=100) param_value = models.CharField(max_length=50) View like below class SearchResults(View): form = SearchResults template_name = 'search_results.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, { 'form': self.form }) def post(self, request, *args, **kwargs): return render(request, self.template_name, { 'form' : self.form(request.POST) }) and a model form like class SearchResults(forms.ModelForm): class Meta: model = models.ResultParam fields = ('module', 'param_name', 'param_value') I am trying to implement django-smart-select like functionality, I tried using django-smart-select but could not get the data filled in module field. class ResultParam(models.Model): module = ChainedForeignKey( ResultModule, chained_field = 'module', chained_model_field = 'module_name', show_all = False ) param_name = models.CharField(max_length=100) param_value = models.CharField(max_length=50) Does my models above match requirements to use django-smart-select? If yes, what am I doing wrong in my code above? If on, what will you suggest me to do to have selects like django-smart-select? -
Django on Production doesn't display all fields of my Models in Django Admin
I'm working on a Django 1.10 & Python 3.6 project, I have deployed it on compute engine successfully with gunicorn.My project is working fine but I have one issue there, I have two models as "Articles" & "TaggedArticle", I have specified all fields from TaggedArticle in admin.py but it doesn't display in Django admin, rather it's displaying all fields in Django admin on my local system. After deployment now I'm using Postgresql instead of SQLite. Here are my models: Article Model: class Article(models.Model): link = models.URLField(max_length=255) category = models.CharField(max_length=255, choices=Categories) TaggedArticle Model: class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) Here's my admin.py for TaggedArticle: User = get_user_model() admin.site.unregister(User) class InlineTaggedArticle(admin.TabularInline): model = TaggedArticle class CustomAdmin(UserAdmin): date_hierarchy = 'date_joined' inlines = [InlineTaggedArticle, ] list_display = list(UserAdmin.list_display) + ['totol_tagged_article'] def totol_tagged_article(self, obj): return obj.tagging.all().count() admin.site.register(User, CustomAdmin) class TaggedArticleAdmin(admin.ModelAdmin): date_hierarchy = 'created_at' fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email'] list_display = ['link', 'user', 'email'] list_filter = ['user', 'email'] model = Tagged admin.site.register(Tagged, TaggedArticleAdmin) Only category_fit & article fields are displaying in Django admin, why other fields don't display … -
Django modelforms, foreignkey filter for data owned by logged in user
I have a model for which I have created a Model form: class StoreDepartment(models.Model): store = models.ForeignKey(Store, verbose_name='Store') department_name = models.CharField(max_length=200, null=False, verbose_name='Department name') department_description = models.TextField(max_length=250, null=False, verbose_name='Description') archive = models.BooleanField(default=False) class StoreDepartmentCreateForm(forms.ModelForm): class Meta: model = StoreDepartment exclude = ['id',] store = forms.ModelChoiceField(queryset=Store.objects.all()) department_name = forms.CharField(label="Name", required=True) department_description = forms.CharField(widget=forms.Textarea,label="Description") The queryset = Store.objects.all() returns all the stores in the system. How to use a filter to get Store data only owned by the current logged in user. -
Django database queries per view in APIs
So I have been developing a Django server application that mostly works as an API endpoint for a mobile app, with about 30 different models, almost all of them having FKs to each other or other or being in MTM relationships. Now that we're going into production (but do not yet have a lot of users), I have noticed (using Silk) that the most complex query that fetches a bunch of objects as JSON makes about 500 SQL queries (and those objects each have about 5 FKs and 2 MTMs, which are all fetched as object fields in the JSON). The numbers don't seem to be too huge (as 50k qps seems to be a normal number for Postgres, which we are using as our DBMS), but I am getting worried about the future. Are those numbers normal in early production? What is the normal distribution of database requests per view for an API like the one I described? We are not currently using DRF, but I am looking towards it. Does it solve this problem? -
Like Button In Django Ajax
my like button is working fine without ajax with page reloading but it is having problem when done by implementing ajax. the like and unlike is happening in the backend (like is created and deleted in database on ajax Post request), but the like count,like,unlike button does not change in response on ajax post request, until the page is reloaded. Need Help here is the post model and like model for posting image and liking it in models.py class PostModel(models.Model): user = models.ForeignKey(UserModel) image = models.FileField(upload_to='user_images') image_url = models.CharField(max_length=255) caption = models.CharField(max_length=240) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) has_liked = False @property def like_count(self): return len(LikeModel.objects.filter(post=self)) class LikeModel(models.Model): user = models.ForeignKey(UserModel) post = models.ForeignKey(PostModel) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) url for liking in urls.py url(r'^like/', like_view), views.py def like_view(request): user = check_validation(request) if user and request.method == 'POST': form = LikeForm(request.POST) if form.is_valid(): #post_id = form.cleaned_data.get('post').id post_id=request.POST['post'] existing_like = LikeModel.objects.filter(post_id=post_id, user=user).first() if not existing_like: LikeModel.objects.create(post_id=post_id, user=user) else: existing_like.delete() return redirect('/feed/') else: return redirect('/login/') template.html {% for post in posts %} <form id="like_form"> {% csrf_token %} <input type="hidden" name="post" id="post_id"value="{{ post.id }}"> {% if post.has_liked %} <button class="btn btn-link unlike"type="submit"><i class="fa fa-heart" aria-hidden="true"style="color:#ed4956;"></i></button> {% else %} <button class="btn btn-link like"type="submit"><i …