Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Default Image from ImageField wont show
I'm trying to simply display an Image from an ImageField within a template. class Profile(models.Model): img = models.ImageField(upload_to='profiles/profile_pictures', default="/profiles\profile_pictures\default_profile_picture.PNG") Django returns that the Image is not found: Not Found: /media/profiles/profile_pictures/default_profile_picture I've been looking to solve this for quite a while now and I can't seem to see why it won't show. I'added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urls.py also I've added MEDIA_ROOT and MEDIA_URL to my settings. # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' I've checked the paths multiple times now. The files definitely exist in the given path. What have I forgotten? -
Best practice to generate access token for api auth in django
I am very new to django and I am building a backend that authenticates user through access token. Currently I am generating token with sha1 with email and some random numbers. I am very new to programming and I am looking for best practice. What will be the best approach to generate access token. Also, I would be glad if someone guide me through refresh token and how to use it. If I generate the token it will only be used but what if I want to refresh token continously according to some time or on every login so that use dont get authenticated with same access token. -
django return the most recent record of each user
I am learning django framework, and currently I am facing a problem. There are two models class User(models.Model): name = models.CharField(max_length=30) ... class Action(models.Model): user = models.Foreign(User) action = models.CharField(max_length=30) createTime = models.DateTimeField(default=django.utils.timezone.now) Each action from each user is inserted into Action Model, therefore, there are lots of records of each user in Action by different createTime. Now, I would like to list the latest action of each user, but I have no idea to implement it. -
How to upload files into BinaryField using FileField widget in Django Admin?
I want to create a model Changelog and make it editable from Admin page. Here is how it is defined in models.py: class Changelog(models.Model): id = models.AutoField(primary_key=True, auto_created=True) title = models.TextField() description = models.TextField() link = models.TextField(null=True, blank=True) picture = models.BinaryField(null=True, blank=True) title and description are required, link and picture are optional. I wanted to keep this model as simple as possible, so I chose BinaryField over FileField. In this case I wouldn't need to worry about separate folder I need to backup, because DB will be self-contained (I don't need to store filename or any other attributes, just image content). I quickly realized, that Django Admin doesn't have a widget for BinaryField, so I tried to use widget for FileField. Here is what I did to accomplish that (admin.py): class ChangelogForm(forms.ModelForm): picture = forms.FileField(required=False) def save(self, commit=True): if self.cleaned_data.get('picture') is not None: data = self.cleaned_data['picture'].file.read() self.instance.picture = data return self.instance def save_m2m(self): # FIXME: this function is required by ModelAdmin, otherwise save process will fail pass class Meta: model = Changelog fields = ['title', 'description', 'link', 'picture'] class ChangelogAdmin(admin.ModelAdmin): form = ChangelogForm admin.site.register(Changelog, ChangelogAdmin) As you can see it is a bit hacky. You also can create you own … -
Django: one authentication backend per user model
in my Django application I need multiple type of Django users: 1. A typical admin user which is identified by email and authenticated with password. 2. A remote application which connects to django and authenticates with pre-shared key and tokens. The email is not required for such type of user. Every type of user has different associated attributes. I know that I can extend User model in Django. I already created email authentication backend. But this works for all the accounts, including the remote applications ones. Is there any effective way to create a auth backend for a type of user? -
Django domain forwarding
I have a Django site which will show different things depending on the subdomain visited. So you will see "A"-type things if you go to a.mysite.com but "B"-type things if you go to b.mysite.com. I do this by gathering the subdomain in the request and using that to filter. What I want to be able to do is allow any other domain to point at these subdomains (like, for instance, heroku can do) but still allow me to do the filtering in the above way. Is that possible? If so, how would I go about it? I assume that, if a user comes to my site on theirdomain.com (which points at a.mysite.com) then I won't have "a" in the subdomain so how do I know they want to see "A"-type things? -
Daphne not listening to websockets
I have a webapp written with django-channels+celery that uses websockets for client-server communication. After testing it running daphne, the celery worker and redis on my host machine I decide to encapsulate everything with docker-compose to have a deployable system. This is where the problems started. I managed to have it working after learning, tweaking and debugging my docler-compose.yaml but still I can't get websockets to work again. If I open a websocket and send a command, wether from inside the javascript part of the app, or from the javascript console in chrome, it never triggers the ws_connect nor the ws_receive consumers. This is my setup: settings.py # channels settings REDIS_HOST = os.environ['REDIS_HOST'] REDIS_URL = "redis://{}:6379".format(REDIS_HOST) CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { # "hosts": [os.environ.get('REDIS_HOST', 'redis://localhost:6379')], "hosts": [REDIS_URL], }, "ROUTING": "TMWA.routing.channel_routing", }, } routing.py channel_routing = { 'websocket.connect': consumers.ws_connect, 'websocket.receive': consumers.ws_receive, 'websocket.disconnect': consumers.ws_disconnect, } consumers.py @channel_session def ws_connect(message): print "in ws_connect" print message['path'] prefix, label, sessionId = message['path'].strip('/').split('/') print prefix, label, sessionId message.channel_session['sessionId'] = sessionId message.reply_channel.send({"accept": True}) connMgr.AddNewConnection(sessionId, message.reply_channel) @channel_session def ws_receive(message): print "in ws_receive" jReq = message['text'] print jReq task = ltmon.getJSON.delay( jReq ) connMgr.UpdateConnection(message.channel_session['sessionId'], task.id) @channel_session def ws_disconnect(message): print "in ws_disconnect" connMgr.CloseConnection(message.channel_session['sessionId']) docker-compose.yaml version: '3' services: … -
Django. Listing files from a static folder
One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory on my server) as a list of links. Whether this is secure or not is another question, but suppose I want to do it... That's how my working directory looks like. And i want to list all the files fro analytics folder in my template, as links. I have tried accessing static files in view.py following some tutorial and having it like that: view.py from os import listdir from os.path import isfile, join from django.contrib.staticfiles.templatetags.staticfiles import static def AnalyticsView(request): mypath = static('/analytics') allfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] return render_to_response('Rachel/analytics.html', allfiles) And my template: <p>ALL FILES:</p> {% for file in allfiles %} {{ file }} <br> {% endfor %} And my settings.py PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] And i am getting the error: FileNotFoundError at /analytics/ [WinError 3] The system cannot find the path specified: '/analytics' Error traceback Any help will be very appreciated -
Django template is removing html table, regardless of using safe or autoescape
I am trying to pass a variable which has a html table into it as a HTML table in a Django template. when I pass it though and mark it as | safe or turn auto escape off. all the HTML is inserted but the table is fully removed, does anyone know why and how I can turn it off? import urllib.request from bs4 import BeautifulSoup tt_opener = urllib.request.build_opener() tt_opener.addheaders = [('User-Agent', 'Mozilla/5.0')] tt_service = tt_opener.open('https://managed.mytalktalkbusiness.co.uk/network-status/') tt_soup = BeautifulSoup(tt_service, "html.parser") tt_data = tt_soup.table template <div id="TALK-TALK-Service" style="width:50vw; height:50vw; float:left;"> {{ TalkTalk |kksafe }} </div> the tt_data variable printed via shell <table border="0" cellpadding="0" cellspacing="0" class="opaltable" width="100%"><th nowrap="nowrap"> </th><th nowrap="nowrap">Issue</th><th nowrap="nowrap">Services affected</th><th nowrap="nowrap">Location</th><th nowrap="nowrap">Last update</th><tr><td width="20"><img src="https://managed.mytalktalkbusiness.co.uk/images/redlight.gif"/></td><td width="350"><a href="https://managed.mytalktalkbusiness.co.uk/network-status-report.php?reportid=15462">incident 10574541 - Washington Exchange - no service</a></td><td>Extranet, Ethernet, EoFTTC &amp; EFM via TalkTalk, DSL via TalkTalk</td><td width="100">n/a</td><td nowrap="nowrap" width="150">11th Oct 2017 12:53</td></tr><tr><td width="20"><img src="https://managed.mytalktalkbusiness.co.uk/images/redlight.gif"/></td><td width="350"><a href="https://managed.mytalktalkbusiness.co.uk/network-status-report.php?reportid=15448">Incident 10573277 - Network – P1 – Some TTB customers are experiencing Post Dial Delay SIP/VOE</a></td><td>SIP/VOE</td><td width="100">n/a</td><td nowrap="nowrap" width="150">11th Oct 2017 12:27</td></tr></table> the html displayed on the webpage <div id="TALK-TALK-Service" style="width:50vw; height:50vw; float:left;"> [&nbsp;, Issue, Services affected, Location, Last update, <img src="https://managed.mytalktalkbusiness.co.uk/images/redlight.gif"><a href="https://managed.mytalktalkbusiness.co.uk/network-status-report.php?reportid=15462">incident 10574541 - Washington Exchange - no service</a>Extranet, Ethernet, EoFTTC &amp; EFM via TalkTalk, DSL … -
How to add new form to django formset and not lose user input from previous forms
If user adds another form to formset, but has already typed something in first form, then the input will be lost, as new form was created. User now has 2 empty forms. Is there a way to add new form to formset but not lose user input? forms.py class Form(forms.Form): client = forms.CharField(label='Client', required=False) end_client = forms.CharField(label='End client', required=False) product = AutoCompleteSelectField(lookup_class=ProductLookup, label='Model', required=False) views.py def get(self, request): request.session['form_count'] = 1 FormSet = formset_factory(Form) formset = FormSet() return render(request, self.template_name, {'formset': formset} ) def post(self, request): if "add-form" in request.POST: form_count = request.session['form_count'] print("There are " + str(form_count) + " forms") form_count = form_count + 1 request.session['form_count'] = form_count print("Form count increased by 1, form count is: " + str(form_count)) FormSet = formset_factory(Form, extra=int(form_count)) formset = FormSet() **<-- if I put request.POST in here, new form will not be created** return render(request, self.template_name, {'formset': formset}) html file <div class="content"> <form method="post"> {% csrf_token %} {{ formset.management_form }} <div class="form-group"> {% for form in formset.forms %} <table class='no_error'> {{ form.as_table }} </table> <br> <br> {% endfor %} </div> <input class="btn btn-primary" type="submit" value="Submit order" /> <input name="add-form" class="btn btn-primary" type="submit" value="Add new product" /> </form> </div> -
Django field lookups day not wok
The model: class A(models.Model): ... stop_date = models.DateTimeField() start_date = models.DateTimeField() ... when i use field lookups day , the result is not my expect: a_list = A.objects.filter(stop_date__day=10) the a_list is a empty queryset. But the database has some records which the day of stop_date is 10. In settings.py, USE_TZ = True TIME_ZONE = 'UTC' Is there something wrong with the time zone setting? Expect your help. -
django test: fixtures not loading with selenium
My fixtures are correctly loaded by TestCase test: like in: class Test_test_fixture(TestCase): fixtures = ['lwt/fixtures/myfix.json'] def setUp(self): super(Test_test_fixture, self).setUpClass() print(User.objects.all()) .. But doing the same thing with Selenium is printing an empty query: class Selenium_fixtures(StaticLiveServerTestCase): fixtures = ['lwt/fixtures/myfix.json'] @classmethod def setUpClass(cls): super(Selenium_fixtures, self).setUpClass() print(User.objects.all()) ... What am I missing? -
why template inheritance when include is more intuitive?
I am new to programming, so I'm sorry if this seems trivial and stupid. Why template inheritance when include seems more intuitive? And seem to do the job? -
Django Multiple Generic Foreign Keys - How to Structure DRF Serializer
I have read the documentation about Content Type for Django, but I cannot seem to correctly think of a way to apply it to my situation. The common 'Tag' example is a little too simplistic. My situation: I have a Model called Docket. It has several fields which hold various simplistic values. However, it also needs to have a destination and a source. In my app, destinations and sources can both be either a Facility Object or a TransFrontier Object. So for example, you could have a Docket which has a Facility as it's source and a TransFrontier as its destination. You could also have a Docket with a TransFrontier as its source and a Faclity as its destination. Additionally, users will not be creating new Facility or TransFrontier objects when they create a new docket. These will existing Facility or TF objects we already have in the database. So to do this I initially thought of ContentType and Generic Foreign Key. I came up with this model: class Docket(BaseDocket): # Fields dest_id = models.PositiveIntegerField() destination = GenericForeignKey("dest_c_type", "dest_id") source_id = models.PositiveIntegerField() source = GenericForeignKey("source_c_type", "source_id") # limit dest & source to facility and transfrontier limit = models.Q(app_label='facilities', model='facility') | … -
django form.is_valid() only works in debug
I have a CreateView subclass with the following method: def post(self,request, *args, **kwargs): form = self.get_form(self.get_form_class()) formset = StepFormSet(self.request.POST) if formset.is_valid() and form.is_valid(): return self.form_valid(form.cleaned_data, formset.cleaned_data) else: return self.form_invalid(form, formset) Two of the fields in every form in formset are TimeFields. Now, if I type an obviously wrong time format (e.g. 09, or ddd), formset.is_valid()==True no matter what. It only returns false if I debug it within PyCharm Professional, placing a breakpoint at the first line of the method. I can't really understand what differs in the debug... -
Django Bootstarp/Materialize
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> </head> <body> <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel"> <div id="Carousel" class="carousel slide"> <ol class="carousel-indicators"> <li data-target="Carousel" data-slide-to="0" class="active"></li> <li data-target="Carousel" data-slide-to="1"></li> <li data-target="Carousel" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="item active"> <img src="img/Carousel/001.jpg"> </div> <div class="item"> <img src="img/Carousel/002.jpg"> </div> <div class="item"> <img src="img/Carousel/003.jpg"> </div> </div> <a class="left carousel-control" href="#Carousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#Carousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> </body> </html> My bootstrap doesn't work for carousels neither does for Materialize. What could be the problem? Is the Javascript causing problem or what is it? I'm getting broken carousels. Ignore the images in the code. -
how can we can make Array of Array in python
I am getting data in python like this N/A,0E-11,0E-11,0E-11,@,N/A,0.0,0.0,0E-11,@ 1 line contain data for 1 array like N/A,0E-11,0E-11,0E-11, this is array of 4 variables N/A , 0E-11 , 0E-11 , 0E-11 . And I have separated both by @ I get all variables in loop like this results += cursor.fetchone() //getting full line results+='@' // giving @ after 1 array of data for r in results: //iterating all variables results_data.append(r) results_data.append(',') print results Now I want to make a array of array like this array3= [[1 2 3], [4 5 6] [7 8 9], [10 11 12]] like after @ new array and , a new attribute. -
How to make a custom database function in Django
Prologue: This is a question arising often in SO: Equivalent of PostGIS ST_MakeValid in Django GEOS Geodjango: How to Buffer From Point Get random point from django PolygonField Django custom for complex Func (sql function) and can be applied on the above as well as in the following: Django F expression on datetime objects I wanted to compose an example on SO Documentation but since it got shut down on August 8, 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and write my example as a self-answered post. Of course, I would be more than happy to see any different approach as well!! Question: Django/GeoDjango has some database functions like Lower() or MakeValid() which can be used like this: Author.objects.create(name='Margaret Smith') author = Author.objects.annotate(name_lower=Lower('name')).get() print(author.name_lower) Is there any way to use and/or create my own custom database function based on existing database functions like: Position() (MySQL) TRIM() (SQLite) ST_MakePoint() (PostgreSQL with PostGIS) How can I apply/use those functions in Django/GeoDjango ORM? -
Stripe Connect Callback and Python Django
def stripe_callback(request): client_secret = STRIPE_API_KEY # the temporary code returned from stripe code = request.GET.get('code', '') # identify what we are going to ask for from stripe data = { 'grant_type': 'authorization_code', 'client_secret': clientsecret, 'client_id': clientid, 'code': code } print(data) # Get the access_token using the code provided url = 'https://connect.stripe.com/oauth/token' r = requests.post(url, params=data) # process the returned json object from stripe stripe_id = r.json().get('stripe_user_id') print(stripe_id) I'm signing up my users and in their landing page I present a stripe connect but everything is working after following stripe doc and i get the response json with all the required info as follows: { "access_token": "sk_test_dQQmmR8797495973tAuO66iZP5V", "livemode": false, "refresh_token": "rt_BYhJGFxQlhgfiub4fbu4un3mn3FdAKiQ9XFgmkxI2cq", "token_type": "bearer", "stripe_publishable_key": "pk_test_UNvjubd4b4dini4ioTQNo4", "stripe_user_id": "acct_19qf4r7tg974fh8f40Za", "scope": "read_write" } What I've not been able to do is save the stripe_user_id againt my website user. Any input on this from you guys would be great. -
Why does uploading images to S3 with JS+Django always yield a 400-error?
I've tried with code from several tutorials that teach me how to upload images to S3 using XHR's. The Ajax-call to get the signature from my webserver goes fine, but when I try to upload the form + image to AWS I always get that 400-error with no further details. Could anyone please help me diagnose this issue? I'm using a Chrome browser. Let me know if you need further details. Backend code (in views.py): def sign_s3(request): S3_BUCKET = 'my-bucket' folder_name = request.GET.get('folder_name', '') file_name = request.GET.get('file_name', '') file_type = request.GET.get('file_type', '') upload_start_path = "static/img/{}".format(folder_name) filename_final = "{}.{}".format(file_name, file_type) policy_expires = int(time.time()+5000) policy_document_context = { "expire": policy_expires, "bucket_name": S3_BUCKET, "key_name": "", "acl_name": "public-read", "content_name": "", "content_length": 524288000, "upload_start_path": upload_start_path } policy_document = """ {"expiration": "2019-01-01T00:00:00Z", "conditions": [ {"bucket": "%(bucket_name)s"}, ["starts-with", "$key", "%(upload_start_path)s"], {"acl": "%(acl_name)s"}, ["starts-with", "$Content-Type", "%(content_name)s"], ["starts-with", "$filename", ""], ["content-length-range", 0, %(content_length)d] ] } """ % policy_document_context aws_secret = str.encode(os.environ.get('AWS_SECRET_ACCESS_KEY')) policy_document_str_encoded = str.encode(policy_document.replace(" ", "")) url = 'https://{bucket}.s3.{region}.amazonaws.com/'.format( bucket=S3_BUCKET, region='eu-central-1' ) policy = base64.b64encode(policy_document_str_encoded) signature = base64.b64encode(hmac.new(aws_secret, policy, hashlib.sha1).digest()) data = { "policy": bytes.decode(policy), "signature": bytes.decode(signature), "key": os.environ.get('AWS_ACCESS_KEY_ID'), "file_bucket_path": upload_start_path, "file_id": 1, "filename": filename_final, "url": url, } return JsonResponse(data) Frontend code: var fileItemList = []; document.getElementById("button").onclick = function(){ var … -
TLS1.2 not supported with my python/django site
I'm hoping someone might be able to help me. I have a client that has a website running Python 2.7.5+ (according to python -V). It's an ecommerce site that also uses the eWay payment gateway. They recently made some changes to only support TLS1.2 https://www.eway.com.au/tls-updates. However, when a customer goes through the checkout it shows a denied message from the eWay payment gateway. eWay say that this is because the transaction is still not coming through as TLS1.2. I have upgraded the Amazon EC2 instance and modified the apache .conf file so that it only supports TLS1.2 and i have verified this by checking the site through an SSL test with https://www.ssllabs.com/ssltest/. Therefore, I believe the issue may be due to the pyOpenSSL package being on a version that doesn't support TLS1.2. It's apparently on version 0.13: pyOpenSSL==0.13. I was wondering if someone might be able to help confirm or disprove my theory (I know this may be difficult with not having access to the server) and perhaps provide some pointers. I have tried upgrading pyOpenSSL using the command pip install –upgrade pyopenssl==0.15.1 but I got the following error; Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip-1.5.2-py2.7.egg/pip/basecommand.py", line 122, in … -
Django: Custom Profile Picture To New User
In Registration form before saving the User I wants to give the Profile picture of First user to every new user until they change it. This is what I tried, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user.userprofile.profile = UserProfile.objects.profile(id=1) new_form.save() This code is showing me the error "'Manager' object has no attribute 'profile'". How can I do that ? -
How to use an es6 file with django?
I would like to implement this answer: https://stackoverflow.com/a/31669706 but I dont have an idea how to integrate it with Django. Would appreciate any guidance. Thank you. -
Get the selected radio button in django template
In my template I have for loop. As you can see the id for each radiobutton is reprsented by {{stud.id}} . {{stud.nameAndSurname}} shows the name and the surname of the student(in browser I can see name and surname of the corresponding student). <form method="POST" class="post-form"> {% csrf_token %} {% for stud in students %} <input type="radio" id={{ stud.id }} name="student">{{ stud.nameAndSurname }} {% endfor %} <button type="submit" class="save btn btn-default">GO!</button> </form> In my view.py I have: class MyClass(View): def get(...): ... def post(self,request, pk): myVar = request.POST.get("student") return HttpResponse(myVar) If I click submit button i want to go to another page that shows me name and surname of the selected student. Now the issue is that instead of the student's name and surname it's showing me simply written "on" -
How to insert multiple images into a blog post not File field upload (Django blog)
I am a semi-noob to Django web development. I've managed to add a File field that actually allows me to upload an image into the post (The image is displayed in post-list and post-detail) but what if I wanted to add several images in a post? I am currently writing a tutorial post and would like to insert images under each instruction for the benefit of the user. I don't want the tutorials to be purely text, how do I go about doing this? Below is my models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone #from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.FileField(null=True, blank=True) #tags = TaggableManager() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def approved_comments(self): return self.comments.filter(approved_comment=True) class Meta: ordering = ["-pk"] class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def approved_comments(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.text And here's my forms.py from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class …