Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static Sitemap is not working gives error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name."
I'm trying to implement a Static Sitemap for my app and I get the error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name." even though these views are set up. What could cause this? I have no problem with dynamic sitemaps, just the static one. My views.py def front_page(request): return render(request, 'django_modules_testing_app/front_page.html', { }) def about_us(request): return render(request, 'ihgr_app/about_us.html', { }) def index(request): return render(request, 'django_modules_testing_app/index.html', { }) urls.py from django.urls import path from . import views from . import blocks from django.contrib.sitemaps.views import sitemap from .sitemaps import DjangoModulesTestingApp app_name = 'django_modules_testing_app' sitemaps = { 'main_app':DjangoModulesTestingApp } urlpatterns = [ path('', views.front_page, name='front_page'), path('', views.index, name='index'), path('', views.about_us, name='about_us'), path('category_details/<slug:slug>/', blocks.category_details, name='category_details'), path('search_website/', views.SearchWebsite.as_view(), name='search_website'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap') ] sitemaps.py from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticSitemap(Sitemap): changefreq = 'weekly' priority = 0.8 protocol = 'http' def items(self): return ['front_page','index','about_us'] def location(self, item): return reverse(item) -
Pydantic from_orm to load django model prefetch_related list field
I have django model: class Foo(models.Model): id: int name = models.TextField(null=False) class Bar(models.Model): id: int foo = models.ForeignKey( Foo, on_delete=models.CASCADE, null=False, related_name="bars", ) and a pydantic model as (orm_mode is True): class BarPy(BaseModel): id: int foo_id: int class FooPy(BaseModel): id: int name: str bars: List[BarPy] Now i want to query on model Foo and load it into FooPy, so i wrote this query: foo_db = Foo.objects.prefetch_related("bars").all() pydantic_model = FooPy.from_orm(foo_db) But it gives me this error: pydantic.error_wrappers.ValidationError: 1 validation error for FooPy bars value is not a valid list (type=type_error.list) I am able to do it when explicitly using FooPy constructor and assigning the values manually but i want to use from_orm. -
Jquery Timepicker Disabletimerange not working
Im using version 1.3.5 <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css"> I don't know why the disableTimeRanges is not working. I've tried this one: $('.add-costings-starttime').timepicker({ dynamic: false, dropdown: true, scrollbar: true, 'disableTimeRanges': [ ['1am', '2am'], ['3am', '4:01am'] ] change: function (time) { var time = $(this).val(); var picker = $(this).closest(".costingsRow").find(".add-costings-endtime"); picker.timepicker('option', 'minTime', time); } }) -
How to redirect user from registration page to profile if user is already registered?
I am using Django class-based views for my project and trying to redirect user from registration view if he is already authenticated. I've done it already with LoginView and it was pretty simple and looked just like adding few lines of code: class Login(LoginView): authentication_form = CustomAuthenticationForm redirect_authenticated_user = True LOGIN_REDIRECT_URL = "core:profile" So after going to url for login, user ends up at his profile url. Absolutely simple and works perfectly. However, there is no CBV for registration and therefore CreateView should be used, which doesn`t have any attributes for checking if user is authenticated. The one method of doing something similar is UserPassesTestMixin, but it only gives me 403 Forbidden if user is authenticated, not redirect. Here is my current registration view: class Registration(UserPassesTestMixin, CreateView): form_class = RegistrationForm template_name = "registration/user_form.html" success_url = reverse_lazy("core:profile") def test_func(self): return self.request.user.is_anonymous def form_valid(self, form): print(self.kwargs) self.object = form.save(commit=True) self.object.is_active = True self.object.save() login(self.request, self.object, backend="core.auth_backend.AuthBackend") return HttpResponseRedirect(self.success_url) Maybe somebody have done it already? Would be very grateful for every advice! -
Calculating values from different Django Models
I have 2 similar django models, the difference between them is that one of them has a Foreign key with another model and the other is like a general Model. class Project: name = models.CharField(default='',max_length=100,verbose_name="name") class Article(models.Model): code = models.CharField(default='',max_length=20,verbose_name="Norma") name = models.TextField(default='',verbose_name="Denumire") project = models.ForeignKey(Project,on_delete=models.CASCADE,null=True) quantity = models.FloatField(default=0,verbose_name="Quantity") value = models.FloatField(default=0,verbose_name="Value") class BaseArticle(models.Model): code = models.CharField(default='',max_length=20,verbose_name="Norma") name = models.TextField(default='',verbose_name="Denumire") price = models.FloatField(default=0,verbose_name="Price") I want to calculate the value attribute from Article model, it should be like this: if article.code == basearticle.code: article.value = article.quantiy * basearticle.price How should I do this type of calculations? Should I write the logic in views.py? views.py: class ProjectDetail(LoginRequiredMixin, DetailView): template_name = "proiecte/project_detail.html" context_object_name = "projects" model = Project In the template I use {% for article in projects.article_set.all %} to generate a table that has all the attributes as headers. -
Django-filter is being ignored when query parameter value is non-existing
Code where problem occurs: class GameFilter(FilterSet): release = MultipleChoiceFilter(choices=Game.RELEASE_CHOICES, method='release_filter', widget=CSVWidget, required=True) def release_filter(self, queryset, name, releases): if releases: ... return queryset Lets say in my Game.RELEASE_CHOICES, one of my options is "2", this means this query is working for me http://localhost:8000/games/?release=2 In this case I can reach my breakpoint in release_filter method. BUT When I try to query this URL with non existing query parameter value http://localhost:8000/games/?release=2156 The release_filter is not being executed, cant reach breakpoint at all and all I get in return is: { "count": 0, "results": [], "page_size": 20 } What I would like to achieve is the filter being executed despite of non existing query parameter value. Is it possible? Thank you for all possible answers. -
How to get url string from url using resolve django for RBAC
I have used extract_views_from_urlpatterns method of show_urls management command in django-extenstion package for populating system urls into the DB. Now whenever user requesting to server it will intercept in middleware there i want to check if requested URL found in URLMaster model(all system URL store) but it didn't match due to the requested url not found here I am attaching the code. Populating the URL's urlconf = __import__(settings.ROOT_URLCONF) urls = Command().extract_views_from_urlpatterns(urlconf.urls.urlpatterns) for view, url, url_name in urls: if url_name is None: URLMaster.objects.get_or_create(url=url, defaults=dict(view_name=view.__qualname__, url_name=url_name)) Now currently i am check that URL in view further will check in middleware. from django.contrib.admindocs.views import simplify_regex # for simplifying regex from src.core.models import URLMaster # model has all the url's request_url = request._request.resolver_match.route print(request_url) # will print 'rough/packet-split/(?P<pk>[^/.]+)/packet-list/$' # simplifying the URL print(simplify_regex(request_url)) # will print '/rough/packet-split/<pk>/packet-list/' # The same url I have saved in DB url_master_url = URLMaster.objects.get(id=1216).url print(url_master_url) # will print 'rough/^packet-split/(?P<pk>[^/.]+)/packet-list\\.(?P<format>[a-z0-9]+)/?$' # now simplifying the URL print(simplify_regex(url_master_url)) # will print '/rough/packet-split/<pk>/packet-list\\.<format>/' # now i am comparing is it the same like simplify_regex(url_master_url) == simplify_regex(request_url) # returning false due to the url mismatched I am binding the permission to particular URL. But didn't match therefor Is there any approach to comparing or … -
How to render two views into one template using Django
fair to mention I'm just starting out with learning Django, and I could really use the help. To paint a clear picture, there are two API endpoints that I have to use and each one of them has to be rendered in the same template (HTML file) meaning they have to be in the same URL path as well, but I couldn't figure it out yet, I tried with both the function and class-based views but I got nowhere. views.py: ` class HomePage(TemplateView): template_name = 'home.html' def home(self, request): response = requests.get('https://api.covid19api.com/world/total').json() print('res',response.data) return render(request, 'home.html', {'response': response}) def other(self, request): response= requests.get('https://api.covid19api.com/country/south-africa/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json() return render(request, 'home.html', {'response': response}) ` urls.py: ` urlpatterns = [ path('home', HomePage.as_view(), name='home') ] ` home.html: ` {% extends '_base.html' %} {% block page_title %} Covid19 Statistics {% endblock %} {% block content %} <br> <br> <h3 class="text-center">World Total Statistics </h3> <br> <!-- <div class="container"> <div class="card-group"> <div class=" col-md-4"> <div class="card text-white bg-secondary mb-3" style="max-width: 20rem;"> <div class="card-body"> <h5 class="card-title text-center">Total Confirmed: {{response.TotalConfirmed}}</h5> </div> </div> </div> <div class=" col-md-4"> <div class="card text-white bg-secondary mb-3" style="max-width: 20rem;"> <div class="card-body"> <h5 class="card-title text-center">Total Deaths: {{response.TotalDeaths}}</h5> </div> </div> </div> <div class=" col-md-4"> <div class="card text-white bg-secondary mb-3" style="max-width: … -
How to get rid of this error? SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async
I use asynchrony in django and I ran into the following problem: It is possible to execute a aget() request for the AccountUser model, but the CabinetUser model is not. When executing a aget() request for the CabinetUser model, I get an error: SynchronousOnlyOperation: You cannot call this from an asynccontext - use a thread or sync_to_async. My mоdels: class AccountUser(AbstractUser): """Модель для пользователей""" username_validator = UnicodeUsernameValidator() id = models.UUIDField( primary_key=True, default=uuid.uuid4(), editable=False) username = models.CharField( gettext_lazy("username"), max_length=150, unique=True, help_text=gettext_lazy( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[username_validator, validate_phone_number], error_messages={ "unique": gettext_lazy("A user with that username already exists."), }, ) class Meta: db_table = 'account_user' verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return f'Пользователь -> {self.username}' class CabinetUser(models.Model): """ Модель кабинета пользователя""" WORK_STATUS_WORKING = 'working' WORK_STATUS_FIRED = 'fired' WORK_STATUS_VACATION = 'vacation' WORK_STATUS_CHOICES = ( (WORK_STATUS_WORKING, 'Работает'), (WORK_STATUS_FIRED, 'Уволен'), (WORK_STATUS_VACATION, 'В отпуске') ) id = models.UUIDField( primary_key=True, default=uuid.uuid4(), editable=False) is_payment = models.BooleanField( default=True, verbose_name='Выплаты включены' ) work_rules = models.ForeignKey( to=WorkRules, verbose_name='Условия работы', on_delete=models.CASCADE, related_name='cabinet_user', ) role = models.CharField( max_length=20, choices=[ ('Director', 'Директор'), ('Operator', 'Оператор'), ('Driver', 'Водитель'), ('Courier', 'Курьер'), ], verbose_name='Должность',) # Для миграций cabinet_park = models.ForeignKey( to='partner.CabinetPark', related_name='cabinet_user', verbose_name='Кабинет парка', on_delete=models.CASCADE, blank=True, null=True ) group_commission = … -
What is difference between factory and factoryboy package?
I am new to the factoryboy package i want to use this for unit testing of my django app, previously i used factory package, i want to know the exact difference between this 2 package becuase syntax and structure is almost same in both package -
Django SAML logout failing
In my Django project I use python3-saml to login with SSO. The login works like expected but the logout is failing with an error message 'No hostname defined'. I really don't know how to solve this as the only parameter passed to logout is the request and request is missing 'http_host' and 'server_name', read here. My logout part looks like following: def get(self, request, pkuser=None): try: get_user_model().objects.get(pk=pkuser) except get_user_model().DoesNotExist: return redirect('HomePage') logger = logging.getLogger('iam') logger.info('IAM logout') auth = OneLogin_Saml2_Auth(request, custom_base_path=settings.SAML_FOLDER) logger.info('account logout') # OneLogin_Saml2_Utils.delete_local_session() try: auth.logout( name_id=request.session['samlNameId'], session_index=request.session['samlSessionIndex'], nq=request.session['samlNameIdNameQualifier'], name_id_format=request.session['samlNameIdFormat'], spnq=request.session['samlNameIdSPNameQualifier'] ) logger.info('account logout success') OneLogin_Saml2_Utils.delete_local_session() logger.info('account logout: deleted local session') except Exception as e: logger.info('account logout failed: {}'.format(str(e))) logout(request) return redirect('HomePage') Maybe I'm using the wrong package...? Any help or advice will be appreciated. -
Why is my form invalid with this error: "Select a valid choice. That choice is not one of the available choices."
forms.py: class CategoryForm(forms.Form): category = forms.ModelChoiceField(queryset=Category.objects.filter(parent=None)) models.py: class Category(models.Model): parent = models.ForeignKey( "Category", on_delete=models.CASCADE, related_name="children", null=True, ) title = models.CharField(max_length=255) def __str__(self): return self.title views.py: def category_select(request, pk): if request.method == "POST": form = CategoryForm(request.POST) if form.is_valid(): category = form.cleaned_data["category"] if category.children.all(): return redirect(reverse("category_select", args=[category.pk])) else: return HttpResponse("no children") else: return render( request, "ads/category_select.html", { "form": form, }, ) The purpose of this form is that if the user selected a category that has no children, it returns an HttpResponse('no children'). But when I select and submit the form, It gives me this error: Select a valid choice. That choice is not one of the available choices. -
How to programatically create a svg with different colors in python/django?
In telegram, when you have yet to upload your picture, they will programatically generate a logo based on your initials like the following I want something similar but as SVG and ICO for a Django web app. I only need 26 letters from A to Z. And I need to be able to change the fill color based on taiwindcss colors The letters itself would be white or black. Is there a programatical way to generate these svg and ico to be used in a Django webapp? I could not find any library that does this. I only need it as a square basically -
How to write a get response for two different models data in one response sorted by date?
I have two models: class A(models.Model): ... date=models.DateTimeField(auto_add_now=True) ... class B(models.Model): ... date=models.DateTimeField(auto_add_now=True) ... Both have date field in them. Now I want to write a get response so that I can get both of these model's data from the database sorted by date on the frontend. I have written model serializers with all fields for them. Now in the get response, I have written something like this: A = A.objects.all() B = B.objects.all() aSerializer = A_serializer(A, many=True) bSerializer = B_serializer(B, many=True) all = aSerializer.data + bSerializer.data all = sorted(all, key=lambda item: item['date'],reverse=True) return Response(all) I think I will not be able to do pagination and other stuff with this. Please let me know if there is any better approach to do this? -
Python coverage used in Django takes too long to execute even though it is run with --source flag option
I am using the Python package in combination with the Django testing framework and sometimes want to test only one app/directory/package stated in the coverage --source option. coverage run --source='custom_auth' manage.py test custom_auth.tests.TestAuth.test_authentication --keepdb Is this command the correct way to run only one test? I am also using --keepdb command to ignore recreating the database again. The test is executed in 0.147s, but something happens behind/before the test, and it takes about 3-5 minutes to start executing the test. -
Too many values to unpack in Django
My endpoint to edit a user in Django is implemented like this: @api_view(['PUT']) @permission_classes([IsAuthenticated]) def updateUser(request, pk): user = User.objects.get(pk) data = request.data user.first_name = data['name'] user.username = data['email'] user.email = data['email'] user.is_staff = data['isAdmin'] user.save() serializer = UserSerializer(user, many=False) return Response(serializer.data) My action in Redux to send a put request to Django is implemented like this: export const updateUser = (user) => async (dispatch, getState) => { try { dispatch({ type: USER_UPDATE_REQUEST }) const { userLogin: { userInfo } } = getState() const config = { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${userInfo.token}` } } const { data } = await axios.put( `/api/users/update/${user._id}/`, user, config ) dispatch({ type: USER_UPDATE_SUCCESS, }) dispatch({ type: USER_DETAILS_SUCCESS, payload: data }) } catch (error) { dispatch({ type: USER_UPDATE_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } I dispatch updateUser action on click of the button in my component like this: const submitHandler = (e) => { e.preventDefault() dispatch(updateUser({ _id: user._id, name, email, isAdmin })) } I get error from Django: ValueError: too many values to unpack (expected 2) Please help me understand where the problem is -
AWS RabbitMQ and Django Rest Framw: socket.gaierror: [Errno -2] Name or service not known
I am trying to a AWS rabbitmq using pika but I am unable to connect and get an error import pika params = pika.URLParameters("amqps://{uname}:{paswd}@<endpoint>") connection = pika.BlockingConnection(params) channel = connection.channel() def publish(): channel.basic_publish(exchange='', routing_key='bid_group', body='hello') The error is form connection = pika.BlockingConnection(params) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/rohan/Development/crm/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 360, in __init__ self._impl = self._create_connection(parameters, _impl_class) File "/home/rohan/Development/crm/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 451, in _create_connection raise self._reap_last_connection_workflow_error(error) File "/home/rohan/Development/crm/lib/python3.10/site-packages/pika/adapters/utils/selector_ioloop_adapter.py", line 565, in _resolve result = socket.getaddrinfo(self._host, self._port, self._family, File "/usr/lib/python3.10/socket.py", line 955, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known I was following https://www.youtube.com/watch?v=ddrucr_aAzA to set this up. I tried aws official docs https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/amazon-mq-rabbitmq-pika.html and it gives the same response -
How can I add html in iframe for django
Tried looking into this from stackoverflow but I wasn't understanding and it also seems that django was updated, so the methods maybe different. I am a new user to django and I want to take an html file I have and put into the index.html as an iframe (not an included template, but specifically an iframe. This html has a lot of weird stuff in it and I need it in an iframe so I can test and see it it show up without affecting the index.html so just an iframe is all I need) I tried adding the html to the urls.py then adding the iframe to the html but it failed. urls.py from django.urls import path, re_path, include #from rest_framework import routers from . import views from django.views.generic import TemplateView # Define app name app_name = "frontend" # Set up rest framework router #router = routers.DefaultRouter() #router.register(r"sites", views.SiteViewSet, basename="sites") # Specify url patterns urlpatterns = [ #path("", include(router.urls)), path("", views.show_map, name = "showmap"), re_path("czwt/", TemplateView.as_view(template_name="cold_zones_with_tooltips.html"), name = "show_coldzone_map") ] inside the index.html <iframe id="serviceFrameSend" src="{% url 'frontend/cold_zones_with_tooltips' %}" width="1000" height="1000" frameborder="0"> error: Reverse for 'czwt.html' not found. 'czwt.html' is not a valid view function or pattern name. -
Foreign Key doesn't store parent table primary key value using MySQL and Django
I am working on a project using Django and MySQL and I am stuck in a situation where I want to store parent table primary key value into child table foreign key and this functionality is not performing well as it always store value NULL. I have two tables first one is user and second one is logs. Here are the details of my tables: `CREATE TABLE user ( id int NOT NULL primary key AUTO_INCREMENT, username varchar(255), email varchar(255), password varchar(255), );` CREATE TABLE logs ( id int NOT NULL primary key AUTO_INCREMENT, notifications varchar(255), FOREIGN KEY (user_id) int NULL REFERENCES user(id), on_delete = CASCADE, on_delete = UPDATE ); I have used query to set the parent table primary key value to NULL to create a relation between parent table and child table: "SELECT logs.user_id from logs LEFT JOIN user on user.id = logs.user_id WHERE user.id is NULL" After creating relation When I insert data in parent table the child table foreign key value stores NULL and not store parent table primary key value: "INSERT INTO user(id, username, email, password) VALUES("abc", "abc@gmail.com", "*****")" after INSERT query the user table looks like: ` id username email password `1 abc abc@gmail.com … -
How to use generic view with pk renamed
django.views.generic.detail.DetailView uses pk or slug from urls.py as the identifier. In my case, I have: urls.py: urlpatterns = [ path('<int:quiz_id>/results/', views.ResultsView.as_view()), ] Is there a way to use: class ResultsView(generic.DetailView): model = Quiz without changing quiz_id to pk (default name used for primary key)? I expect that there is some way to change the vague pk to something more descriptive. -
Viewing all the Comments for a post using modal in Django
I am working on implementing a social media website using Django.I want the users to view all the comments posted for a post using modals of Twitter Bootstrap. The comments aren't displaying if there are more than 1 post in my database if I use modals. The logic which I have written works completely fine if I don't nest them inside a modal and display it directly on the webpage after the caption of the post. But considering good UI design implementation I thought of nesting it inside a modal so as to enrich the user experience. Can someone help me out with this? The code for the same is pasted below: <a data-bs-toggle="modal" data-bs-target="#staticBackdrop" style="cursor: pointer;"> View all comments </a> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="staticBackdropLabel">Comments</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button> </div> <div class="modal-body"> {% if not post.comments.all %} No Comments yet.. <a href="{% url 'add_comment' post.pk %}" >Add Comment</a> {% else %} {% for comment in post.comments.all %} <strong>{{ comment.name }}-{{ comment.date_added }}</strong> <br/> {{ comment.body }} <br/> <hr> {% endfor %} {% endif %} </div> <div class="modal-footer"> <button type="button" class="btn … -
How to properly hide application.fcgi within .htaccess file on shared hosting with https
Hello and thanks in advance, I have a django project working with fcgi on a shared hosting with ionos; I followed a tutorial from https://github.com/sparagus/django-shared-hosting-1and1 and it works pretty well. When I try "http://www.example.com/admin/" it works but the problem is that "https://www.example.com/admin/" redirects to "https://www.example.com/cgi-bin/application.fcgi/admin/" My .htaccess file looks like this AddHandler cgi-script .fcgi RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /cgi-bin/application.fcgi/$1 [QSA,L] How can I hide the "cgi-bin/application.fcgi" with https too? Thanks a lot for reading. I tried with flask docs aswell https://flask.palletsprojects.com/en/2.0.x/deploying/fastcgi/ but didn't works. -
How to make the dependant multiple choice field don't remove the previously selected choices from the choice field when depending field changes value?
I am working on Django forms. I have 2 choice fields, one is just a choice field and other one is multi choice field. The dropdown values of multi choice field depends upon the selection of choice field. Now, if I select a value from choice field, and then, selected 2-3 values from multi choice field regarding that earlier choice field, then, those selected values are displayed in choice field. Now my problem is, once I select the different choice from choice field, my previous selected choices from multi choice field gets deleted. One way is you can use .append() in jquery but the problem with this is it shows the choices from the previous selected choice field option. For eg: If by selecting previous choice value, I get 20 dropdown choices in multi select choice field (out of which I select 3 choices), then, by selecting some other choice value, I should be getting (let say only 5 choices), but I am getting 25 dropdown choices in multi select option. what I want is only 5 choices in drop down of multi select choice field with only 3 choices already present in the multi select choice field.. I hope … -
How to redirect print statement to log file and change print statement to logger in django python
I want to replace print statements to logger but without change print statement in application. And how can I redirect print statement to log file??? Below is my code. settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" }, "verbose": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout" }, "debug": { "class": "logging.handlers.TimedRotatingFileHandler", "level": "DEBUG", "formatter": "verbose", "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. "interval": 7, "backupCount": 7, # Only kept last 7 days log files "filename": "log/debug.log", }, "info": { "class": "logging.handlers.TimedRotatingFileHandler", "level": "INFO", "formatter": "verbose", "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. "interval": 7, "backupCount": 7, # Only kept last 7 days log files "filename": "log/info.log", }, "error": { "class": "logging.handlers.TimedRotatingFileHandler", "level": "ERROR", "formatter": "verbose", "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. "interval": 7, "backupCount": 7, # Only kept last 7 days log files "filename": "log/error.log", }, }, "loggers": { "root": { "level": … -
Display counter of likes per post with Django is not working
I want to get a variable on the views.py file that retrieves the list of likes for each post. So, then on the HTML file, I would use .count so I can get the number of items on the list and finally be displayed on the DOM. I first made classes on models.py. There, I have 3 classes: User, Post, and Like. User is from the default User class from Django. Post is a class that gets information about the post like the author, description, and timestamp. And on the Like class, I get the user and post. from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="user") description = models.CharField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.id}: {self.author}" class Like (models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, default='', related_name="user_like") post = models.ForeignKey("Post", on_delete=models.CASCADE, default='', related_name="post_like") def __str__(self): return f"{self.id}:{self.user} likes {self.post}" Second, I made a function on views.py called "index". There, I get the whole list of posts (on the posts variable), then I tried to create the variable (totalLikesSinglePost), which should get the list of likes for each post. def index(request): posts = Post.objects.all().order_by("id").reverse() # Pagination Feature (OMIT THIS, IF YOU WANT) …