Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a Tree Documents based on an element of a Queryset?
I have a queryset within some objects. What i have to do is: For each object and for each son of these objects i should build a tree of documents by using a new class. ( if is possible i wouldn't use django-mptt or some other applications. -
How to save json object received from ajax request to postgreSQL in Django?
I'm trying to save a JSON object into Note object. But getting this error: InterfaceError-Error binding parameter 1 - probably unsupported type. index.js $.ajax({ type: "POST", url: "/notes/{{note.id}}/update", data: { content: editor.getContents(), csrfmiddlewaretoken: "{{ csrf_token }}" } }); views.py def update_view(request, id): if request.method == 'POST': note = Note.objects.get(pk=id) note.content = request.POST['content'] note.save() return redirect('/') models.py from django.contrib.postgres.fields import JSONField class Note(models.Model): last_updated = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=50) content = JSONField() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) Any help is appreciated. -
Django - Grouping context datasets into 1 for loop
1) For each Product I need to show all it's reviews with an attached profilepicture, this requires queries into 3 models but I need a maximum of 2 for loops as when I do the Profile for loop all the images appear together as shown below. 2) It also looks like my filter "id__in" isn't working as all users who've reviewed an item have their profilepicture in the for loop instead of the users who have only reviewed that specific product. Is there a way to fix these issues? models.py class Product(models.Model): name = models.CharField(max_length=100) brand = models.CharField(max_length=100) cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) category = models.CharField(max_length=100) releasedate = models.DateField() description = models.TextField() productphoto = models.ImageField(default='products/default_product.jpg', upload_to='products') class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)]) reviewtext = models.TextField() class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) profilephoto = models.ImageField(default='profiles/default_profile.jpg', upload_to='profiles') views.py class ProductDetailView(TemplateView): # template_name = 'reviewApp/test.html' template_name = 'reviewApp/product_detail.html' def get_context_data(self, **kwargs): prod = self.kwargs['pk'] context = super(ProductDetailView, self).get_context_data(**kwargs) context['Products'] = Product.objects.filter(id=prod) context['Reviews'] = Review.objects.filter(product=prod) profile_ids = Review.objects.values_list('profile_id', flat=True) context['Profiles'] = Profile.objects.filter(id__in=profile_ids) return context product.html {% for prod in Products %} <img src="{{prod.productphoto.url}}"> {{ prod.brand }} {{ … -
How to add crud in django comment
I'm just new to django. I'm having a hard time how can i add an update and delete functions in my comment section. here's my forms.py for comment. class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' })) class Meta: model = Comment fields = ('content', ) and here's my views.py for comment. it's attached to my bookdetail. def BookDetail(request, slug): most_recent = Book.objects.order_by('-timestamp')[0:3] book= get_object_or_404(Book, slug=slug) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={'slug': slug})) if request.user.is_anonymous: user_membership = None else: try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) I hope someone can help me, thanks. -
Post multiple to REST API django from Array using Axios in Reactjs
I have an Array, i want to get all values one by one from Array and post value using axios to rest-api django In Django i have model: class Cars(models.Model): car = models.CharField(max_length=100) i want to add data in my model from axios post here is my array, from this array i want to get value and add in to my model one by one on single submit, let cars = [ ["Saab", "Volvo", "BMW"], ["Toyota", "Alto", "Civic",] ] i have try like this, handleFormSubmit = event => { event.preventDefault(); for (var i = 0; i < cars.length; i++) { axios.post('myURL',{ car: car[i] }) .then(res => console.log(res)) .catch(err => console.log(err)); } } and after on submit i got Error: "Request failed with status code 400", when i make axios post outside the loop it is fine, but i want to add multiple data from an array. -
How can i send data to a database from a view in Django?
I created a form in my Django project, i would now like to have this form interact with a database. Basically, when the user inputs some data, it must be sent to a database. Note: i already have a database in my django project, i defined it on my settings.py, but i must not send the data to that DB, but to a different database, since that db will interact with another Python script. Now, what i don't know, is how can i use another database in Django? Where should i define the whole second database configuration? This is what my basic view looks like at the moment: def input(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = InputForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: messages.success(request, f"Success") # if a GET (or any other method) we'll create a blank form else: form = InputForm() return render(request, "main/data.html", context={"form":form}) -
How to deserialize a django model object?
I am fairly new to python and transitioning from java, so I'll use the java terminologies as I need to know the equivalent python version of it. So I have a django model as described below : class Order(models.Model) : order_id = models.TextField(,null=False,blank=False is_completed = models.BooleanField(null=False,blank=False,default=False) Also I have a kafka broker to process these orders, to push these into a kafka quaue, I am transforming them into json objects as depicted below : from django.core import serializers serialized_obj = serializers.serialize('json', [ order, ]) print("Pushing to kafka topic ","some_topic") print(serialized_obj) send_message("some_topic",serialized_obj) Now I need this json object to be converted back to django model object, in java we have something called as Jackson which could have done the same for me, but I am not sure how to do this in Python3. I tried the below code snippet, it returned me an object of type <generator object Deserializer at 0x7fe000323bf8> //consumer.py try : print(json.loads(msg.value())) print("---------------------------------") obj = serializers.deserialize("json", msg.value()) print(obj) except Exception as e : import traceback print(traceback.format_exc()) How can I achieve this in Python3? -
What's wrong with authentication?
I'm trying to change sqlite3 to postgresql in django and getting this error: django.db.utils.OperationalError: FATAL: password authentication failed for user "mat" settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ohhbjebb', 'USER' : '', 'PASSWORD' : 'bplsinfHGZNWjUzOgyd74Z7FIokMVqXU', 'HOST' : 'balarama.db.elephantsql.com', 'PORT' : '5432', } } -
Is there any way to know if the user is using the django web application from different devices?
I want to build a web application where the user can only browse or use the site from one device that he used while first signing up to the site. Let's say I used device A (It can be anything like android, desktop etc) to register. So If I want to browse the mentioned site using a different device the server will not allow me to browse that site. More precisely, suppose A is an Android device. So If I use another Android device B to browse the site it won't allow. I need A to browse the site. Using Django - Python Framework. -
Django models relationships
I build an application where people post ads for sale different things like a cars,apartments, gadgets & etc. I have models with its own special fields for each item like a : CarModel, ApartmentModel, SmartphoneModel etc... And I have a model Article : and want to add field item_of_sale which can be instance of different models (for example CarModel or ApartmentModel). class Article(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles' ) category = models.ForeignKey(Category,on_delete=models.CASCADE ) title = models.CharField(max_length=120) text = models.TextField() item_of_sale = # ??????? models.OneToOneField I suppose I try something like this: class CarModel(models.Model): ad = models.OneToOneField(Article, on_delete=models.CASCADE, related_name='item_of_sale') marc = models.CharField(max_length=40, choices=MARC_CHOICES) model = models.CharField(max_length=120, default='') ..... class ApartmentModel(models.Model): ad = models.OneToOneField(Article, on_delete=models.CASCADE, related_name='item_of_sale') location= models.CharField(max_length=200 ) address= models.CharField(max_length=120) ..... But django does not allow to have more than one model with related_name="item_of_sale" . Have you any ideas how I can make database with this kind of relations. Please any help . Thank you in advance. -
ModelForm vs formset_factory vs modelformset_factory vs inlineformset_factory
I m working to a project and i have a model in OneToOne relationship to another model that have multiple fields Now i want to insert data from template to both models and i don t know what is the best option to do that I read about formset,inline formset, modelformset but i don t understand the difference between them. exemple cod: class Person(models.Model): firs_name = models.CharField(max_length=50) last_name = models.CharField(max_lenght=50) email = models.EmailField(max_length=50) address = models.OneToOneField(Address, on_delete=models.CASCADE) class Address(models.Model): city = models.CharField(max_length=50) str = models.CharField(max_length=50) bl = models.CharField(max_length=50) -
What does mean from . import?
Hello I am using Django with Python and I don't understand this : from . import views I would like to know what I am importing when I type that. Thank you for your explanations -
operational error 1050 Error “Table already exists” in django makemigrations
Hi am getting this wherever i try to make changes to my models or trying to migrate am using mysql and django 1.8.6 operational error 1050 Error “Table 'products_myproducts' already exists” just every time i make migrations class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) managers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="managers_product",blank=True) media = models.ImageField(blank=True,null=True, upload_to=download_media_location, storage=FileSystemStorage(location=settings.PROTECTED_ROOT)) title = models.CharField(max_length=30) description = models.TextField(default='',blank=True) slug= models.SlugField(blank=True,unique=True) price = models.DecimalField(max_digits=60,decimal_places=2,default=9.99) sale_active = models.BooleanField(default=False) sale_price = models.DecimalField(max_digits=60,decimal_places=2,default=6.99,null=True,blank=True) def __str__(self): return self.title also fo my products class MyProducts(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) products = models.ManyToManyField(Product,blank=True) def __str__(self): return "%s" %(self.products.count()) class Meta: verbose_name = "My Products" verbose_name_plural = "My Products" -
How do I store / pass inputs from dynamically made textfields in HTML to Django?
I'm dynamically creating new textfields which will take information from a user. I'm wondering how I'm supposed to go about taking the inputs and passing it to Django? -
Can I specify instance parameter if I am using forms.Form?
I am currently using forms.Form type for one of my forms because I needed to specify many parameters for them, such as queryset, disabled, required. The form will allow users to update certain fields in an entry, that means I will have to use the instance parameter as seen in here https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#the-save-method . However, I get this error when I run my code in views.py if Class.objects.filter(module__subject=subject).exists(): a = Class.objects.filter(module__subject=subject)[0].pk form = InputClassInformation(request.POST, instance=a) Error: TypeError at /input-class-info/ __init__() got an unexpected keyword argument 'instance' I know this would have been fine if I was using ModelForm, but trying to specify all the parameters I need in ModelForm has been difficult, so is there a way I can specify the instance I want to update while using forms.Form? -
How to create a kafka consumer independent of Django server
I am fairly new to Python, so please bear with my question. So I have a django based web application where I am performing some tasks using Kafka. I am using confluent-kafka wrapper to communicate with the Kafka Broker. So once a topic is created on the kafka broker, I assign a consumer to subscribe to this process, to make this non-blocking, I am using multiprocessing module so that the consumer runs on a separate thread and not block the main application thread. However, I am not sure, what will happen if my server shuts down? Will the process still run like how the cronjobs still run even if the server is not running? If not can someone please suggest me how should I trigger my consumer so that it is independent of my django server? -
UnicodeEncodeError: 'ascii' codec can't encode character '\u2026' in position 38: ordinal not in range(128)
I'm having some problem with Django migrations. when I migrate it shows this error: UnicodeEncodeError: 'ascii' codec can't encode character '\u2026' in position 38 : ordinal not in range(128) there were similar problems on StackOverflow like this article or this one but I don't know how to fix this in Django. here is my models file: from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from tinymce.models import HTMLField from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.core.validators import MinValueValidator from django.core.validators import MaxValueValidator from .validators import PhoneValidator class AquaUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not phone: raise ValueError('لطفا شماره تلقن خود را وارد کنید') user = self.model( phone=self.model.normalize_phone(phone), **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(phone, password, **extra_fields) def create_superuser(self, phone, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_admin', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') if extra_fields.get('is_admin') is not True: raise ValueError('Superuser must have is_admin=True.') if extra_fields.get('is_active') is … -
How to fix category view calling as age_rate category that dosen't work in template
I want to show views results in template django app named as core but it dosen't work properly, where is the problem? There is two model for two kind of category one as Category and another as AgeRate. Category will categorize books based on genre and AgeRate will categorize them by age rates that for now includes (A, B ,C) rates. now in template I'll try to show the results of age rate but dosen't work properly. model.py class AgeRate(TranslatableModel): translations = TranslatedFields( age_rate=models.CharField(max_length=3), slug=models.SlugField(max_length=4, db_index=True, unique=True, default='') ) class Meta: # ordering = ('name',) verbose_name = 'age_rate' verbose_name_plural = 'age_rates' def __str__(self): return self.age_rate def get_absolute_url(self): return reverse('core:product_list_by_age_rate', args=[self.slug]) class Product(TranslatableModel): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) age_rate = models.ForeignKey(AgeRate, related_name='products_by_age', on_delete=models.CASCADE, default='') url.py from django.urls import path from . import views app_name = 'core' urlpatterns = [ path('', views.core, name='core'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<slug:age_rate_slug>/', views.core, name='product_list_by_age_rate'), ] views.py def core(request, age_rate_slug=None): age_rate = None age_rates = AgeRate.objects.all() products_by_age = Product.objects.filter(available=True) if age_rate_slug: language = request.LANGUAGE_CODE age_rate = get_object_or_404(AgeRate, translations__language_code=language, translations__slug=age_rate_slug) products_by_age = products_by_age.filter(category=age_rate) if request.method == 'POST': #.... else: form = ContactForm() return render(request, 'core/core.html', {'form': form, 'products_by_age': products_by_age, 'age_rate': age_rate, 'age_rates': age_rates}) template {% for a in age_rates … -
How to make an update view handle both an object creation first and the after that object updation in django?
I am making a dating site and right now I am stuck in a problem. The problem follows : 1.I want the user to create his user profile info like when his likes ,dislikes etc.. 2.After the user has created his profile I want him to update that profile on that same page it was created. 3.The problem is how can i make my update view handle both user creation and user updation.For e.g If the user first created his profile then it will be done with create view and then when he has to update his profile it will be done with update so how can these two views be in same view. Here's the views.py @login_required def profile(request,pk): user_detail = UserDetail.objects.all() return render(request,'social_app/profile.html'{'user_detail':user_detail,}) class Create_View(CreateView): model = UserDetail template_name = 'social_app/profile-create.html' fields = [ 'enthicity','You_work_as','image','cover_image','country','height', 'birth_date','smoking','relationship','looking_for','diet','kids','eye_color', 'status','hobby', ] -
Django - How to filter purchased book by user
I have created a model where a user is allowed to purchase a book. The book being purchased was already recognized but when the user visits the content of the book, the following error occurs: get() returned more than one Purchase_Book -- it returned 2! I already tried to tweak the codes but to no avail. Here are my models and their connection to each other. class Book(models.Model): # some book info def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'slug': self.slug}) @property def pages(self): return self.page_set.all() the content of the book class Page(models.Model): # some pdf files to upload def __str__(self): return self.slug def get_absolute_url(self): return reverse('page-detail', kwargs={ 'book_slug': self.book.slug, 'page_slug': self.slug }) the models to be able filter users who can access the contents of the book. class Purchase_Book(models.Model): description = models.CharField(max_length=50, null=True) selected_Book = models.ManyToManyField(Book) def __str__(self): return self.description class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) service_Type = models.ForeignKey(Purchase_Book, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.email Here's my latest views.py, where I am filtering the user who can access the content of the book. class PageDetailView(NeverCacheMixin, LoginRequiredMixin, generic.View): def get(self, request, book_slug, page_slug, *args, **kwargs): book = get_object_or_404(Book, slug=book_slug) page = get_object_or_404(Page, slug=page_slug) purchased = get_object_or_404(Purchase_Book) user_membership = get_object_or_404(Customer, … -
How to debug django (logic) code using django shell in Visual Studio Code
I'm developing a django app including custom logic code using Visual Studio Code and I would like to debug my code while interactie via the django shell. Is this possible and if so, what debugging settings are required? -
No Reverse Match Found error Django while passing pk to view
For my project, i am trying to view the profile of individual users by passing the profile primary key to the urls.py ! Now for some reason, whenever i click on the link, it says no reverse match found. I am certain that i am passing the correct key because i was debugged the same, but still it fails with the same error , (Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['usercreation/profile/(?P[0-9]+)/$']) The primary key passed in the template to view matches with the profile primary key. But somehow it returns with error when i refresh the page. URLS.py path('profile/<int:pk>/',views.ProfilePage.as_view(),name="profile"), Views.py class ProfilePage(DetailView): model = models.UserCreation context_object_name = 'profile' def get_context_data(self, *args, **kwargs): context = super(ProfilePage, self).get_context_data(*args, **kwargs) user =self.request.user try: context['data'] = ProfileData.objects.get( user=user) context['sorted'] = sorted(chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)), key=lambda instance: instance.date, reverse=True) except ProfileData.DoesNotExist: context['data']= None return context Models.py class ProfileData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) b_place = models.CharField(max_length=100,blank=True) l_place = models.CharField(max_length=100,blank=True) j_place = models.CharField(max_length=100,blank=True) dob = models.DateTimeField(blank=True) def get_absolute_url(self): return reverse("usercreation:profile",kwargs={'pk':self.post.pk}) class AddStatus(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) status = models.TextField() date = models.DateTimeField(default=datetime.now) class ImageLib(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) picture = models.ImageField() date = models.DateTimeField(default=datetime.now) Templates <td><h5><a href="{% url 'usercreation:profile' blog.author.usercreation.pk %}">{{blog.author}}</h5></td> -
How do I dynamically change initial form values based on a value selected by the user? Django
I would like certain fields in my form to be populated based on a selected value in one of the fields. I have found examples on dynamic form generation, but not on this... Here is my models.py class Module(models.Model): subject = models.CharField(max_length=200, default="") class Class(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, default="") duration = models.CharField(max_length=200, default="") description = models.CharField(max_length=200, default="") and my forms.py class inputClassInformation(forms.Form): module = forms.ModelChoiceField(queryset=Module.objects.all()) duration = forms.CharField(disabled=True, required=False) description = forms.CharField() Based on the module selected by the user, I would like duration to be (1) automatically pulled from the entry in the database, and be shown in the form field. (2) The user should be able to update the same entry. I've not been able to find an example online/in the documentation on this, so help is appreciated, thank you! -
Django page with two forms: how to post only one form without page refresh
I have one page with two forms. Depending on the radio button selected (one is selected by default) one of the forms is showing and the other one is hidden (using JS and CSS). When the user fills in the form field and submits the form both forms are validated and the page refreshes. I am looking to achieve that on submitting the form only the corresponding form is validated and the page is not refreshed. How can only one form be validated and the page prevented from refreshing (i.e. keep showing the manual form after submission)? Looking for a solution the following suggestions did not solve the problem: Proper way to handle multiple forms on one page in Django, How to submit form without refreshing page using Django, Ajax, jQuery?, http://jquery.malsup.com/form/. views.py from flap.forms import FlapManualForm from flap.forms import FlapAutoForm def index(request): if request.method == 'POST': form_manual = FlapManualForm(request.POST) form_auto = FlapAutoForm(request.POST) if form_manual.is_valid(): try: if form_manual.data['flap']: print(form_manual.data['flap']) manual = request.POST['flap'] except: print('manual form empty') if form_auto.is_valid(): try: if form_auto.data['flap_time']: print(form_auto.data['flap_time']) auto = request.POST['flap_time'] except: print('auto form empty') else: form_manual = FlapManualForm() form_auto = FlapAutoForm() return render(request, 'index.html', {'form_manual': form_manual, 'form_auto': form_auto}) forms.py class FlapManualForm(forms.Form): flap = forms.CharField(min_length=4, max_length=4, … -
Adding A View Count System To A Function Based Detail View
I'm trying to implement django-hitcount into my project and i don't know how to go about it. Using some of the methods i tried will keep counting the same IP Address, using a function based view will be preferable I am still getting used to CBV #views def postdetail(request, pk): post = get_object_or_404(Post, pk=pk) UserId = request.user.id comments = Comment.objects.filter(post=post, reply=None).order_by('-id') is_liked = False is_saved = False # hitcount.views.HitCountMixin.hit_count() if post.likes.filter(id=UserId).exists(): is_liked = True if post.saved.filter(id=UserId).exists(): is_saved = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs) comment.save() # return HttpResponseRedirect(object.get_absolute_url()) else: comment_form = CommentForm() context = { 'object': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), 'comments': comments, 'comment_form': comment_form, 'is_saved': is_saved, } if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({'form': html}) return render(request, 'blog/post_detail.html', context) #models.py class Post(models.Model, HitCountMixin): title = models.CharField(max_length=140) content = models.TextField(max_length=400,validators=[validate_is_profane]) likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='post_pics', blank=True) image_2 = models.ImageField(upload_to='post_pics', blank=True) image_3 = models.ImageField(upload_to='post_pics', blank=True) restrict_comment = models.BooleanField(default=False) saved = models.ManyToManyField(User, related_name='saved_post', blank=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') objects = PostManager() def __str__(self): …