Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 Logging - custom app logger isn't used
I have this app structure app/ customApp/ urls.py app/ settings.py manage.py In settings.py this is my logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'ERROR', }, 'customApp': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, } } I am trying to trigger the customApp logger in customApp.urls like this: from django.urls import path from django.http import HttpResponse from logging import getLogger logger = getLogger(__name__) def make_response(request): # if handler is set to console, print result is ALWAYS logged # this is the logging level hierarchy debug < info < warning < error logger.debug(f'DEBUG logged in {__name__}') logger.info(f'INFO logged in {__name__}') logger.warning(f'WARNING logged in {__name__}') logger.error(f'ERROR logged in {__name__}') return HttpResponse('<h1>Ok!</h1>') urlpatterns = [ path('', make_response) ] When running the django app and going to this path is using the root logger, logging only the ERROR. ERROR logged in customApp.urls Why isn't my customApp logger being used? -
How to set success_url to redirect back to a model that is different from the one referenced in UpdateView?
# models.py class Address(models.Model): address = models.TextField() class Doctor(models.Model): locations = models.ManyToManyField(Address) class Patient(models.Model): locations = models.ManyToManyField(Address) # views.py class PatientDetailView(DetailView): model = Patient class DoctorDetailView(DetailView): model = Doctor class DoctorUpdateView(UpdateView): model = Doctor fields = ['locations'] class AddressUpdateView(UpdateView): model = Address fields = ['address'] I want to be able to go to AddressUpdateView from DoctorDetaillView or PatientDetailView, then be able to return back to DDV or PDV depending on whose view I was in. I am able to route to AddressUpdateView from DDV/PDV by using the following: # detailview1 {% for address in object.address.all %} <a href="{% url 'address-update' address.id %}">Update Address</a> {% endfor %} I've tried # detailview1 <a href="{% url 'address_update' adress.id %}?next={% url 'doctor_detail' object.id %}">Update Address</a> but this url query parameter itself does not work. It just doesn't take me back to the doctor_detail url. I know I need to add a success_url, reverse, or something in the manner but I just can't figure it out. I can't explicitly put get_success_url to return back to Doctor because if it was an address update for a Patient, I don't want it going back to DoctorView, and vise versa. Does anyone know how I can get back … -
Django app works fine locally, but fails in heroku when logging into admin sit
class UserProfile(AbstractBaseUser,PermissionsMixin): #email=models.EmailField(max_length=40,unique=True) phone=models.CharField(max_length=10,unique=True,) name=models.CharField(max_length=30) is_volunteer=models.BooleanField() district=models.CharField(max_length=30,null=True) areaofvol=models.CharField(max_length=40,null=True) address=models.CharField(max_length=200,null=True) lat=models.DecimalField(max_digits=9,decimal_places=6) lon=models.DecimalField(max_digits=9,decimal_places=6) is_staff=models.BooleanField(default=False,blank=True,null=True) REQUIRED_FIELDS=['lat','lon','is_volunteer'] USERNAME_FIELD ='phone' objects=UserProfileManager() def __str__(self): return self.name The app works locally and I also checked the db.sqlite3 file in heroku bash it had is_staff inside flood_userprofile. -
Problem running Celery in ubuntu 18.04 with Supervisor and Django
I've set up Supervisor to run some Celery scheduled tasks, but this tasks are never executed. I don't know if I have a bad configuration or if I am missing something to configure. According to my supervisor status all is ok: sudo supervisorctl status my_app -> my_app RUNNING pid 16757, uptime 0:00:04 What i have Celery app configuration from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") app = Celery("myproject") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { "add-two-numbers": {"task": "myproject.myapp.tasks.add", "schedule": 30.0} } Supervisor configuration [program:my_app_celery] user=root directory=/var/www/my_django_app/ command=/var/www/my_django_app/venv/bin/celery -A config beat -l info autostart=true autorestart=true stdout_logfile=/var/log/my_project/celery.log stderr_logfile=/var/log/my_project/celery.err.log Celery task # Some Django app task from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y Celery log [2020-07-24 21:40:21,168: INFO/MainProcess] Scheduler: Sending due task add-two-numbers (my_project.my_app.tasks.add) Django celery setting CELERY_BROKER_URL='redis://localhost:6379' CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_TIME_LIMIT = 5 * 60 CELERY_TASK_SOFT_TIME_LIMIT = 60 Environment Ubuntu 18.04 redis-server v=4.0.9 celery==4.4.6 django==3.0.8 python 3.8 -
How to properly set Facebook Sharing Link Thumbnail and Text
I am trying to add a Facebook Sharing Link to my blog post detail page. So It is currently working but I have a question which didn't find an accurate answer to: How to set the thumbnail and text after I press the sharing button on the popup page? Here is the HTML <!-- Sharingbutton Facebook --> <a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"> Share on Facebook </a> -
Deploying Django to AWS
just wondering if you ever had an issue when trying to deploy a Django application to Elastic Stalk beans AWS. I finally was able to follow all the steps to get to this point. enter image description here 22:16 when I check my AWS account nothing gets created there and when I do be open..... I get 404 error -
How to filter a list of posts based on category
Hi I'm pretty new to django. I'm building my first web app and I've hit a bit of a snag. I have a template that shows a paginated list of posts. I have a side bar which also dynamically populates a list of post categories: {% for cat in category_count %} <div class="item d-flex justify-content-between"> <a href="#">{{ cat.categories__title }}</a> <span>{{ cat.categories__title__count }}</span> </div> {% endfor %} I would like to be able to click one of these categories and then display a filtered list of the posts by category. Categories are a Many to Many field of Posts. class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() content = HTMLField() previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) My idea was to create a url for 'category/' and have that display the filtered list, but I don't know how to set it up so that I can get the user's selected category from the request. Any ideas? NOTE: If there's a better way to handle this that any of you have come across I'm completely open to it. Thanks in … -
Django Model Form not showing errors after validation in clean()
Can you help me out with this. I hava a model form and I need to raise an error after validate two datetime objects in the clean method of the model form. This is what I have. Forms class HorariosDisponibles(forms.ModelForm): tutor = forms.ModelChoiceField(queryset=Tutor.objects.all(),widget=forms.Select(attrs= {'class': 'input is-small is-rounded ' }),label='TUTOR',) dia_hor_inicio =forms.DateTimeField(widget=forms.DateTimeInput(attrs= {'class': 'input is-small is-rounded ',}),label='Horario de Inicio', initial=datetime.date.today ) dia_hor_fin= forms.DateTimeField(widget=forms.DateTimeInput(attrs= {'class': 'input is-small is-rounded ' }),label='Horario de Finalización', initial=datetime.date.today) class Meta: model = horarios_disp fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["dia_hor_inicio"].widget = DateTimeInput() self.fields["dia_hor_inicio"].input_formats = ["%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M"] self.fields["dia_hor_fin"].widget = DateTimeInput() self.fields["dia_hor_fin"].input_formats = ["%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M"] def clean(self): cleaned_data = super(HorariosDisponibles, self).clean() tutor = cleaned_data.get("tutor") dia_hor_inicio = cleaned_data.get("dia_hor_inicio") dia_hor_fin = cleaned_data.get("dia_hor_fin") if dia_hor_inicio and dia_hor_fin: if dia_hor_inicio.day != dia_hor_fin.day : msg = 'Las fechas no pueden ser distintas' self.add_error("dia_hor_inicio", msg) raise forms.ValidationError("Las fechas no pueden ser distintas") #NEITHER OF THIS APPROACHES WORKED return cleaned_data VIEWS @login_required def horario_tutor(request): context = { } if request.method == 'POST': print(request.POST) form = HorariosDisponibles(request.POST) if form.is_valid(): tutor = form.cleaned_data['tutor'] print("adentro") dia_hor_inicio = form.cleaned_data['dia_hor_inicio'] dia_hor_fin = form.cleaned_data['dia_hor_fin'] tutor_horario = horarios_disp( tutor=tutor, dia_hor_inicio=dia_hor_inicio, dia_hor_fin=dia_hor_fin) tutor_horario.save() context = { 'form': form } return redirect("home") return render(request,"horarios_disponibles.html", context) else: form = HorariosDisponibles() context['form'] … -
ValueError at /register/ Users must have an email address
This is my code in views.py if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") new_user = User.objects.create_user(username, email, password) Here is what is printed from the line 'print(form.cleaned_data)' {'full_name': 'Ross', 'email': 'tree34-5@hotmail.com', 'profilepicture': None, 'password1': 'tree', 'password2': 'tree'} Here is my code from models.py class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_active=True, is_staff=False, is_admin=False): print(email) if not email: raise ValueError("Users must have an email address") 'print(email)' returns None. I don't understand why 'print(email)' is not returning tree34-5@hotmail.com. I keep getting the error message "Users must have an email address". -
An Unknown Error While Installing PostgreSQL
I use a windows operating system so i had to download postgresql from their main site, but after downloading and trying to install i got an error which says : unable to write inside TEMP environment variable path -
how to have one urls for each language in django
I have these urls. And all three show the same contents. But with the text translated into their language. How to manage the urls in dajngo for each language? 1: https://example.com/es/cursos 2: https://example.com/en/courses 3: https://example.com/de/schulungen the url must change according to the language that is selected. It is the same page. -
Can't set PointField default value
I'm trying to set the default value of a django.contrib.gis.forms.PointField in my django admin with a customized form like this: from django.contrib.gis import forms from django.contrib.gis.geos import Point from api import models class CustomPlaceCreationForm(forms.ModelForm): place_url = forms.CharField(initial="https://www.places.com/myplace") position = forms.PointField( widget=forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}), initial=Point(x=121.502020, y=25.039270, srid=4326) ) class Meta: model = models.Place fields = '__all__' The place_url initial works perfectly but the position is always [0, 0] by default. Is it a bug from the library or something I'm not doing correctly? Any workaround? Thanks! -
Display ValidationError In Ajax
I'm trying to display ValidationErrors using ajax. I've read many posts about this and tried many things but can't get it to work. I thiiinnnkkk ValidationErrors are passed as a dictionary and that they need to have json.dumps or .as_json() called on them before they are passed to ajax. Here is some of my code: forms.py raise forms.ValidationError('Please enter a number greater than 100') views.py if form.is_valid(): [...] else: # i've tried this error_dict= {'status':'form-invalid','form-errors':form.errors} return HttpResponse(json.dumps(error_dict),content_type="application/json", status_code=400) # and this data = {'error':form.errors.as_json(), 'is_valid': False} return JsonResponse(data, status_code=400) ajax error: function (data, xhr, errmsg, err) { $('.error-block').html(data.form-errors) }, -
Why doesn't request.GET.get capture this parameter?
I am working on a Django application that has a central page with many links to several functions. To keep track of the links I have made a template: xtodo.html and its corresponding view: xtodo_view <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>En construcción</title> </head> <h1 align="left">EN CONSTRUCCIÓN</h1> <h1> <h1>{{pagref}}</h1> <div> <img src="http://{{ request.META.HTTP_HOST }}/static/logos/Under_construction_icon-orange.svg.png" width="300" height="250" alt="UnderConstruction"/> </div> </body> </html> and this is the view def xtodo_view(request): # para pruebas, quitar if request.method == 'GET': pagref = request.GET.get('pagref','g') elif request.method == 'POST': pagref = request.POST.get('pagref','p') return render(request, 'incid/xtodo.html', {'pagref': pagref}) whenever necessary, I code the calls this way: <a href="{% url 'incid:xtodo' %}?pagref='newincidencia'" type="button" class="btn btn-primary waves-effect"> Nueva incidencia</a> or <li><a href=" {% url 'incid:xtodo' %}?pagref='perfil'"><i class="material-icons">person</i>Perfil</a> </li> With the hope that an "under construction" page will appear, indicating the name I have indicated for the link, but it works only for the first case - which is a button - but not in the others which are mere links. What am I missing?. -
Serializers update method returning just strings
i'm relatively new to Django & DRF, i created a serializer and defined an update method to override the default one, but when i test it in postman it returns just the strings in user data, code sample below. 'serializers.py' class UserSerializer(ModelSerializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] class AgentSerializer(ModelSerializer): user = UserSerializer() class Meta: model = Agent fields = ['user', 'phone', 'company'] def create(self, validated_data): user = validated_data.pop('user') new_user = User.objects.create(**user) agent = Agent.objects.create(user=new_user, company=validated_data['company'], phone=validated_data['phone']) return agent def update(self, instance, validated_data): user = validated_data.pop('user') user = instance.user user.username = ['username'] user.first_name = ['first_name'] user.last_name = ['last_name'] user.email = ['email'] user.password = ['password'] user.save() validated_data['user'] = User.objects.get(id=user.id) return super(AgentSerializer, self).update(instance, validated_data) 'postman test' {"user": { "username":"testusername", "first_name": "testfirstname", "last_name":"testlastname", "email":"test@test.com", "password": "secret" }, "phone":"1111", "company":"1"} 'postman result' "user": { "username": "['username']", "first_name": "['first_name']", "last_name": "['last_name']", "email": "['email']", "password": "['password']" }, "phone": 1111, "company": 1 What im i doing wrong? -
Generic detail view PostUpdateView must be called with either an object pk or a slug in the URLconf
Im getting this error "Generic detail view PostUpdateView must be called with either an object pk or a slug in the URLconf" when trying to use a PostUpdateView on my blog site this is my code I know I need to pass informations about the URL to the PostUpdateView but nothing I have tried worked. Im unsure if I need to convert my post_detaul view to a generic class view for this to work Thank you in advance for any help views.py """ from django.shortcuts import render, get_object_or_404 from .models import Post, Comment from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView, DetailView, CreateView, UpdateView from .forms import CommentForm, PostForm from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from django.contrib.auth.mixins import LoginRequiredMixin class PostListView(ListView): queryset = Post.cleared.all() context_object_name = 'posts' paginate_by = 3 template_name = 'posts/post/list.html' def post_detail(request, year, month, day, post): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.post = post comment_form.instance.name = request.user comment_form.save() return HttpResponseRedirect( post.get_absolute_url() ) else: comment_form = CommentForm() return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'comment_form': comment_form}) class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = … -
Sort django ListView based on calculated field in view
I want to sort the list from my model based on a (user-specific) field calculated in my views. I know how to order by the model fields using class Meta, but I have no idea how to do it if I want to use a calculated field in my views. In searching for the answer, the extra() method has come up, but django warns not to use it and that it will be deprecated in the future. Is there any other way to achieve this? What I want to achieve: I have a Song model with title, artist and lyrics fields, and in my views I calculate how many words the user knows for every song, and this is the field I would like to order by. So the field is (extract): for song in context['song_list']: stat = ((len(user_word)+len(set(already_known)))/(len(set(lyrics_list_))))*100 -
Postgres doesn't allow Django Admin to perform cascading deletion
So I'm trying to delete a User object from Django Admin. Obviously every model object related to the User should be deleted, as that's how I've defined it in my models.py. However, when I try to delete the User object, I get this: django.db.utils.IntegrityError: update or delete on table "app_reply" violates foreign key constraint "app_post_original_reply_id_fkey" on table "app_post" DETAIL: Key (id)=(m1GWZFPA) is still referenced from table "app_post". In my models.py, Post has a GenericRelation to Reply, like so: class Post(models.Model): ... replies = GenericRelation(Reply) ... def delete(self, *args, **kwargs): if self.images.all(): for i in self.images.all(): i.delete() if self.link: self.link.delete() super(Post, self).delete(*args, **kwargs) if self.original_reply: self.original_reply.delete() class Reply(models.Model): ... replies = GenericRelation('self') #Mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete = models.CASCADE) object_id = models.CharField(default = make_id(), unique = True, max_length = 8) content_object = GenericForeignKey() ... def delete(self, *args, **kwargs): if self.reply_images.all(): for i in self.reply_images.all(): i.delete() if self.link: self.link.delete() super(Reply, self).delete(*args, **kwargs) When I try deleting Reply instances from Django Admin, it works. It cascades as you'd expect it to, since GenericForeignKeys are by default cascade. But deleting the User object, that gives a a foreign key constaint violation. I just moved my database from SQLite to Postgres, … -
Braintree payment form not working | Django
I'm trying to build a Braintree payment form following the 'Django by Example 3' book but the form is not able to be filled: As you can see, the form is displayed in the browser but there's no chance by editing this 3 fields. Actually is being shown like 'images'. Below my template: {% extends "shop/base.html" %} {% block title %}Pay by credit card{% endblock %} {% block content %} <h1>Pay by credit card</h1> <form id="payment" method="post"> <label for="card-number">Card Number</label> <div id="card-number" class="field"></div> <label for="cvv">CVV</label> <div id="cvv" class="field"></div> <label for="expiration-date">Expiration Date</label> <div id="expiration-date" class="field"></div> <input type="hidden" id="nonce" name="payment_method_nonce" value=""> {% csrf_token %} <input type="submit" value="Pay"> </form> <!-- includes the Braintree JS client SDK --> <script src="https://js.braintreegateway.com/web/3.44.2/js/client. min.js"></script> <script src="https://js.braintreegateway.com/web/3.44.2/js/hostedfields. min.js"></script> <script> var form = document.querySelector('#payment'); var submit = document.querySelector('input[type="submit"]'); braintree.client.create({ authorization: '{{ client_token }}' }, function (clientErr, clientInstance) { if (clientErr) { console.error(clientErr); return; } braintree.hostedFields.create({ client: clientInstance, styles: { 'input': {'font-size': '13px'}, 'input.invalid': {'color': 'red'}, 'input.valid': {'color': 'green'} }, fields: { number: {selector: '#card-number'}, cvv: {selector: '#cvv'}, expirationDate: {selector: '#expiration-date'} } }, function (hostedFieldsErr, hostedFieldsInstance) { if (hostedFieldsErr) { console.error(hostedFieldsErr); return; } submit.removeAttribute('disabled'); form.addEventListener('submit', function (event) { event.preventDefault(); hostedFieldsInstance.tokenize(function (tokenizeErr, payload) { if (tokenizeErr) { console.error(tokenizeErr); return; } // … -
How to set Google-Vision Credentials on Django Heroku App
Cannot use Google Vision API on my Django app after I deploy it using Heroku. The problem is that I do not know how what to do regarding my Google Service Account key that is a JSON file. On localhost I would set the JSON file's path as an environment variable, but I do not know what should be done after deploying on heroku. I am fairly new to programming and django, apologies if the question does not make sense. -
back_populates behaviour in Django models
As explained in the answer of When do I need to use sqlalchemy back_populates? question, in SQLAlchemy you can define a related field in both of the classes to be explicit by using the parameter back_populates referring to the other variable name. I like this because it follow the principle of the Python Zen better explicit than implicit. The question is how to write this code class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") # Parent.children <--o2o--> Child.parent class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent = relationship("Parent", back_populates="children") # Child.parent <--o2o--> Parent.children in Django >= 3. -
Django Image Kit and AWS S3 bucket
I have imagekit working well using IDE but once deployed to heroku with storage in AWS S3 bucket my app within my project crashed . -
how to install mkvirtualenvwrapper from pip which is not working
I tried to install virtalenvwrapper but it didn't I have no idea what to do C:\Users\Vimal Rajan>pip install virtualenvwrapper Collecting virtualenvwrapper Downloading virtualenvwrapper-4.8.4.tar.gz (334 kB) |████████████████████████████████| 334 kB 1.3 MB/s ERROR: Command errored out with exit status 1: command: 'c:\users\vimal rajan\appdata\local\programs\python\python38\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Vimal Rajan\\AppData\\Local\\Temp\\pip-install-3nh4gw0r\\virtualenvwrapper\\setup.py'"'"'; __file__='"'"'C:\\Users\\Vimal Rajan\\AppData\\Local\\Temp\\pip-install-3nh4gw0r\\virtualenvwrapper\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Vimal Rajan\AppData\Local\Temp\pip-pip-egg-info-7pa4p02r' cwd: C:\Users\Vimal Rajan\AppData\Local\Temp\pip-install-3nh4gw0r\virtualenvwrapper\ Complete output (3 lines): Traceback (most recent call last): File "<string>", line 1, in <module> ValueError: source code string cannot contain null bytes ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Parse JSON and Filters in Python Django Template
Foreach in django python {{details.variation_values}} In django, I'm getting result of details.variation_values in JSON Format But Now i wanna make iterations of JSON result ,For example: details.variation_values = ["28","30","32"] Example Result But I need each index in each row {% for data in array %} <div class="row" id="variationfield{{data}}"> <div class="col-md-9"> <div class="form-group"> <input type="text" class="form-control" name="value" placeholder="" value="{{data}}"> </div> </div> </div> {% endfor %} Sorry if you're not understanding my problem. Thanks in advance -
like/unlike a post without refreshing the page
I have been working on a like system in which a user can like a post and unlike if it is already liked by that user, very similar to instagram. So after finishing with this system I realized that the page is reloading everytime a button is pressed and I dont want that to happen, after some investigation I concluded that this can be done using json or jquery but the problem is that I haven't really used that because I am focusing exclusively on learning django for now. How would be the code to make the page dont refresh when the buttons are pressed? models.py class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank=True) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) created =models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def get_absolute_url(self): return reverse('comments', args=[self.pk]) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) def __str__(self): return str(self.post) views.py def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(author=user, post_id=post_id) if not created: …