Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call a python function with annotations?
I have a function in another annotated method and there is a problem. I call it through django and get all sorts of errors. like this. views.py: ` def callbot(): bot_activate = bot.Command.callBot() return render(request, bot_activate) def output(request, temlate_name='custom_change_form.html',): callbot() print('work') return render(request, temlate_name) **bot.py** @logerrors def do_echo(update: Update, context: CallbackContext,): print('HELLOOOOO') chat_id = update.message.chat.id text = update.message.text p, _ = Profile.objects.get_or_create( external_id=chat_id, defaults={ 'name': update.message.from_user.username, } ) MessagePanel( profile=p, text=text, ).save() reply_text = f"Your ID: {chat_id} \n{text} \n " update.message.reply_text(text=reply_text,) @logerrors def send_text(update: Update, context: CallbackContext,): chat_id = update.message.chat_id text = update.message.text commandname = CommandsForButtons.objects.filter(is_active=True) print('Its worked') for mess in commandname: mess_send = mess.command_text update.message.reply_text(text=f'It\'s test message: {mess_send}') do_echo(update, context) @logerrors def send_hand_message(update: Update, context: CallbackContext,): chat_id = update.message.chat_id text = update.message.text hand_message = HandMadeMessage.objects.all() update.message.reply_text(text=f'It\'s test message: {hand_message}') class Command(BaseCommand): help = 'Telegram-Bot' def handle(self, *args, **options): hand_message = HandMadeMessage.objects.all() request = Request( connect_timeout=0.5, read_timeout=1.0, ) bot = Bot( request=request, token=settings.TOKEN, base_url=getattr(settings, 'PROXY_URL', None), ) to_bot_panel, _ = BotsPanel.objects.get_or_create( bot_id = bot.get_me().id, bot_name = bot.get_me().first_name, bot_nickname= bot.get_me().username, bot_token= bot.token ) print(bot.get_me()) updater = Updater( bot=bot, use_context=True, ) #Commands def callBot(): return send_text(Update, CallbackContext) updater.dispatcher.add_handler(CommandHandler('get', send_text,)) updater.dispatcher.add_handler(MessageHandler(Filters.text, do_echo)) updater.start_polling() updater.idle() ` Maybe u guys know what i should to … -
How to make logical AND, NOT work properly in Postgres full text search with Django
I have a project with Django, DRF and PostgreSQL. And I need to make a search for some data in this project. In this search I need logical operators (AND, OR, NOT), searching by prefix (like manch*) and case insensitivity. So I decided to use PostgreSQL full text search like this class VariableSearch(generics.ListAPIView): serializer_class = VariableSerializer def get_queryset(self): q = self.request.query_params.get('query') if q: vector = SearchVector('name', 'label') query = SearchQuery(q, search_type='raw') queryset = Variable.objects.annotate(search=vector).filter(search=query) else: queryset = Variable.objects.none() return queryset So with this type of search I can do queries like this http://127.0.0.1:8000/search_var/?query=полит:* | инфо:* And operator OR and searching by prefix working good. But when I'm trying to use AND (&) on NOT (!) it's giving me results without this logical AND or just syntax error in tsquery: "word !not" for queries like this http://127.0.0.1:8000/search_var/?query=word !not So how to make AND and NOT work properly? -
Appenchild is throwing an error when trying to append a modal to a div
I am currently exploring and trying to create a Django application. The problem I am facing currently is, while trying to append a modal to a div element in the HTML file, the JavaScript threw an error saying : Uncaught (in promise) TypeError: modalContainer.appendChild is not a function at HTMLButtonElement.replyModal ((index):217:28) Here is the code throwing the problem: console.log("REPLY MODAL"); var modal = document.createElement('div'); modal.className = "modal fade"; modal.id = "reply-modal"; modal.tabIndex = "-1"; modal.setAttribute("aria-labelledby", "Reply to feedback"); modal.setAttribute("aria-hidden", "true"); var modalDialog = document.createElement('div'); modalDialog.className = "modal-dialog"; var modalContent = document.createElement('div'); modalContent.className = "modal-content"; var modalHeader = document.createElement('div'); modalHeader.className = "modal-header"; var modalTitle = document.createElement('h5'); modalTitle.className = "modal-title"; modalTitle.innerHTML = "Reply to feedback"; var modalCloseButton = document.createElement('button'); modalCloseButton.className = "btn-close"; var modalBody = document.createElement('div'); modalBody.className = "modal-body"; var modalForm = document.createElement('form'); modalForm.method = "POST"; modalForm.action = "/suggestionbox/reply/" + feedback.pk + "/"; modalForm.id = "reply-form"; var modalCsrfToken = document.createElement('input'); modalCsrfToken.type = "hidden"; modalCsrfToken.name = "csrfmiddlewaretoken"; var modalFormGroup = document.createElement('div'); modalFormGroup.className = "form-group"; var modalLabel = document.createElement('label'); modalLabel.for = "reply"; modalLabel.innerHTML = "Reply"; var modalTextArea = document.createElement('textarea'); modalTextArea.className = "form-control"; modalTextArea.id = "reply"; var modalSubmitButton = document.createElement('button'); modalSubmitButton.type = "submit"; modalSubmitButton.className = "btn btn-primary"; modalSubmitButton.innerHTML = "Submit"; modalFormGroup.appendChild(modalLabel); modalFormGroup.appendChild(modalTextArea); modalForm.appendChild(modalCsrfToken); modalForm.appendChild(modalFormGroup); modalForm.appendChild(modalSubmitButton); … -
Django Apache production page loading very slow
hi I have a simple 2 page web app. The page where it display database data to html is running verry slow, can't even load properly and the database is very little (3 objects). I dont what the problem I been trying to fix that for the last 3 day. models.py class photos(models.Model): # title field title = models.CharField(max_length=100) #image field image = CloudinaryField('image') views.py def index(request): photo = photos.objects.all() context = {'photo': photo} return render(request, 'main/index.html', context) index.html {% for pic in photo %} <h2>{{pic.title}}</h2> {% endfor %} I feel like the problem come from the apache configuration server. Here my config. <VirtualHost *:80> ServerName MY-SERVER-IP ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-home=/var/www/mysite/venv/ python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /media/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> I didnt run any database command on my apache server, I dont know if I should run a command regarding the database. -
Celery keeps trying to connect to localhost instead of Amazon SQS
So I'm trying to setup Celery in my Django project, and using Amazon SQS as my broker. However, Celery keeps trying to find SQS on localhost for some reason. This is my settings.py: CELERY_BROKER_TRANSPORT = "sqs" CELERY_BROKER_USER = env.str("DJANGO_AWS_ACCESS_KEY_ID") CELERY_BROKER_PASSWORD = env.str("DJANGO_AWS_SECRET_ACCESS_KEY") CELERY_BROKER_TRANSPORT_OPTIONS = { "region": env.str("DJANGO_AWS_SQS_REGION_NAME", default="us-east-2"), "polling_interval": 10, } CELERY_DEFAULT_QUEUE = "default" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_CONTENT_ENCODING = "utf-8" CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_SQS_QUEUE_NAME = "default" This is my celery.py : import os from celery import Celery # set the default django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') app = Celery('consumers') # type: Celery app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() When I start the worker using celery -A src.consumers worker --loglevel=debug, the worker tries to start with the following output and then immediately stops: -------------- celery@aditya-PC v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.0-52-generic-x86_64-with-glibc2.35 2022-10-27 13:56:01 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: consumers:0x7fd77051de40 - ** ---------- .> transport: sqs://AHJJHHFYTA3GHVJHB8:**@localhost:6379// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) … -
How can I upload my projects to my website? [closed]
So, I have a portfolio website and 'Projects' section. In the 'Projects' section there is information about my projects: their picture, name and "See More" button. I want to I want it to open its own project every time the button is clicked. I use Django framework for backend. -
Sort table in Django admin with a boolean field
I want to sort data by Boolean in Django admin, but it doesn't work with admin_order_field, below is my code : def get_is_active(self, obj): return obj.is_active get_is_active.allow_tags = True get_is_active.admin_order_field = 'is_active' get_is_active.short_description = _('Is Active') This is the image below : -
How can I subselect a value in django querySelector?
I will exlplain my question with an example: lets say I am able to extract an object with this form with my filter: { a, b, c : {x, y, z} } But what I am trying to do, is to get the object as following: { a, b, c : {x} } { a, b, c : {y} } { a, b, c : {z} } if my question isn't clear enough don't hesitate to ask for more details in the comments -
django queryset: How I can override values in django queryset before sending the response?
I am on something where I need to override the values according to the URL parameters. Model: Person Name Alias Alex {"Alex", "Jacob" Alias column is the Array type I get alias from the URL parameter like: example.com/?alias=Alex here alias = Alex and my query is queryset = Person.objects.filter(name=alias) and finally, I have to send the response to the frontend like <QuerySet [<Person: "Alex">] basically here I have to remove Jacob from the Alias I have tried for qs in list(queryset): if "Alex" in qs["alias"]: qs["alias"] = ["Alex"] it is working but I need to return response in the form of queryset object -
How to join different models with primary key in Django?
I am very new on Django. I wanna make patient storage system but i'm stuck. These things must be in project. 1-) In my project i want to add hundreds of patients and also some new patients can add their own infos via register. 2-) Every patients will answer more then 300 questions, so i wanna split the model for good user experience. Here is the my problem. I split the main models, and then i add some basic information from hastaekle.html and then when i looked the admin panel. I see this selection page on the image at below. How can it be automatically. Here is my models.py from django.db import models from django.shortcuts import render from django.urls import reverse # Create your models here. class HastaProfil(models.Model): #id = models.IntegerField(primary_key=True) hasta_ad = models.CharField(max_length=155) hasta_soyad = models.CharField(max_length=155) hasta_dogum_yeri = models.CharField(max_length=155) def __str__(self): return self.hasta_ad + ' ' + self.hasta_soyad def get_absolute_url(self): return reverse('hasta-aliskanlik') class HastaAliskanlik(models.Model): #id = models.IntegerField(primary_key=True) sigara = models.CharField(max_length=155) alkol = models.CharField(max_length=155) uyusturucu = models.CharField(max_length=155) def __str__(self): return self.sigara def get_absolute_url(self): return reverse('hasta-listele') class Hasta(models.Model): #id = models.IntegerField(primary_key=True) hastaprofil = models.ForeignKey(HastaProfil, on_delete=models.CASCADE, null=True) hastaaliskanlik = models.ForeignKey(HastaAliskanlik, on_delete=models.CASCADE, null=True) forms.py from .models import HastaAliskanlik, HastaProfil, Hasta from django import … -
Is there a simpler way check if the filter i am filtering by is NULL in django?
I am wondering whether there is a simpler way to ignore NULL values when filtering in django. I don't mean NULL values in the database but rather potential NULL values I am filtering by. This is my code so far: if data['grade'] is not None: posts = posts.filter(grade=data['grade']) if data['subject'] != '': posts = posts.filter(subject=data['subject']) Is there a way to avoid all the if clauses and write the filter in a single statement? Thanks in advance! -
Can I add images from an AWS S3 bucket to Wagtail/Django database from , without downloading and opening each file?
I have a pre-existing AWS S3 bucket that I want to use for Wagtail Images. I want to populate the gallery with the images held in the S3 bucket, so that they're accessible to image fields on page models and also to RichText embedded imagery. The issue is that there are 1500 images, so I think I want to avoid having the script actually download/open each of these files if I can help it; I'm worried it will make the script run a long time and might kill down a server with a small amount of memory. Is there a way to register the files in the database without actually opening each image? Where I'm up to Where I think I'm going with this is to manually pull down the file references using boto and then somehow plug those references into the database? s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_S3_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_S3_SECRET_ACCESS_KEY) items = s3_client.list_objects_v2(Bucket='xxx') for item in items: image = CMSImage(...) But what next, I'm not sure of. I see solutions which involve downloading/opening the files, but is there a way to do this without that? -
What is the solution for DRF Social Oauth2 giving 401 (Unauthorized) Error from browser, but working fine on POSTMAN
I have an application which passes the client ID and secret along with username and password to http://127.0.0.1:8000/auth/token/ through a POST method. It is giving a 401 Error when I try to get the response in the console. I have tried multiples ways of submitting this but it is the same result. Also the same is working fine on POSTMAN. Please help if possible. I have tried multiple ways of submission, reformatting, checked everywhere on stackoverflow for similar errors, tried different browsers etc. -
Grouping dates in Django templates
im trying to group my objects by year only year in datetime field. {% regroup notificacoes by criados|date:"Y" as criados_list %} <ul> {% for x in criados_list %} <li> {{ x.grouper }} <ul> {% for y in x.list %} <li>{{ y.slug }} : {{ y.arquivo }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> this was supposed to work, but is not working -
my static files like images are not displayed after deploying my django 2.2 app
when I deploy my django 2.2 app on OVH but the static files like the image is not displayed even though the path is correct myapp/settings STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_URL = '/static/' index.html {% extends 'layout/base.html' %} {% load static %} {% block content %} <img src="{% static 'images/fondu2.png' %}" style="width:500px;height:500px"> {% endblock content %} myapp/urls.py ....... from .import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index, name='index'), ] where is the problem? -
How shall i add images in css using django?
how do i add image in css in django and flask i am not getting it I tried to used simple way of adding the images in css file but it is not showing, and I want it to be loaded and to be seen in my webpage. -
Django Rest Framework: TypeError: Object of type Facility is not JSON serializable
When i try to send a put request to my LeadUpdate Api Endpoint i receive the following error: Django Rest Framework: TypeError: Object of type Facility is not JSON serializable Can someone tell me why that is? This serializer is basically supposed to save assigned facilities within a lead when a lead gets updated and create a "LeadFacilityAssociation" object if any facility id's end up being sent with the IntegerField. serializer.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.IntegerField(required=False) scheduled_datetime = serializers.DateTimeField(required=False) class Meta: model = Lead fields = ( "id", "assigned_facilities", "scheduled_datetime", "is_owner", ) read_only_fields = ("id", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def create(self, validated_data): assigned_facilities = validated_data.pop("assigned_facilities") scheduled_datetime = validated_data.pop("scheduled_datetime") instance = Lead.objects.create(**validated_data) instance.LeadFacilityAssociation.create(assigned_facilities=assigned_facilities,scheduled_datetime=scheduled_datetime) return instance def to_representation(self, instance): representation = super().to_representation(instance) representation["scheduled_datetime"] = instance.LeadFacilityAssociation.first().scheduled_datetime representation["assigned_facilities"] = instance.LeadFacilityAssociation.first().assigned_facilities print(instance.LeadFacilityAssociation.first().assigned_facilities) return representation models.py class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.Name class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssociation(models.Model): assigned_facilities = models.ForeignKey(Facility, related_name='LeadFacilityAssociation') lead = models.ForeignKey(Lead, related_name='LeadFacilityAssociation') scheduled_datetime = models.DateTimeField(null=True, blank=True) -
How to only calculate the xp earned at frist try?
So the user can take some quiz and earn xp only at first try. From the second try on I only want to calculate how many correct answer scored but not xp will be earn. My models: class ClassAttempt(models.Model): user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True) related_class = models.ForeignKey(to=Class, related_name='attempt', on_delete= models.PROTECT, null=True) collected_xp = models.IntegerField(null=True, blank=True, default=0) status = models.CharField( verbose_name='status', max_length=20, choices=( ('no-completed', 'no-completed'), ('completed', 'completed'), ), default='no-completed' ) try_num = models.IntegerField(null=True, blank=True, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserClassQuestionsRecord(models.Model): user = models.ForeignKey(to=User, related_name='user_class_question_record', on_delete=models.CASCADE, null=True) question = models.ForeignKey(to=ClassQuiz, related_name='question_selected', on_delete=models.PROTECT, null=True, blank=True) selected_answer = models.ForeignKey(to=QuizAnsClass, related_name='answer_selected', on_delete=models.PROTECT, null=True, blank=True) is_correct = models.CharField( verbose_name='status', max_length=10, choices=( ('True', 'True'), ('False', 'False'), ), default='' ) try_num = models.IntegerField(null=True, blank=True, default=1) xp_collected = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) My View: class UserClassScore(ListAPIView): """ Get User Score at the end of each class by Class ID Get request """ queryset = ClassAttempt.objects.all() serializer_class = UserClassScoreSerializer permission_classes = [IsAuthenticated] lookup_field = 'id' def get_queryset(self): queryset = self.queryset.filter(related_class_id=self.kwargs.get('id'), try_num=1) if not queryset: self.serializer_class = UserClassScoreSerializerNoXp return queryset else: self.serializer_class = UserClassScoreSerializer return queryset My serializers : class UserClassScoreSerializer(serializers.ModelSerializer): score = serializers.SerializerMethodField() xp_collected = serializers.SerializerMethodField() def get_score(self, obj): class_data = UserClassQuestionsRecord.objects.filter(user=self.context['request'].user, question__singleclass_id=obj.related_class.id, try_num=1, … -
How to have my sitemap refreshed after a modification?
I’m using the Django sitemap framework to generate my sitemap and it is working, but I made some changes and my sitemap was not re-generated. This is my ok sitemap being generated: class StaticViewSitemap(Sitemap): protocol = "https" changefreq = "monthly" priority = 1 def items(self): return ['home'] def location(self, item): return reverse(item) <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://example.io/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/enterprise/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/about/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/pricing/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/posts/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> </urlset> However, I made some changes, I removed some links, but my sitemap is still displaying the old links. class StaticViewSitemap(Sitemap): protocol = "https" changefreq = "monthly" priority = 1 def items(self): return ['home','enterprise','about','pricing'] def location(self, item): return reverse(item) <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://example.io/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/enterprise/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/about/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/pricing/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/posts/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> </urlset> I'm trying migrate again and again to my sitemap.xml be re-generated, but this is not working. I also changed the branch and re-created, but still displays the first sitemap generation. -
show related fields in django admin panel
I have 3 django models. Requirement Model has its own fields. RequirementImage and RequirementDOc models have Requirement as foreign key in them which are used for multiple image and multiple document upload. In admin ,I want to show the Requirement along with the images and documents related to requirement. How can i show it in admin panel. I am able to show Requirement alone but i need to show the attached images and documents. Below is the exact code of models. class Requirement(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length = 5000) mobile = models.CharField(max_length=15, null=True, blank=True) email = models.EmailField(null=True, blank=True) city = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class RequirementImage(models.Model): requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, validators=[ FileMimeValidator() ], upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/images") class RequirementDoc(models.Model): requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE) requirement_file = models.FileField(null=True, blank=True, upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/docs") Python version is 3.7.12 and django version is 3.2.14 -
Where should I include a global fixture in a django project?
I have this fixture , and I want to make it global , where should I put it in my django project @pytest.fixture def auth_client(user = None): if(user is None): user = User.objects.create() client = APIClient() client.login(username=user.username, password=user.password) return client thanks in advance. -
Encrypt Django Rest Framework API response + Decrypt response in react app
I am currently building an application. My front end is developed using React and Axios (for API call requests). It is served directly by vercel on mydomain.com My back end is developed using Django and Django Rest. It is served with apache2 on api.mydomain.com. It only serves API endpoints. So the front-end and back-end are separated. I would like to return the entire data in encrypted form as an API response and then wants to decrypt it in the frontend app(react) Do you have any idea of what I could do to achieve this? Thanks a lot in advance for your answers. -
Python dictionary simplify a bit
I have some code inside dictionary how can i simplify this a bit. template_data = { 'name': title if name is not None else None, } -
Netsuite how do I open a file in the browser (Doc, excel) without downloading
Files which are uploaded onto the system will only show in a new browser if it is an image or PDF. If it's any other file format it will automatically download the file. Is there a way around this? I have tried using SuiteScript to access the file and open it in a new browser but, it will download it once opened in a new browser. -
Getting NoReverseMatch while click the comment button
I was getting that same error while click the like button, But the error was solved.. again after creating comment view and its other staff I'm getting that error again...When I click the comment button then the error appears..I'm very new to Django,,, help me please.. My project models.py, template page, urls.py, views.py are attached herewith **models.py** from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, verbose_name="Put a Title") blog_content = models.TextField(verbose_name="What is on your mind") blog_image = models.ImageField(upload_to="blog_images", default = "/default.png") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_comment" ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_comment") comment = models.TextField() comment_date = models.DateField(auto_now_add=True) def __str__(self): return self.comment class Like(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_liked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_liked") class Unlike(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_unliked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_unliked") **blog_page.html** {% extends "main.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div style="text-align:center;"> <h2>{{blog.title}}</h2> <img src="{{blog.blog_image.url}}" alt="" width="630px" height="300px"> </div> <div style="text-align:center;"> {{blog.blog_content|linebreaks}} </div> {% if …