Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django pre filled form
I want form data to be pre filled when rendered first time, the initial parameter does not affect the form at all. When user edits profile I want user data to be displayed in the form. def profile_update(request): if request.method == 'POST': form = UpdateProfile( initial={'username': 'Hi there!'}, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('profile')) else: form = UpdateProfile() return render(request, 'users/profile_update.html', {'form': form}) class UpdateProfile(forms.ModelForm): email = forms.EmailField() img = forms.ImageField(label='img', required=False) class Meta: model = TbUser fields = ['username', 'img', 'email', 'cellphone', 'empno', 'real_name', 'nfc_id', 'sex', 'role', 'department'] -
How to get_connect_redirect_url after SocialAccountSignUp?
Hi is there any working solution to get get_connect_redirect_url to work? I have tried multiple redirects, renders, resole_url, reverse etc. all with custom adapters but nothing is working. How is able to help? class MySocialAccountAdapter(DefaultSocialAccountAdapter): def get_connect_redirect_url(self, request, sociallogin): """ Returns the default URL to redirect to after successfully connecting a social account. """ assert request.user.is_authenticated return resolve_url('social_login_success') -
Building a complete multi-platform (android & web) chat app
I want to build a chat app platform for both web and android. I want the chats and contents in the same database (kind of like telegram I guess?). What tools I should use for creating such a project? -
How to use a choice model to filter out certain characters from a set
I'm fairly new at this so please keep that in mind. I'm creating a Django website where users (who are learning Chinese) can upload Chinese vocabulary lists and the site will return a list of just the unique characters (no duplicates) that the user can download. So far, it's working and doing everything I described above. But the part that I'm stuck on is that I want to add a filter functionality. I want to add the option to exclude some of the more common Chinese characters from the list that the user downloads (what I'm thinking of as a filter feature). I have created a dropdown menu where before the user presses upload, they first say whether they want to filter out the 100 most common characters, 500, none, etc. Then, they move to another page where it should take that into account when it's writing to the file that it presents for the user to download. models.py from django.db import models #This is supplying the options on the first page class FilterPreference(models.Model): NONE = 'NO' first_250 = 'F250' first_500 = 'F500' first_750 = 'F750' first_1000 = 'F1000' PREFERENCE_CHOICES = [ (NONE, 'None'), (first_250, 'First 250'), (first_500, 'First 500'), … -
Download data from ajax requests from multi-soruce web scraper
I am looking for help on adding a download feature to a web-app. The app takes a query from the user and then searches over 30 sources with the users query and returns it. The searching is done using ajax through a results.html. The below code is reduced as the code can be very long with essentially repeated work (slightly different depending on the website searched). The below code works in its current state where the 'example.com' is searched and returns the number of hits from the query. Results.html {% load custom_tags %} {% block content %} <!--Show user's query--> <div class="row"> <div class="col-md-12"> <table> <tbody> <tr> <td class="ps"><i id="spin" class="fa fa-fw fa-2x"></i></td> <td> <h4 style="margin-bottom:0px;">Your query: <a href="{% url 'search:result' %}?query={{query}}">{{query}}</a></h4> <span>Searching for: {{queries}}</span> </td> </tr> </tbody> </table> </div> </div> <hr> <!--Links to sections--> <div class="row"> <div class="col-md-12"> <ul class="nav nav-pills"> <li role="presentation"><a href="#identity">Identity</a></li> <li role="presentation"><a href="#phys-chem">Phys-chem</a></li> <li role="presentation"><a href="#other-info">Other Information</a></li> <li role="presentation"><a href="#synonyms-more">Synonyms</a></li> {% if next_query%} <a href="{% url 'search:result' %}?query={{next_query}}"><button class="btn btn-default">Next Query</button></a> {% endif %} </ul> </div> </div> <a href="{% url 'search:download_data' %}">Download Data</a> <div class="row"> <div class="col-md-12"> <span class="anchor" id="biomonitoring"></span> <h2>Biomonitoring</h2> <table class="table table-hover"> <thead> <tr><th class="text-center info" colspan="3">Tier 1</th></tr> <tr><th>Source</th><th>Status</th><th>Result</th></tr> </thead> <tbody> {% with … -
Need more explanation on Admin customisation of Django using fieldsets?
Ok, this is kind of a rookie question. While trying to build a polling app, I came across these concepts where they used TabularInline in models. py. Couldn't figure out a proper explanation for the below code and how they behave. Added my code below. (It's supposed to have multiple 'choices' for a question on the same page.) So whats fieldsets? classes? class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [(None,{'fields': ['question_text']}), ('Date published',{'fields': ['pub_date'], 'classes':['collapse']}),] inlines = [ChoiceInline] admin.site.register(Question,QuestionAdmin) -
How to customize JSON Field in django admin
I have a Postrges JSON field in my model which is used to store nested json data. I want to reformat it on django admin to either open in a editor or some reformatted json which is readable by someone having 0 knowledge of JSON I have tried using django_json_widget like this from django.contrib.postgres.fields.jsonb import JSONField from django.contrib import admin from django_json_widget.widgets import JSONEditorWidget class MyModel(admin.ModelAdmin): formfield_overrides = { JSONField: {'widget': JSONEditorWidget}, } But this is just showong me empty space in place of field content like this The data stored in context field is of this format: { "type":"product", "products":[ { "id":"b9757d05-1b33-4ce3-aaa4-4d20480253f3", "mrp":65000.0, "tax":null, "upc":null, "name":"Macobook Air", "isbn_number":null, "display_name":"Macobook air", "product_type":"goods", } ], "variant_detail":{ } } How can I show it in a proper way? -
How to check if data from input exist in QuerySet - Django
Can I check if a data from input html is in QuerySet? exemple: <div> <input type="tel" id="phone-number"> {% if input in client %} -
how can i get the "post id"(foreign key field connected with comment model) to the django comments form without post_detail page in django
i am creating a single page blog site how can i get the post id to the comments form , i created django forms with necessary field but the problem is ,i have to select the post id from a drop down menu manually while commenting, for that i passed post object as an input value of a form to views.py file but django needs instance to save in database what should i do now note :i am not using post_detail models.py class comments(models.Model): name=models.CharField(max_length=255) content=models.TextField() post=models.ForeignKey(blog,related_name="comments",on_delete=models.CASCADE) #blog is the model to which comment is related date=models.DateTimeField(auto_now_add=True) forms.py class commentform(ModelForm): class Meta: model=comments fields=('name','content','post') widgets={ 'name' : forms.TextInput(attrs={'class':'form-control','placeholder':'type your name here'}), 'content' : forms.Textarea(attrs={'class':'form-control'}), 'post' : forms.Select(attrs={'class':'form-control'}) } Html <form method='POST' action="comment_action" class='form-group'> {%csrf_token%} {{form.name}} {{form.content}} <input type="text" id="objid" name="objid" value="{{objs.id}}" hidden> <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button> views.py def comment_action(request): name=request.POST.get('name') content=request.POST.get('content') objid=request.POST.get('objid') to_db=comments.objects.create(name=name,content=content,post=objid) print(name,content,objid) return redirect('/homepage') return render(request, 'index.html') ERROR : Exception Type: ValueError Exception Value: Cannot assign "'48'": "comments.post" must be a "blog" instance. -->48 is my blog id i know that database will only accept instance post field because that was a foreign key my question is how to pass it ? -
How can I turn Tag to List ? or How can I use tags in for loop ? (Django)
I want to show some tags product part of the homepage. How can I do with for loop ? Thats my index func. can I turn tags in product to list ? I try like : example_tag = Tag.objects.filter('example') but not working def index(request,): category = Category.objects.all context = { 'products': products, 'category': category, } return render(request, 'index.html', context ) -
Static Files and Upload, process, and download in Django
I've made a desktop app in Python to process .xls files with openpyxl, tkinter and other stuff. Now i'm looking to run this App on www.pythonanywhere.com. I was expecting to make an app to upload the file to the server, process it and then retrieve it changed to the user. But after long months struggling with Django i`ve reached the problem of static media. As I understood Django doesn’t serve files in production mode. Does this means that I can’t upload-process-download as I was planning? Or I can run in the view function the process algorithm on the request.file and then retrieve it changed, regardless of not serving static files? Am I missing something? Does Flask has the same issue? What’s the optimal solution? Apologize me for the many doubts. PD: I took the time to read many similar questions and seems to be possible to upload and download, but then im missing something on handling static files and what that means -
Trying to get the no of (count) of questions of specific data and used this information to validate the input field value in Django template
in my project, I have a table having questions of specific topics and subtopics. I want to count the no of questions of each subtopic for a particular topic id. here I have a query named subtopics which contains the information about subtopics of a particular topic and the other one is a list named totall which contains total questions of subtopics that are present in query named subtopics . in models.py the question table class Questions(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics, on_delete= models.CASCADE , default = 1) sub_topic = models.ForeignKey(Sub_Topics, on_delete= models.CASCADE, default = 1) question = models.CharField(max_length=100) image= models.URLField(null=True) difficulty=models.CharField(max_length=100, default='') class Meta: db_table = 'questions' in views.py def showassess(request): if request.method=='POST': classname=request.POST.get("classname") topicid=request.POST.get("topicid") topicname=request.POST.get("topicname") print(topicname,topicid) gradeid=request.POST.get("gradeid") subtopics=Sub_Topics.objects.filter(topic__id=topicid) print(subtopics) listt=list(Sub_Topics.objects.values_list('id',flat=True).filter(topic__id=topicid)) q=0 totall=[] for p in listt: if q <= len(listt): totalques=Questions.objects.filter(sub_topic__id=listt[q]).count() totall.append(totalques) q=q+1 #totalques=Questions.objects.filter(sub_topic__in=listt) print(listt) print(totall)#list contain no of questions of each subtopic having specic topic_id context={ 'totall':totall, 'topicid':topicid, 'topicname':topicname, 'classname':classname, 'gradeid':gradeid, 'subtopics':subtopics, } return render(request,"assessment.html",context) output is [1, 2, 3, 4]-->list (contains subtopic id ) [3, 2, 1, 1]-->totall (total no of questions of subtopics mentioned above[eg: subtopic having id=1 has total 3 questions ,subtopic of id=2 have 2 questions] in the template, … -
Limit choices to a user attribute
I have a series of Models which are connected by foreign keys. General SETUP APP class Company(HistoryBaseModel): code = models.CharField(max_length=3) name = models.CharField(max_length=50) user_company = models.ManyToManyField(User, through="UserCompany", through_fields=("company", "user")) class Meta(BaseModel.Meta): verbose_name = "Company" verbose_name_plural = "Companies" ordering = ('code',) def __str__(self): return f'{self.name} ({self.code})' class UserCompany(HistoryBaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, verbose_name="Company", related_name="%(app_label)s_%(class)s_company") user = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="User", related_name="%(app_label)s_%(class)s_user") class Meta(BaseModel.Meta): verbose_name = "User's Company" verbose_name_plural = "User's Companies" constraints.UniqueConstraint(fields=['company', 'user'], name='unique_user_company') def __str__(self): return f'{self.user} ({self.company})' class MachineTypes(HistoryBaseModel): manufacturer = models.CharField(max_length=50) family = models.CharField(max_length=20) type = models.CharField(max_length=10) series = models.CharField(max_length=10) company_machine_types = models.ManyToManyField(Company, through = 'CompanyMachineTypes', through_fields=('type_series', 'company')) class Meta(BaseModel.Meta): verbose_name = "machine Type" verbose_name_plural = "machine Types" constraints.UniqueConstraint(fields=['family', 'type', 'series'], name='unique_type_series') ordering = ('manufacturer', 'type', 'series') def __str__(self): return f'{self.manufacturer} {self.type}-{self.series}' # Unique: Type, Series class CompanyMachineTypes(HistoryBaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_company") type_series = models.ForeignKey(MachineTypes, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_type_series", verbose_name='Type/Series') class Meta(BaseModel.Meta): verbose_name = "Company machine Types" verbose_name_plural = "Company machine Types" constraints.UniqueConstraint(fields=['company', 'machineTypes'], name='unique_company_typeSeries') def __str__(self): return f'{self.company} ({self.type_series})' class Machine(HistoryBaseModel): type = models.ForeignKey(MachineTypes, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_type") company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_company") registration = models.CharField(max_length=10, unique=True) sn= models.CharField(max_length=10, unique=True) class Meta(BaseModel.Meta): verbose_name = "machine" verbose_name_plural = "machine" ordering = ('company', 'type', 'sn') def __str__(self): return f'{self.company} {self.registration} ({self.sn})' Power Source … -
Using SweetAlert2 in Django
I'm using SweetAlert to have better javascript alerts. In the documentation of sweetalert, says this: A HTML description for the popup. [Security] SweetAlert2 does NOT sanitize this parameter. It is the developer's responsibility to escape any user input when using the html option, so XSS attacks would be prevented. I know that Django autoescapes by default to prevent XSS attacks. My question is if django autoescapes automatically the HTML written by javascript. -
JSONDecodeError in Django project
I'm a beginner. I do everything as in the django ecommerce website course from the link, but it does not work for me. I also tried other stack overflow solutions but they didn't help. I have this error when i go to /update_item/ and the data is not showing up in the terminal: Expecting value: line 1 column 1 (char 0) error png tutorial link cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) return JsonResponse('Item was added', safe=False) -
how to call api in android using retrofit?
I want to call login api(django) when user click on login button.I have created apiinterface and apiclient also.but when I Click on login button it shows me text: ***Failed to connect to /my ip address:8000.***I am using pgadmin.Server is already runnig and api works fine in postman,I don't know why it is not connecting and gives me message failed to connect??Please help me out!! public class ApiClient { private static final String BASE_URL="http://192.168.0.102/auth/"; private static ApiClient mInstance; private Retrofit retrofit; private ApiClient(){ retrofit=new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static synchronized ApiClient getInstance(){ if (mInstance==null){ mInstance=new ApiClient(); } return mInstance; } public ApiInterface getApi(){ return retrofit.create(ApiInterface.class); } } public interface ApiInterface { @FormUrlEncoded @POST("registeruser") Call<ResponseBody>performUserSignIn(@Field("username") String username, @Field("full_name") String full_name , @Field("password") String password, @Field("confirm_password") String confirm_password); @FormUrlEncoded @POST("loginuser") Call<ResponseBody>performUserLogin( @Field("username") String username ,@Field("password") String password ); } Call<ResponseBody> call=ApiClient.getInstance().getApi().performUserLogin(username,password); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { String s =response.body().string(); Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).show(); } }); } -
Share files with other users (Django)
Description About the application: The main idea of this app is to create projects and share uploaded files with other users with permission. So: after creating the project( which is a Project module also), When any user uploads his file to the Django database, he can make this file visible to other users or not(this depends on his choice). This is the models: class File(models.Model): file_name = models.CharField(max_length=100) file = models.FileField(storage=file_storage, max_length=100) project_owner = models.ForeignKey(Project, on_delete=models.CASCADE,related_name='project_owner') projects_accessed = models.ManyToManyField(Project) And this is the Project Module also: class Project(models.Model): name = models.CharField(max_length=30) task = models.ForeignKey(Task, on_delete=models.SET_NULL, null=True, blank=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) This is the kind of prototype i want to create!! Image Proto type So, please any ideas or how can solve this kind of problem? Thank you in advance !! -
How do I setup Django Allauth with the new Sign in With Google?
Recently I realize that there is a signin with google that easier to use: no redirect to Google Singin page. For example the below Sign to Kayak with Google will popup kinda seamlessly when I open kayak.com I usually use django-allauth for social signin: but I think it still use the old Google Login UX. So, how do I use this new Sign int With Google using Allauth? -
Django Class Based View (update view)
I want to update the labels of images using Update view(Class-based-views). I can update labels of one image at a time but I would like to update labels of multiple images at once. Will passing a list of Image IDs to update view work? (How to pass a list of ids in Url pattern?) Can someone please help me with the methods I should be using in update view?? Here is my models.py class DataFile(models.Model): projectinfo= models.ForeignKey(ProjectInfo, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) label = models.ForeignKey( LabelName, on_delete=models.SET_NULL, null=True, blank=True ) def __str__(self): return str(self.label) if self.label else '' -
Django list class instances matching parent
I'm new to Django, so any help is appreciated. I have one class Gym and a second class Route (rock climbing gym and climbing routes). Each gym can contain multiple routes, but each route can only belong to one gym. I can list available gyms and click on one to go to the gym page, but I want to list all of the routes that belong to it and can't figure out how. # /gym/models.py from django.db import models from django.shortcuts import reverse class Gym(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='gym', default='default_route.jpg') address = models.CharField(max_length=200) def get_absolute_url(self): return reverse('gym:detail', kwargs={'pk': self.pk}) def __str__(self): return self.name # route/models.py from django.db import models from .utils import generate_qrcode class Route(models.Model): Gym = models.ForeignKey('gym.Gym', on_delete=models.CASCADE, null=True) grade = models.CharField(max_length=10) hold_color = models.CharField(max_length=20, default='') rating = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='routes', default='default_route.jpg') def __str__(self): return str(self.pk) # gym/views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from .models import Gym from route.models import Route def gym_list_view(request): # Can filter this for specific gyms qs = Gym.objects.all() return render(request, 'gym/index.html', {'gym_list': qs}) def gym_detail_view(request, pk): gym_obj = Gym.objects.get(pk=pk) # This is where I don't know how to get the routes that belong … -
How to filter a table based on data from another table
there are three tables: class Course(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) start_date = models.CharField(max_length=255) end_date = models.CharField(max_length=255) def get_count_student(self): count = CourseParticipant.objects.filter(course=self.id) return len(count) def __str__(self): return f'{self.name}' class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) def __str__(self): return f'{self.first_name}' class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='course', on_delete=models.CASCADE) student = models.ForeignKey(Student, related_name='student', on_delete=models.CASCADE) completed = models.BooleanField(default=False) I want to get students who do not participate in specific courses, I fulfill the following request potential = Student.objects.exclude(courseparticipants__course=pk) where in pk I indicate the id of the course, in response I get: django.core.exceptions.FieldError: Cannot resolve keyword 'courseparticipants' into field. Choices are: email, first_name, id, last_name, student -
How can I save the name of the selected option?
How can I save the name of the selected option in a select input? If i select plan and i sumbit i want to in select option stay plan option not selected option. <form method="get"> <!-- filtro por carpeta --> <label for="carpeta">Carpeta</label> <select id="carpeta" class="form-control" name="carpeta"> <option disabled selected>Selecciona una opcion</option> <option>Plan</option> <option>Gestion</option> </select> <br /> {% block buscador %} Nombre:<br /> <input class="form-control" type="text" value="{{ request.GET.buscar }}" name="buscar" /> <br /> {% endblock buscador %} <!-- fin filtro por carpeta --> <button type="submit" class="btn btn-primary btn-sm">Buscar</button> </form> -
POST request does not writes data to field from another model
Hello Guys, Huge Respect for all devs I have one model called field in one app, and I connected this field with the model in the same and from another app. User and Course models. User model is from usersapp. In this model, I am trying to make sign up on API, but if send data in array type, It is not written. It shows empty array in admin panel. How can I write this here is my models.py file from users app from django.db import models from courses.models import Field from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, first_name, password, **other_fields) def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=32 , verbose_name="Login", unique=True, ) email = models.EmailField(unique=True) first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False) second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False) # … -
How to create a system used in facebook, linked in that suggest a friend or connection to connect
How to create a system used in facebook, linked in that suggest a friend or connection to connect I need to do it using python and django -
Django - Cannot query username, must be instance of Tagulous_Post_season
Good afternoon everyone, I'm just wondering if anyone could provide any guidance or tips on how to resolve the following error: Cannot query [username], Must be instance of Tagulous_Post_season I am trying to return two different filters within my PostListView class but when attempting to get the list of Tagulous tags which have been assigned my user's previous posts, I am getting an error as quoted above. Views.py class PostListView(LoginRequiredMixin, ListView): model = Post template_name = 'core/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = PAGINATION_COUNT def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) all_users = [] data_counter = Post.objects.values('author')\ .annotate(author_count=Count('author'))\ .order_by('-author_count')[:6] for aux in data_counter: all_users.append(User.objects.filter(pk=aux['author']).first()) # if Preference.objects.get(user = self.request.user): # data['preference'] = True # else: # data['preference'] = False data['preference'] = Preference.objects.all() # print(Preference.objects.get(user= self.request.user)) data['all_users'] = all_users print(all_users, file=sys.stderr) return data def get_queryset(self): user = self.request.user qs = Follow.objects.filter(user=user) follows = [user] instance = Post() #taguser = Post.objects.filter(season=self.request.user) taguser = Post.season.tag_model.objects.all() for obj in qs: follows.append(obj.follow_user) return Post.objects.filter(author__in=follows).filter(season__author=user).order_by('-date_posted') Models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.png', upload_to='srv_media') author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) title = tagulous.models.SingleTagField(initial="Mr, Mrs, Miss, Ms") season = tagulous.models.TagField( autocomplete_view='swaptags_season_autocomplete' ) def __str__(self): return self.content[:5] img = Image.open(self.image.path) if …