Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to filter on data belonging to the logged in user (Django)
First of all; I'm fairly new to Django. Right now, I'm trying to create a very simple webpage with links (just to learn). The idea right now is, that a user (which is logged in) can add links to the database/model, and only see the links of which he has added. I'm strugling to figure out what the best practice is for that - is it to store the user.username in the model, and then make a .filter(username=user) each time or..? I would assume Django has some (faster way) of handling this. I have the following models.py from django.db import models from django.contrib.auth.models import User class links(models.Model): link = models.URLField() #user = <something_here> views.py def add_link(request): if request.method == "POST": form = add_link_form(request.POST) if form.is_valid(): messages.success(request, "Link is added!") form.save() return redirect("my_links") else: form = add_link_form() context = { "links":links.objects.all(), "form":form } return render(request, "django_project/my_links.html",context=context) my_links.html {% extends "django_project/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} {{form|crispy}} <div class="form-group"> <button class="btn btn-outline-info" type="submit">Add link</button> </div> </form> {% for l in links%} {{l.link}} {% endfor%} {% endblock content %} -
How to send an email with quoted-printable using django
I'm trying to send an email with quoted-printable encoding, but I can't seem to figure out the django mailer. I'm using EmailMultiAlternatives and am trying to attach the html. I've found this answer: Python send email with "quoted-printable" transfer-encoding and "utf-8" content-encoding but I can't figure out the equivalent for the django libraries. -
Error while trying to follow the users in Django
I have error while I trying to follow users, when I click the follow button in some user else profile it's should be I follow him, but the opposite happen he follow me but I'm not follow him My model class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True ,related_name="follow") The view class AddFollwers(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): account = Account.objects.get(pk=pk) account.following.add(request.user) return redirect('account:view', account.pk) class RemoveFollowers(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): account = Account.objects.get(pk=pk) account.following.remove(request.user) return redirect('account:view', account.pk) The urls path('follower/<int:pk>/add', AddFollwers.as_view(), name='add-follower'), path('follower/<int:pk>/remove', RemoveFollowers.as_view(), name='remove-follower'), The html template {% if username == request.user.username %} {% else %} {% if is_following %} <form action="{% url 'account:remove-follower' pk=id%}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger">Unfollow</button> </form> {% else %}<form action="{% url 'account:add-follower' pk=id%}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-success">Follow</button> </form> {% endif %} {% endif %} -
Onchange in select HTML, does not work (Django)
I have a Problems model. My Models models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA, 'NA'), (Easy, 'Easy'), (Medium, 'Medium'), (Hard, 'Hard'), ] .... name_problem = models.CharField(max_length=150) difficulty = models.CharField(max_length=150, choices=DIFFICULTY, default=NA) .... I have connected a django-filter My filters.py class ProductFilter(django_filters.FilterSet): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA, 'NA'), (Easy, 'Easy'), (Medium, 'Medium'), (Hard, 'Hard'), ] name_pr = django_filters.CharFilter(field_name='name_problem', lookup_expr='icontains') diff = django_filters.ChoiceFilter(field_name='difficulty' ,choices=DIFFICULTY) class Meta: model = Problems fields = ['name_pr', 'diff'] My views.py from .models import Problems from .filters import ProductFilter class MyProblemView(View): def get(self, request): problems = Problems.objects.all() filter = ProductFilter(request.GET, queryset=problems) problems = filter.qs context = { 'problems': problems, 'filter': filter, } return render(request, 'problems/problems.html', context) And finally html {% load static %} {% load widget_tweaks %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container"> <form action="/" name="form" method="get"> {{ filter.form.diff }} <input type="submit" /> </form> </div> {% for problem in problems %} <p id="text"> {{ problem.name_problem }} </p> {% endfor %} </body> </html> When there is a button in the form, it works … -
How to send json response in chunks in django rest framework?
I am working on a project Django rest framework in which I have to call 4 third-party APIs in my API class view and return the results. It works fine. But now I want API to return me the response immediately after executing each API's one by one like video streaming. class FraudDetection(APIView): permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication,) def post(self, request, format=None): serializer = FraudDetectorSerializer(data=request.data) if serializer.is_valid(): my_date = datetime.now() # '2020-07-13T23:18:21Z', time_stamp = my_date.strftime('%Y-%m-%dT%H:%M:%SZ') # 1st API CALL aws_full_output = fruad_detector(eventTimestamp1=time_stamp, billing_address=request.data['street1_address'], billing_postal=str(request.data['postal_code']), billing_state=request.data['state_code'], email_address=request.data[ 'email_address'], ip_address=request.data['ip_address'], phone_number=request.data['phone_number'], user_agent=request.data['user_agent']) # 2nd API CALL aws_minimal_output = fruad_detector2( eventTimestamp1=time_stamp, ip_address=request.data['ip_address'], email_address=request.data['email_address']) # 3rd API CALL ekata_phone_output = ekata_phone_api( phone_number=request.data["phone_number"]) # 4th API CALL ekata_address_output = ekata_address_api(street_line_1=request.data["street1_address"], street_line_2=request.data['street2_address'], city=request.data[ 'city'], postal_code=request.data['postal_code'], state_code=request.data['state_code'], country_code=request.data['country_code']) # 5th API CALL ekata_transaction_ouput = ekata_transaction_api(name=request.data['name'], street1=request.data['street1_address'], street2=request.data['street2_address'], city=request.data['city'], postal_code=request.data['postal_code'], state_code=request.data['state_code'], country_code=request.data['country_code'], phone_number=request.data['phone_number'], email=request.data['email_address'], ip_address=request.data["ip_address"], transaction_id=request.data['transaction_id'], transaction_time=request.data['transaction_time']) Result.objects.create(user=request.user, name=request.data['name'], street_1=request.data['street1_address'], street_2=request.data['street2_address'], city=request.data['city'], state_code=request.data['state_code'], postal_code=request.data['postal_code'], country_code=request.data['country_code'], email=request.data['email_address'], phone_number=request.data['phone_number'], ip_address=request.data['ip_address'], user_agent=request.data['user_agent'], transaction_id=request.data['transaction_id'], transaction_time=request.data['transaction_time'], output_aws_full=aws_full_output, output_aws_minimal=aws_minimal_output, output_ekata_phone=ekata_phone_output, output_ekata_address=ekata_address_output, output_ekata_transaction=ekata_transaction_ouput) outcome = {'first_detector_output': aws_full_output, 'second_detector_output': aws_minimal_output, 'third_detector_output': ekata_phone_output, 'fourth_detector_output': ekata_address_output, "fifth_detector_output": ekata_transaction_ouput} return Response(outcome, status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
how to join 2 dictionaries on same keys in python
I have 2 table of : form(id, label, name) and subform(subid, formID (f.k) , subname) In python, I'm trying to make a dictionary of join of these tables and i need a nested dictionary which for each id i could have another dictionary of subform(with related key),in format like: {form:{"id":"1" , "subid":"11", subname:"test"}, label:"testlabel" , name:"testname"} Do you know any solution to make this kind of Dictionary in python please? -
how to get the objects of specific field
Tn the following code the User.objects returns the "url","username","email","groups" from django.contrib.auth.models import User, Group class UserViewSet(viewsets.ModelViewSet): # TODO return only usernames and urls without emails for privacy purpeses # User.objects.username queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] But I also create the following model for the user avatar class TheUserProfiel(models.Model): TheUser = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(blank=True, null=True) personalityInformation = models.CharField( max_length=9999999, null=True, blank=True) created_date = models.DateTimeField(default=timezone.now) So, HOW to make the UserViewSet to return all of these "url","username","email","groups" in addition to the "avatar" field in the same view I tried before to create two views and to combine them in the frontend but it got very complicated. -
Attribute Error when attempting to create a model manager in Django
I am following the book Django By Example as a tutorial. I am trying to create a custom model manager following the steps in the book but I am having an issue where I am getting an AttributeError. My models.py file is the following: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, unique_for_date = 'publish') author = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'blog_posts') body = models.TextField() publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField (auto_now = True) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default = 'draft') class Meta: ordering = ('-publish',) def str(self): return self.title objects = models.Manager() # default manager published = PublishedManager() # customer manager Following the steps in the book I ran: >>> from blog.models import Post >>> Post.published.filter(title__startswith='Who') But following the second command I get the following AttributeError: AttributeError: 'PublishedManager' object has no attribute 'filter' I understand that I mustn't be defining 'filter' correctly but I am not sure how I do this in this scenario, … -
Messed up my Mac with excessive changes in terminal while debugging
I'm sort of a beginner on django and python, and, a year ago, I tried building a website with django, but messed up my terminal by doing a lot of debugging with 'sudo' and just being reckless in general. Now I'm trying to make another website with django, since I have a bit more experience with programming, but I'm wondering if there is a way to reset all my file locations and downloads from terminal -- or pretty much start over from scratch without having to restore my computer to factory settings? My main problems are with admin privileges and paths in a variety of different places, but I really don't think I could debug everything individually. -
what's the purpose of customizing django models
I read the following code for customizing Document model. class DocumentQuerySet(models.QuerySet): def pdfs(self): return self.filter(file_type='pdf') def smaller_than(self, size): return self.filter(size__lt=size) class DocumentManager(models.Manager): def get_queryset(self): return DocumentQuerySet(self.model, using=self._db) # Important! def pdfs(self): return self.get_queryset().pdfs() def smaller_than(self, size): return self.get_queryset().smaller_than(size) class Document(models.Model): name = models.CharField(max_length=30) size = models.PositiveIntegerField(default=0) file_type = models.CharField(max_length=10, blank=True) objects = DocumentManager() #overriding the default model manager Now suppose i want to retreive files of type pdf and size less than 1000. Then i need to do the following: Document.objects.pdfs().smaller_than(1000) But what's the use of doing this even when i could have simply obtained the desired result by filtering the default model manager 'objects' using the following command: Document.objects.filter(file_type='pdf', size__lt=1000) What is the difference in the execution of above two commands? -
Default Image for ImageField
Hi I'm trying to set up a default image for a ToDo List in Django. I have a the images under static/images. Now I'm trying to add a function where you can add tasks. in thid function I can choose a image. If no image is chosen, the image will become a default image ex. Placeholder.png I tried creating a if else loop in models.py but that does not work either. Showing chosen images does work. models.py: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() description = models.CharField(max_length=255, null=True) image = models.ImageField(null=True, blank=True) technologie = models.CharField(max_length=255, null=True) def __str__(self): return self.name @property def imageURL(self): if self.image: return self.image.url else: return "static/images/Placeholder.png" Now my question is how can I set Placeholder.png from the static directory as a default for ImageField? -
How to make an Youtube Like Subscriber model with Django
I think the title is rather self-explanatory, but I’ll explain. On YouTube, you are able to subscribe to users and you can see how many subscribers an user has. I like this idea, and I want to make this in Django, but have no clue how. Please tell me how, and show me all the code I will need. -
NoReverseMatch at /purchase_form/ Reverse for 'purchase_form' not found. 'purchase_form' is not a valid view function or pattern name
#models.py from django.db import models from django.utils import timezone from django.urls import reverse,reverse_lazy,resolve # Create your models here. class Purchase(models.Model): purchase_date = models.DateField() components = models.ForeignKey(Components,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() remarks = models.TextField(max_length=500,blank=True,null=True) def __str__(self): return str(self.pk) #views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import (View, ListView, DetailView, CreateView, UpdateView, DeleteView) from myinventory.models import Purchase # Create your views here. class PurchaseCreateView(CreateView): model = Purchase fields = '__all__' success_url = reverse_lazy("purchase_form") def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['purchases'] = Purchase.objects.all() return context project urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('myinventory.urls','myinventory')), ] app urls.py from django.urls import path,reverse_lazy from django.views.generic import CreateView from myinventory import views app_name = 'myinventory' urlpatterns = [ path('purchase_form/', views.PurchaseCreateView.as_view(),name="purchase_form"), ] purchase_form.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Purchase</title> </head> <body> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> {% for purchase in purchases %} <h2>{{ purchase.purchase_date }}</h2> <h2>{{ purchase.components }}</h2> <h2>{{ purchase.quantity }}</h2> <h2>{{ purchase.remarks }}</h2> {% endfor %} </form> </body> </html> admin.py from django.contrib import admin from myinventory.models import * # Register your models here. admin.site.register(Purchase) Traceback I'm getting following error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/purchase_form/ Django Version: 3.1.7 Python … -
drf is responding "Method \"GET\" not allowed
Here is my views.py '@api_view(['GET']) @permission_classes((permissions.AllowAny,)) def hnid(request, user_id): if request.method == 'GET': try: user = HNUsers.objects.get(user__id=user_id) return Response({'existing': True}, status=status.HTTP_200_OK) except HNUsers.DoesNotExist: return Response({'existing': False}, status=status.HTTP_200_OK)' and my urls.py url(r'^newusers/retrive/(?P<user_id>.+)', hnid), although it seems there's nothing wrong there( Atleast to my knowledge ) but while trying to get throu POSTMAN I am getting following Any help regarding this will be much appreciated -
Pass variable to view Django
Im pretty new to django. I have created an website that outputs data from an API to an table in django. I created an app called 'display_networks'. Inside the views.py of this app i have the following code: from django.shortcuts import render from django.views.generic import TemplateView from .services import get_networks # Create your views here. class GetNetworks(TemplateView): template_name = 'networks.html' #context == dict def get_context_data(self, *args, **kwargs): context = { 'networks' : get_networks(), } return context As you can see i import an function called 'get_networks' from .services (services.py). Inside services.py i have the following code: import os import requests import json # Headers apikey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' headers = {'x-cisco-meraki-api-key': format(str(apikey)), 'Content-Type': 'application/json'} # Headers def get_networks(): url = 'https://api.meraki.com/api/v0/organizations/XXXXX/networks/' r = requests.get(url,headers=headers) networks = r.json() return networks Inside my app i have created a templates folder with an index.html. Inside this index.html i have the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Meraki Networks</title> <link crossorigin="anonymous" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css" integrity="sha256-8B1OaG0zT7uYA572S2xOxWACq9NXYPQ+U5kHPV1bJN4=" rel="stylesheet"/> <link rel="shortcut icon" type="image/png"/> </head> <body> <nav aria-label="main navigation" class="navbar is-light" role="navigation"> <div class="navbar-brand"> <div class="navbar-item"> <img alt="Meraki" src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Meraki_Logo_2016.svg/1920px-Meraki_Logo_2016.svg.png" style="margin-right: 0.5em;" width="142" height="142">Networks </div> </div> </nav> <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth"> <thead> <tr> <th>Network Name</th> <th>Network … -
How to import a function from a file which is outside the directory
├── apps │ ├── package1 │ ├── directory 1 │ │ ├── demo1.py │ │ └── demo2.py └ └── test1.py └ └── test2.py (def function2) here i need to access function2 in test2.py, and use it in demo2.py it will look like in demo.py file as below from test2 import function2 and got an following error ImportError: cannot import name 'function2' from 'test2' -
wagtail svg in html template not rendering
Seems like such a basic question but I have put wagtails svg uploader into a separate block outside of the body, everything working as it should but when I save and preview nothing is showing up? In my model: svg_img = models.ForeignKey( Svg, related_name='+', null=True, on_delete=models.SET_NULL, blank=True ) content_panels = Page.content_panels + [ FieldPanel('introduction', classname="full"), StreamFieldPanel('body'), SvgChooserPanel('svg_img'), ] As for the HTML: {% if page.svg_img %} <li> <h4>Origin</h4> {{ page.svg_img }} </li> {% endif %} It returns None even though I have uploaded an svg? Any Ideas anyone? -
Embed PDF in Django template
I am trying to embed a pdf in a Django template. I am using the same way we are embedding an image in django. It`s seems that the file cannot be found. Is there a different way to display it? Many Thanks views.py class BillDetailView(generic.DetailView): model = Bill template_name = 'accounting/bills/bill_detail.html' models.py class BillFile(models.Model): bill = models.ForeignKey(Bill,on_delete=models.CASCADE, blank=True, null=True, unique=False) bill_file = models.FileField(upload_to='media/bill_files/', default='bill_files/default_id.jpg', blank =True) bill_detail.html <div class="card-block"> {% if billfile.bill_file %} <div class="top-right"></div> <!-- Option 1 --> <embed src="{{ billfile.bill_file.url }}" width = "200" height = "240" style =" margin-left: auto; margin-right: auto; display: block;">Click me</a> <!-- Option 2 --> <iframe src="{{ billfile.bill_file.url }}" style="width: 100%;height: 100%;border: none;"></iframe> <!-- Option 3 --> <a href="{% static '{{ billfile.bill_file }}' %}">Click me</a> {% else %} <h3>There is no file to display</h3> {% endif %} </div> -
Dockerized postgres restarts `postgres` user password
I’m running web app and postgres in docker containers inside VM and every once in a little while postgres docker resets user password but data remains. This makes application fails calling postgres db. I’d have to access ssh and run ALTER USER postgres WITH PASSWORD ‘postgres’; to fix it every time them it’d run fine for a day or two sometimes more. Here is the log before the error occurs: https://imgur.com/FxwiDMY Has anyone seen any similar problems or any idea what’s going on? My docker-compose.yml : version: '3.4' services: postgres: image: postgres:latest environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres volumes: - db-data:/var/lib/postgresql/data ports: - ${POSTGRES_PORT:-5432}:${POSTGRES_PORT:-5432} redis: ... web: ... volumes: db-data: driver: local EDIT: I copied wording from here since this was exactly the same problem I am facing. https://www.digitalocean.com/community/questions/postgres-docker-in-droplet-resets-user-password-on-its-own -
forien key in django model
I have 2 error in my code : ValueError: invalid literal for int() with base 10: 'cream' and ValueError: Field 'id' expected a number but got 'cream'. and my code contains : class Colors(models.Model): color_code = models.IntegerField(unique=True, blank=True, null=True, verbose_name = ' ') color = models.CharField(max_length=50, blank=True, null=True, verbose_name = '') class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return self.color and class Product(models.Model): product = models.CharField(max_length=6, choices=PRODUCT_CHOICES,) ... number = models.ForeignKey("Numbers", related_name="numbers", blank=True, null=True, on_delete=models.CASCADE, verbose_name="") color = models.ForeignKey("Colors", related_name='colors', blank=True, null=True, on_delete=models.CASCADE, verbose_name="") size = models.ForeignKey("Sizes", related_name='sizes', blank=True, null=True, on_delete=models.CASCADE, verbose_name="") what is my mistake? -
How to set a custom session element in Django when using django.contrib.auth.urls
I am looking for an elegant way to add a custom session element (variable) after logging a user in. Currently I am using the default URLs with custom templates. urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), ] Is there any way to do this without writing a custom AuthBackend or extending the Middleware? Ideas are appreciated. -
Getting a reverse match Django issue
I'm getting a NoReverseMatch error: NoReverseMatch at / Reverse for 'post-detail' with arguments '(22, '')' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/$'] not sure how to fix this, here is some of the code : urls.py urlpatterns=[ path('', PostListView.as_view(), name='home'), path('post/new/<slug:slug>/', views.create_post, name='post-create'), path('post/<int:pk>/<slug:slug>/', views.post_detail, name='post-detail'), path('like/<slug:slug>/', views.like, name='post-like'), path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/<slug:slug>/delete/', views.post_delete, name='post-delete'), path('search_posts/', views.search_posts, name='search_posts'), models.py class Post(models.Model): description = models.TextField(max_length=255) pic = models.ImageField(upload_to='path/to/img', blank=True) date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) def __str__(self): return self.description def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk, 'slug': self.user_name.profile.slug}) views.py @login_required def post_detail(request, pk, slug): post = get_object_or_404(Post, pk=pk) user = request.user is_liked = Like.objects.filter(user=user, post=post) if request.method == 'POST': form = NewCommentForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.post = post data.username = user data.save() return redirect('post-detail', pk=pk, slug=slug) else: form = NewCommentForm() return render(request, 'feed/post_detail.html', {'post':post, 'is_liked':is_liked, 'form':form}) -
Authorize against Jira and Bitbucket api with Django ldap
I have written a webservice with Django to communicate with Jira and Bitbucket to retrieve pull requests from their apis. Due to security reasons I'm not storing any user credentials which forces the user to enter their credentials every time the webservice need communicate with the apis. This seems like a bad solution. Can this authentication against the apis be accomplished using LDAP against the company Active Directory servers? The optimal result would be to have the user log in to the webservice once. Thank you -
Django: Unsupported lookup 'following' for CharField or join on the field not permitted
I try to build follow system, when I tried to let the users see the posts of the users which that follow them I got error Unsupported lookup 'following' for CharField or join on the field not permitted The profiles model class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True ,related_name="follow") The posts model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to='post-videos') title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) my view class home_screen_view(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): logged_in_user = request.user post = Video.objects.filter( author__username__following__in=[logged_in_user.id] ).order_by('-created_date') context = { 'post_list': post, } return render(request, "personal/home.html", context) -
Django printing tags on screen
I am trying to print products list on to screen {% for product in product_list %} {% include 'home/new-products.html' with product = product %} {% endfor %} But it directly showing tag onto screen Any idea what's going wrong here?