Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django python google distance matrix api json question
so, I'm new to python and Django. I created a view and html page for a very basic form that uses the google distance matrix api. I'm able to display the output of the json back to my html page without any issues. the question is, how do I get the distance in miles to appear on my html page. Right now I'm just getting the raw json. but I can't seem to get just the distance in miles. Current output from the HTML page: origin ['660 Celebration Ave, Celebration, FL 34747, USA'] destination ['878 Columbus Ave, New York, NY 10023, USA'] distance in miles: [{'elements': [{'distance': {'text': '1,093 mi', 'value': 1759428}, 'duration': {'text': '16 hours 13 mins', 'value': 58364}, 'status': 'OK'}]}] ''' views.py def mapdistance_view(request): distance = {} if 'From' in request.GET: origin = request.GET['From'] destination = request.GET['To'] apikey = "mykey" url = 'https://maps.googleapis.com/maps/api/distancematrix/json?mode=driving&units=imperial&origins=' + origin + ',DC&destinations=' + destination + ',' + apikey response = requests.get(url) distance = response.json() print(url) print(distance) return render(request, 'mapdistance.html', {'distance': distance}) ''' Html page ''' {% block content %} <h2>map API</h2> <form method="GET"> {% csrf_token %} <label>Pickup Location:</label><input type="text" name="From"><br> <label>Delivery Location:</label><input type="text" name="To"><br> <button type="submit">post to google map</button> </form> {% if distance … -
django channels - delayed messaging does not work
I am trying to imitate a time consuming django response, by delaying group message in Django channels, but it does not work. The consumer is very simple: class ExportConsumer(JsonWebsocketConsumer): ... def delayed_message(self, event): print("In delayed") time.sleep(5) self.send(text_data=json.dumps({ 'message': 'delayed!' })) def immediate_message(self, event): print("In Immediate") self.send(text_data=json.dumps({ 'message': 'immediate_message!' })) and in views I just send to a group two messages - for delayed and immediate processing: class DecisionListView(PaginatedListView): ... def get(self, *args, **kwargs): async_to_sync(get_channel_layer().group_send)( '5e001793-18be-4a4b-8caf-c4a8144a11d2', { 'type': 'immediate_message', 'message': 'message' } ) async_to_sync(get_channel_layer().group_send)( '5e001793-18be-4a4b-8caf-c4a8144a11d2', { 'type': 'delayed_message', 'message': 'message' } ) return super().get(*args, **kwargs) The 'immediate message' is delivered. And I get In delayed on terminal (which means that it reaches the delayed_message but the message is never delivered (unless I comment out time.sleep. What am I doing wrong? -
Python Django Interaction between users. Asking for Directions
I am a Beginner so please be kind and forgive me for not being able to use the english language correctly. Anyway, I have a blog of posts. Every user can create posts. I want to make it so any user can send any of his/her posts to another user and get as a result a comment for that post. I do not have any code to show for this as i have not any idea how to even approach this. All i ask is some directions to any Documentation or tutorials where i can dig in and learn about this. I thank all in advance and Good Luck to Everyone. -
Django QuerySet Any
I want to get a queryset of all books that are currently in Library (the dateReturn of a currently rent is set to null). I'm new to python and i don't know how to do subqueries in django. In other words in want to filter every related object field on a condition, if only one related-object doesn't match to this condition the object must not be returned models.py class Book(models.Model): cod = models.CharField(max_length=255, unique=True) title = models.CharField(max_length=255) ..... class Rent(models.Model): dateRent = models.DateField(default=timezone.now) dateReturn = models.DateField(null=True, blank=True) book = models.ForeignKey(modelsBook.Book, on_delete=models.DO_NOTHING, related_name="rent") ..... P.S: I need this subquery for display book currently not render in a choiceField forms.py class RentForm(forms.ModelForm): __pk=None def __init__(self, *args, **kwargs): self.__pk = kwargs.pop('pk', None) super(RentForm, self).__init__(*args, **kwargs) class Meta(): model = models.Rent fields = ('book', 'student') labels = { 'book' : _('Libro'), 'student' : _('Studente'), } widgets = { 'book': queryset, ..... -
django database router not writing to database
I have configured the below database router but once I run it the output indicated success but the tables do not appear in the database. I have tried walking through the code in debug mode but cannot figure out why it won't write to my custom db router. I have changed the config so that my default db router uses the config of the new router and the default django tables are created. So this proves I can connect and write to my default and custom db router. my project structure: ├── django_app │ ├── manage.py │ ├── package.json │ ├── __pycache__ │ ├── requirements.txt │ └── zoho_integration │ ├── apps │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── quoting │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── serializers.py │ │ ├── static │ │ │ └── quoting │ │ │ ├── css │ │ │ │ └── index_style.css │ │ │ └── js │ │ │ └── product_selection.js … -
adding input to form by button django
I want to add new input in page when user clicks button. I wasn't really sure how to do it. I found some tutorial on google and came up with that: forms.py class CreateChoiceForm(forms.ModelForm): class Meta: model = Question fields = ['question_text',] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(CreateChoiceForm, self).__init__(*args, **kwargs) choices = Choice.objects.filter( question=self.instance ) for i in range(len(choices) + 1): field_name = 'choice_%s' % (i,) self.fields[field_name] = forms.CharField(required=False) try: self.initial[field_name] = choices[i].choice except IndexError: self.initial[field_name] = "" field_name = 'choice_%s' % (i+1,) self.fields[field_name] = forms.CharField(required=False) def clean(self): choices = set() i = 0 field_name = 'choice_%s' % (i,) while self.cleaned_data.get(field_name): choice = self.cleaned_data[field_name] if choice in choices: self.add_error(field_name, 'Duplicate') else: choices.add(choice) i += 1 field_name = 'choice_%s' % (i,) self.cleaned_data['choices'] = choices def save(self): question = self.instance question.question_text = self.cleaned_data['question_text'] question.author = self.request.user question.save() question.choice_set.all().delete for choice in self.cleaned_data['choices']: Choice.objects.create(question=question, choice_text=choice) def get_choice_fields(self): for field_name in self.fields: if field_name.startswith('choice_'): yield self[field_name] The problem is that i don't know what to do from here. If i add new input in my page by simply copy the other input with js and changing id and name incrementation, only first two inputs will save and others won't. Here is the … -
Django - How to fix model with id field
I unintentionally created a model with a field "id" and did the migration. The model at first looked like this: class VsSession(models.Model): id = models.TextField(default="123"), state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10) Afterwards I rename the field to vs_session: class VsSession(models.Model): vs_session = models.TextField(default="123"), state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10) Now whenever I try to use the model e.g., like this: def get(self, request): try: sessionid = uuid.uuid4() new_session = VsSession(vs_session=sessionid, state="active") new_session.save() return Response({'success': 'true', 'vssession': sessionid}) except Exception as e: print(str(e)) return Response({'success': 'false'}) I get this error: VsSession() got an unexpected keyword argument 'vs_session' Can anybody please tell me what I did wrong and how to fix this. Thank you very much! -
Can I perform queries in Django where both the LHS and RHS are a function?
I'd like to perform queries in Django where both the left-hand-side and right-hand-side are a function. As simple example, something like: SELECT * FROM table WHERE LCASE(field1) = LOWER(field2) Is this possible using the QuerySet.filter(..) or Q(..) objects API? -
Add the second records into the model return ""Column 'created_at' cannot be null""
I have a problem with the following model class TagBuyer(CreatedatModelStaff): id = models.UUIDField( primary_key=True, default=DEF_UUID, editable=False) buyer = models.ForeignKey( Buyer, on_delete=models.SET(DEF_UUID), ) tag = models.OneToOneField( Tag, on_delete = models.SET(DEF_UUID), blank=True, to_field='unique_id', ) description = models.CharField( blank=True, null=True, max_length=256, help_text=_('Observatii:'), ) objects = models.Manager() # The default manager. active_objects = IsActiveManager() # Select only active records class Meta: verbose_name = _('Cumparator TAG') verbose_name_plural = _('Cumparatori TAG-uri') def __str__(self): return str(self.tag) class CreatedatModelUser(BaseCreateModel): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, verbose_name=(_("Ultima modificare")), ) class Meta: abstract = True class BaseCreateModel(models.Model): """ Abstact class for common model atributes """ created_at = models.DateTimeField( verbose_name=(_("Creat la")), auto_now_add=True, ) last_change = models.DateTimeField( verbose_name=(_("Ultima modificare")), auto_now=True, ) is_active = models.BooleanField( default=True, help_text= _('Modelul de tiparire este disponibil pentru tiparire'), ) class Meta: abstract = True First insert works good from django admin and from my view. Problem popup with the second record. django admin return "Column 'created_at' cannot be null" my view actually perform an update of the first record ''' class BuyerAddTagPopupView(LoginRequiredMixin, CreateView): template_name = 'buyer/popup/buyer_add_tag.html' readonly_fields = ['buyer'] def get(self, request, slug=None): if request.user.is_authenticated: form = BuyerAddTagForm() try: buyer_obj = Buyer.active_objects.get(slug=slug) except Buyer.DoesNotExist: ## args = { 'msg': msg, 'form':form, 'page_title':self.title, 'gargs':self.gargs, } return render(request, self.template_name, … -
How to create a django model for JSONField that takes values from other fields from the same table?
I am writing a model in django which looks like this: name = models.CharField(max_length=50) address = models.CharField(max_length=100) info = JSONField() Question: For POST request, I will provide name and address as json. Now how should I store name and address in their respective fields and store json data i.e. "name:{...},address:{...}" and store it into info field? -
How to fetch date to output in a form in Django?
I have a flight model, which has a date field. I am creating an update form and, so far, it works. But, I also want it to show the already stored values. I can show every value but the date. This is my forms.py: class UpdateFlight(ModelForm): def __init__(self, *args, **kwargs): super(UpdateFlight, self).__init__(*args, **kwargs) self.fields['date'].widget = forms.DateTimeInput(attrs={'class': 'form-control', 'data-target': '#datetimepicker1'}) self.fields['flight_id'].widget = TextInput(attrs={'class': 'form-control'}) class Meta: model = Flight fields = ('date', 'flight_id', 'company', 'airport') This is my views.py: @login_required(login_url='../accounts/login/') def flight_upd(request, id): fs = Flight.objects.get(id=id) if request.method == 'POST': form = UpdateFlight(request.POST, instance=fs) if form.is_valid(): form.save() return redirect('flights') else: form = UpdateFlight(initial={'date': fs.date, 'flight_id': fs.flight_id, 'company': fs.company, 'airport': fs.airport}) return render(request, 'backend/flight_update.html', {'form': form, 'fs': fs}) And this is my html file: <div class="col-lg-3"> <label class="form-control-label" for="input-first-name">Data</label> <div class="input-group date" id="datetimepicker1"> {{form.date}} <span class="input-group-addon input-group-append"> <button class="btn btn-outline-primary" type="button" id="button-addon2"> <span class="fa fa-calendar"></span></button> </span> </div> </div> -
How to access to dictionary value via variables in another list in Django
I have this situation in my views.py d = {'05:45':3,'06:30':6 (...) } T = ['05:45','06:30' (...)] I would like to get d[T[i]] in my HTML site I tried to call this with dot, but it doesn't work. I will be thankful for help/hint. -
Invalid syntax urls.py
I'm doing a project with Django, when i start my site i see a error message that says: invalid syntax. here is the source codes: urls.py: from django.urls import path from my_app import views as post_views urlpatterns = [ path(r'^',posts_views.lista_post, name="lista") path(r'^',posts_views.post_singolo, name="singolo") #here is the error path(r'^',posts_views.contatti, name="contatti") #also here ] views.py: from django.shortcuts import render # Create your views here. def post_singolo(request): return render(request,"post_singolo.html") def lista_post(request): return render(request,"Lista_post.html") def contatti(request): return render(request,"Contatti.html") Please help me, i can't see the problem -
Populating a dropdown with a django variable after AJAX call
I have a dropdown that triggers an AJAX call when a new value is selected. The AJAX script calls my Django view, which returns a variable (a list of values). It seems to work until the step where I need to fill a second dropdown with the values from that list. I couldn't figure out how to do this. Here is my html code: <form class="wrapper" action="" method="post"> {% csrf_token %} <select name="myVal" class="toChange"> <option val="1">1</option> <option val="2">2</option> </select> <select id="dep" name="dep"> </select> <script type="text/javascript"> function dropdownChange () { var selectedValue = $(".toChange option:selected").val(); $.ajax({ url: '/myApp/templates/3/', type: 'POST', data: {'myVal': selectedValue}, success: function(result) { alert(result); } }); } $(".toChange").change(dropdownChange); </script> </form> And here is my views.py file: @csrf_exempt def MyView3(request): if request.method == 'POST' and request.is_ajax: myVariable = json.dumps(["1", "2", "3", "4", "a"]) return HttpResponse(myVariable , content_type='application/json') else: return render(request,'home3.html') When I select a new value in my dropdown, it triggers the AJAX call and the alert(result) line returns "1,2,3,4,a". So this part works, but I don't know how to populate with these values my "dep" dropdown. I've been trying to insert the following code in the script, but it didn't produce any results: var select = document.getElementById("dep"); var … -
Submit Button and Preview Button In Same View (Django)
Here's my situation. I have one view which displays a form for the user to fill out. The html contains two buttons, one for 'Submit' and one for 'Preview'. My intention is that the 'Submit' option would truly save and commit the form, whereas the 'Preview' option would launch a PDF preview of whatever data has currently been entered into the form. I am able to make each work one at a time (i.e. submit function works and preview doesn't or preview function works and submit doesn't). Also I want 'Submit' to work only if the form is valid, but preview could work even if it is not. How can I have two buttons in the same view execute different logic? Maybe I need to change one of my <button> to an <a> and launch another view? Here's my code: Views.py (not behaving the way I way would like) def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): request.session['data'] = form.cleaned_data #passing data to view which generates pdf form.save() return redirect('myview') else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) class myview(View): def get(self, request, *args, **kwargs): data = request.session.pop('data', {}) pdf = render_to_pdf('packlist_preview.html', data) return HttpResponse(pdf, content_type='application/pdf') … -
How to remove all connections from a group in channel layer | Django Channels
I want to use the channels groups as a lobby system for a game and when the game ends, remove everyone from the lobby but I'm unsure how to 1) iterate through users in the group, 2) remove all users or delete the group in total. -
File sharing and editing between users (google drive) in Django
How can I create a Django app where a user can create a document which the user can share with other users to read/write just like google docs. I found that WYSIWYG editors in Django where it enables the user to write content in the web browser. -
How to enable the users delete and edit comments they create in Django?
I am currently working on a blog app in django. I have almost done with it, but it is hard to deal with comments. Comments are posted but I do not know how to delete or edit it by the creators. models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = HTMLField() date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #featured = models.BooleanField() #categories = models.ManyToManyField(Category) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={ 'id': self.id, 'title': self.title }) @property def get_comments(self): return self.comments.all().order_by('date_updated') @property def comment_count(self): return Comment.objects.filter(blogpost=self).count() @property def view_count(self): return PostView.objects.filter(blogpost=self).count() class Comment(models.Model): content = models.TextField(max_length=5000, null=False, blank=False) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blogpost = models.ForeignKey('BlogPost', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.author.username class PostView(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey('BlogPost', on_delete=models.CASCADE) def __str__(self): return self.user.username The model above goes to the html below. detail_blog.html {% extends 'base.html' %} {% block content %} <style type="text/css"> .card{ max-width: 700px; } .card-body{ padding: 20px; } </style> <div class="container"> <div class="row"> <!-- Blog Post --> <div class="card m-auto"> <div class="card-body mt-2 mb-2"> <h2 class="card-title">{{blog_post.title}}</h2> <p class="card-text">{{blog_post.body|safe}}</p> {% if blog_post.author == request.user %} <a href="{% … -
Is there a way for logged in user to store the database in their own account in django?
I am working on a django project to store my daily expenses. models.py: class BudgetInfo(models.Model): items= models.CharField(max_length=20) cost= models.FloatField(blank=False, null=True) date_added= models.DateField() user= models.ForeignKey(User, on_delete= models.CASCADE) view.py: def login_view(request): if request.method == 'POST': form= AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) return render (request, 'tasks_notes/index.html') def additem_view(request): name = request.POST['expense_name'] expense_cost = request.POST['cost'] expense_date = request.POST['expense_date'] create=BudgetInfo.objects.create(user= request.user,items=name,cost=expense_cost,date_added=expense_date) create.save() return redirect('app') def signup_view(request): if request.method == 'POST': form= RegisterationForm(request.POST) if form.is_valid(): user=form.save() login(request,user) return redirect('login') else: form=RegisterationForm() return render(request, 'tasks_notes/signup.html',{'form':form}) forms.py: class RegisterationForm(UserCreationForm): email=forms.EmailField(required=True) class Meta: model=User fields=( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user=super(RegisterationForm, self).save(commit=False) user.first_name=self.cleaned_data['first_name'] user.last_name=self.cleaned_data['last_name'] user.email=self.cleaned_data['email'] if commit: user.save() return user I want to store the daily expense of each user in its own model. But every instance (even with the same user) is created whenever I am trying to save the data. I want a single instance of the model for each user. How can I achieve it? -
django: How can display in the same url form and table?
I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table. All works untill I assign two different urls for table and forms, but If I try to merge them togheter in the same url (utilizing so the same html file) django give me the following error: ValueError at / Expected table or queryset, not str Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.5 Exception Type: ValueError Exception Value: Expected table or queryset, not str Above my code in each file of my project: urls from django.urls import path from app import views urlpatterns = [ path('', views.homepage, name='homepage'), path('', views.PersonListView.as_view(), name='algo'), ] forms from django import forms from .models import Income class IncomeModelForm(forms.ModelForm): class Meta: model = Income fields = "__all__" tables import django_tables2 as tables from .models import Income class PersonTable(tables.Table): class Meta: model = Income template_name = "django_tables2/bootstrap.html" views from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from .models import Income from .tables import PersonTable from django_tables2 import SingleTableView from .forms import IncomeModelForm def homepage(request): if request.method == 'POST': form = IncomeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_post = form.save() … -
Python Django Linking problems
I am working on an online school project, I just linked subjects, with classes so when you click on a class you get it's subjects page, and in the subject page there are lessons playlist(playlist use IDs not slugs),in the playlist you will get a list of lessons My problem is at linking the lesson URL in the HTML page so my question is How to link lessons to lessons to the playlist in the HTML page? My codes: HTML PAGE: <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="/static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> <button class="bt1"><a href="/signup">انشاء حساب</a></button> </ul> </nav> {% for list in list.all %} <div class="div1"> <img src="/static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">{{list.title}}</h1> </div> <li><a href="#"> HelloWorld </a></li> {%endfor%} {% for lesson in lesson._set.all %} <li><a href="{% url 'lessons' classes.id list.id lesson.id %}">World1</a></li> {% endfor %} </div> </body> </html> MODELS.py: from django.db import models from users.models import * # Create your models here. class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title … -
How to raise exceptions in Django view based in ORM exceptions
Instead of doing, for example this: views.py: my_noob_way(request): object = Object.objects.filter(name=request.POST.get('name', None)) if not object: Object.objects.create(name=request.POST.get('name', None)) data = {'success': True, 'message': 'Object successfully created.'} else: data = {'success': False, 'message': 'Object already exists.'} return JsonResponse(data) Instead of doing this, I want to avoid the filter line (extra garbage query) and just performing a create inside a try and catch the possible duplication exception with except. How can I make this? I don't know what to put after except: (Too broad exception clause). -
Nginx try_files not working with domain that appends trailing slash
I have a dockerised Django app where nginx uses proxy_pass to send requests to the Django backend. I am looking to pre-publish certain pages that dont change often so Django doesnt have to deal with them. I am trying to use try_files to check if that page exists locally and pass to Django if not. Our URL structure requires that all URLs end with a forward slash and we dont use file type suffixes e.g. a page might be www.example.com/hello/. This means the $uri param in nginx in this instance is /hello/ and when try_files looks at that it is expecting a directory due to the trailing slash. If I have a directory with a list of files how do I get try_files to look at them without re-writing the URL to remove the slash as Django requires it? My nginx conf is below. server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name example.com; root /home/testuser/example; location / { try_files $uri uri/ @site_root; } location @site_root { proxy_pass http://127.0.0.1:12345; } } If I have a file "hello" at /home/testuser/example/hello and call https://www.example.com/hello/ how can I get it to load the file correctly? P.S. the permissions on … -
Error in Channel library OSError: [WinError 123]
when i am installed "channels"library in settings.py at installed app i get this error plz anyone find my resolve error File "c:\program files (x86)\python38-32\Lib\pathlib.py", line 200, in resolve return self._ext_to_normal(_getfinalpathname(s)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
How to resolve a ManyRelatedManager error
While working with django 3.0, passing a context from the view to a template became confusing to me. I don't know whether there has been a change in the method. I did this in models.py from tinymce import HTMLField from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse user = get_user_model() class Author(models.Model): user = models.OneToOneField(user, on_delete=models.CASCADE) thumbnail = models.ImageField() def __str__(self): return "%s %s" % (self.user.username) class Category(models.Model): title = models.CharField(max_length=250) def __str__(self): return (self.title) class Post(models.Model): title = models.CharField(max_length=250) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() comment_count = models.IntegerField(default=0) view_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() def __str__(self): return self.title class Meta: verbose_name ='The post' verbose_name_plural = 'posts' def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id':self.id }) and this is the view.py file def post(request, id): post = get_object_or_404(Post, id=id) context = { 'post':post } return render(request, 'post.html', context ) and am getting this error TypeError at /post/1/ 'ManyRelatedManager' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/post/1/ Django Version: 3.0.4 Exception Type: TypeError Exception Value: 'ManyRelatedManager' object is not iterable what should i do