Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
deploying channels with nginx
I have deployed django with nginx following the tutorials in digital ocean. Then I blindly followed the section "Example Setup" in the channels document after installation. My confusions are: When setting up the configuration file for supervisor, it says to set the directory as directory=/my/app/path Should I write down the path where the manage.py is or the path where the settings.py is? When I reload nginx after changing nginx configuration file, I get an error saying that host not found in upstream "channels-backend" in /etc/nginx/sites-enabled/mysite:18 nginx: configuration file /etc/nginx/nginx.conf test failed I did replace "mysite" by the name of my website. I had another error earlier saying that no live upstreams while connecting to upstream but could not recreate the situation. I am new to using the channels, so any additional information on upstream would be helpful. Please let me know if I need to provide more information. -
data passing by one to one field in Django
I have two models Employee and myCustomeUser in my Django project. My models.py: class myCustomeUser(AbstractUser): username = models.CharField(default="abcdef", max_length=150, unique="True") password = models.CharField(default="12345", max_length=150) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_IndustryOwner = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='releted_user') extraField = models.TextField(blank=True) Now I am trying to entry an Employee's data with views.py like this: Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True) Employee_obj.save() But It shows error like this: Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True) ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="? How can I solve this problem? Mainly I need to save any employee's data by Employee.objects.create() -
How to Build vue components in a django project in Ubuntu
I am working on a project with Django and Vue. In the ReadMe files it has the below instructions. I am in my django terminal on pycharm working in Ubuntu 18.04.5 LTS *) Install vue requirements: cd vuekhal npm init I did the above in the npm init I just kept pressing enter all the way *) Build the vue components (still inside vuekhal): ./node_modules/.bin/webpack --config="build/webpack.prod.conf.js" How do I configure the above components. What code do I add below (venv) samir@VB:~/path to/vuekhal$ -
Django: Create an editable form for each instance within a queryset all in one page?
Sorry if this is too much code, but I believe it is all relevant to the question at hand. Long story short, on my series_detail page, all episodes belonging to each series is shown, as well as forms to add a new episode or edit an existing one. The edit episode form, however, requires an instance, which always returns the very first object of the episodes queryset. This is presumably because of the .first(), but I used this since you can only have one object passed as an instance. What I am trying to achieve is: after showing the edit modal next to each episode, show the instance of each episode instead of only the first episode. save only that episode's instance after the form is filled achieve this without redirecting to an edit page models.py class Series(models.Model): name = models.CharField(max_length=100) class Episode(models.Model): series = models.ForeignKey(Series, on_delete=models.CASCADE) name = models.CharField(max_length=100) episode_no = models.IntegerField(null=True) description = models.TextField(max_length=500) image = models.ImageField(upload_to='pics/episodes',) forms.py class EpisodeForm(forms.ModelForm): name = forms.CharField() description = forms.CharField(widget=forms.Textarea, required=False) episode_no = forms.IntegerField() class Meta: model = Episode fields = ['name', 'description', 'episode_no' ,'image'] views.py def series_detail(request, pk): try: series = Series.objects.get(pk=pk) except: return render(request, 'error_404.html') episodes = Episode.objects.filter(series=series).first() if request.method … -
Problem render a function on a Django file
Hello Friends I have this program in views.py Im using django with websockets to take the RFID data from antenna and send to my server. The problem is that in the function def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" global numtags tags = llrpMsg.msgdict['RO_ACCESS_REPORT']['TagReportData'] if len(tags): logger.info('saw tag(s): %s', pprint.pformat(tags)) for tag in tags: numtags += tag['TagSeenCount'][0] else: logger.info('no tags seen') return I cant renderd to send the data to the websocket in my script on html file I trie with all but everytime its the same error This is my entire code from django.shortcuts import render from django.http import HttpResponse import datetime from django.template import Template,Context from django.template import loader import sys import os sys.path.append(os.path.abspath(os.path.join(__file__, '..', '..', '..'))) from argparse import ArgumentParser from logging import getLogger, INFO, Formatter, StreamHandler, WARN from sllurp.llrp import LLRP_PORT, LLRPClientFactory import smokesignal from twisted.internet import reactor from sllurp.util import monotonic ''' Sllurp/Tornado Example This file contains an example showing how to use Sllurp with Tornado to update a web page via websockets when rfid tags are seen. ''' numtags = 0 start_time = None def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" global numtags tags … -
Django views KeyError on production
I have a small NewsAPI application that returns JSON data when I run it locally but after deploying it on Heroku I get a KeyError in the logs and a 500 on the webpage. The log appears to show that the error is in the views: 2020-12-25T23:21:33.571005+00:00 app[web.1]: File "./evening_brew/news/views/api.py", line 114, in get 2020-12-25T23:21:33.571006+00:00 app[web.1]: news = self.requestNewsApi() 2020-12-25T23:21:33.571006+00:00 app[web.1]: File "./evening_brew/news/views/api.py", line 60, in requestNewsApi 2020-12-25T23:21:33.571006+00:00 app[web.1]: return self.extractDataFromNewsApi(responseData) 2020-12-25T23:21:33.571007+00:00 app[web.1]: File "./evening_brew/news/views/api.py", line 31, in extractDataFromNewsApi 2020-12-25T23:21:33.571007+00:00 app[web.1]: for posts in data["articles"]: 2020-12-25T23:21:33.571008+00:00 app[web.1]: KeyError: 'articles' Here's the full code for the view that the log is referring to: class NewsViewSet(MultipleSerializerMixin, viewsets.GenericViewSet): permission_classes = [AllowAny] def get_queryset(self): queryset = News.objects.all().order_by("-published_at") return queryset def extractDataFromNewsApi(self, data): articles = [] for posts in data["articles"]: post = {} post["headline"] = posts["title"] post["link"] = posts["url"] post["snippet"] = posts["description"] post["content"] = posts["content"] post["image_url"] = posts["urlToImage"] post["published_at"] = posts["publishedAt"] post["source"] = "news" articles.append(post) return articles def requestNewsApi(self, query=False): headers = {"Authorization": "Basic "} if query: url = ( settings.NEWS_API_URL + "everything?q=business+finance&pageSize=50&apiKey=" + settings.NEWS_API_KEY ) r = requests.get(url, headers=headers, params={"q": query}) else: url = ( settings.NEWS_API_URL + "everything?q=business&pageSize=50&apiKey=" + settings.NEWS_API_KEY ) r = requests.get(url, headers=headers) responseData = json.loads(r.text) return self.extractDataFromNewsApi(responseData) def storeInDb(self, articles, query=False): … -
Why does my Django Model not work correctly?
Currently making a basic django project, following a well set out tutorial off youtube. All's going well and I usually try to debug isses myself and I wouldn't be asking if i was stuck. Issue: This code is meant to check the image size onces it's reuploaded and then format to make it square but looking at the image linked, this isnt the case. Is my code wrong? is there another way to check and validate images? Code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) [Refrence Image for context][1] [1]: https://i.stack.imgur.com/g8uf6.png -
Catching classes that do not inherit from BaseException is not allowed with Redis in Django Rest Framework
so i'm working on a small DRF application, and I've implemented a custom config backend using redis: class RedisBackend(ConfigBackend): CONFIG_SET = Config.objects if "migrate" not in sys.argv else MagicMock() def __init__(self): ip = settings.CONFIG['REDIS']['HOST'] port = settings.CONFIG['REDIS']['PORT'] db = settings.CONFIG['REDIS']['DB'] password = settings.CONFIG['REDIS']['PASSWORD'] from redis import Redis self.redis = Redis(host=ip, port=port, db=db, password=password) # other methods omitted for brevity It all works fine until I quit the server with CTRL-C, at which point, I get this rather unsavoury exception: Exception ignored in: <bound method Connection.__del__ of Connection<host=localhost,port=6379,db=0>> Traceback (most recent call last): File "E:\Programming\programs\anaconda\lib\site-packages\redis\connection.py", line 537, in __del__ File "E:\Programming\programs\anaconda\lib\site-packages\redis\connection.py", line 667, in disconnect TypeError: catching classes that do not inherit from BaseException is not allowed I have no idea what I can do to fix this. Any ideas? I already tried closing the socket in the __del__ method of the config backend, but no dice. -
Passing Pandas Data Frame to Angular
Someone can explain why my function is no working? I want to get some data(pandas data frame and plot) from my django backend to angular frontend. Plot is working correctly, but i have problem with data frame. In browser console i have no notifications about this endpoint. import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, tap } from 'rxjs/operators'; @Component({ selector: 'app-entry', templateUrl: './entry.component.html', styleUrls: ['./entry.component.scss'] }) export class EntryComponent { title = 'FRS'; imgsrc = ''; pandas = ''; resavg = ''; constructor(private http: HttpClient) { } getDF(){ this.http.get('/getdata').pipe(map(r => r.toString()), tap(v => this.pandas = v)); } getimage(){ this.imgsrc = '/getimg'; } } -
how to change status by a link or a button in django
So I want to make a link or a button that should be able to change status from 1 to 0 in the database actually I have the link like this <a href="{% url 'articles:delete' slug=article.slug %}" class="btn btn-danger mr-1 float-left">Delete</a> and in url.py path('delete-article/<slug:slug>/', views.delete_article, name='delete'), now I want to make a function in views.py that change the status to 0 whenever the link is clicked -
NoReverseMatch at /questions/4/detail
I don't know why but when I click on a question's "more", I get this error: Reverse for 'category_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P[0-9]+)/questions$'] what does it have to do with category_detail?! I'm trying to access questions:quesiton_detail not questions:category_detail !! views.py from django.shortcuts import render, get_object_or_404, redirect from questions.models import Question,Category from questions.forms import QuestionForm from django.views.generic import TemplateView, ListView, DetailView, CreateView from django.urls import reverse_lazy class HomeTemplateView(TemplateView): template_name = 'questions/index.html' class AboutTemplateView(TemplateView): template_name = 'questions/about.html' class QuestionListView(ListView): model = Question template_name = 'questions/posts/allPosts.html' class QuestionDetailView(DetailView): model = Question template_name = 'questions/posts/detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.object.num_of_views += 1 self.object.save() self.object.refresh_from_db() return context class QuestionCreateView(CreateView): model = Question form_class = QuestionForm template_name = 'questions/posts/add_question.html' success_url = reverse_lazy('questions:all_questions') def get(self, request): question_form = QuestionForm() return render(request,'questions/posts/add_question.html', {'form': question_form}) def post(self, request): question_form = QuestionForm(request.POST) if question_form.is_valid(): cleaned_data = question_form.cleaned_data current_user = request.user question = Question(title=cleaned_data['title'], text=cleaned_data['text'], category=cleaned_data['category'], user=current_user) question.save() return redirect('questions:all_questions') class CategoryQuestionsDetailView(DetailView): model = Category template_name = 'questions/categories/category_questions.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['category'] = Category.objects.get(id=pk) context['cat_ques'] = context['category'].category_questions.all() context['questions'] = Question.objects.all() return context questions/urls.py from django.urls import path from questions import views app_name = 'questions' urlpatterns = [ path('', views.HomeTemplateView.as_view(), name='home'), … -
How to query and return list of dates that aren't present in Django Model table?
I have a query, FinalizedSalesReportObject.objects.filter(created__gte=datetime.now()-timedelta(days=7)).extra({'day':"date(created)"}).values('day').annotate(count=Sum('total')) on my model which has total = DecimalField() and created=DateTimeField() Currently, it returns <QuerySet [{'day': '2020-12-22', 'count': Decimal('148.980000000000')}, {'day': '2020-12-25', 'count': Decimal('54.3600000000000')}]> I would like to have all 7 days from 7 days ago until now returned in this, but am not sure if that's going to be possible using just a query. I can implement a function to populate the missing data, but am having trouble figuring out the best way to do this as well. -
django_neomodel can't find attribute MAX_POOL_SIZE
I am trying to set my first Django project using neo4j as database and neomodel as OGM, so I am following this directions. Nevertheless, when a try to start Django server, I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django_neomodel/apps.py", line 20, in ready self.read_settings() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django_neomodel/apps.py", line 17, in read_settings config.MAX_POOL_SIZE = getattr(settings, 'NEOMODEL_MAX_POOL_SIZE', config.MAX_POOL_SIZE) AttributeError: module 'neomodel.config' has no attribute 'MAX_POOL_SIZE' I am using python 3.7 and Django 3.1.4. -
Django models NameERROR in the same file?
good day to everyone, i had the name error in this code, someone can explain me why, please??? category = models.ManyToManyField(Category) NameError: name 'Category' is not defined from django.db import models from datetime import datetime # Create your models here. class Store(models.Model): bussines_name = models.CharField(max_length=100, null=False, verbose_name='Nombre') nit = models.PositiveIntegerField(null=False,default=0,verbose_name='NIT') category = models.ManyToManyField(Category) def __str__(self): return self.bussines_name class Meta: db_table = 'Store' verbose_name = 'Tienda' verbose_name_plural = 'Tiendas' ordering = ['id'] class Category(models.Model): name = models.CharField(max_length=150, verbose_name='Name') def __str__(self): return self.name class Meta: verbose_name = 'Categoria' verbose_name_plural = 'Categorias' ordering = ['id'] thanks for your comments -
Gunicorn service not starting EXEC 203
I am trying to start gunicorn service. My gunicorn configuration file is the following: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/var/www/www.techsoftconsulting.mx/app/ ExecStart=/var/www/www.techsoftconsulting.mx/techsoftenv/bin/gunicorn --workers 3 --bind unix:/var/www/www.techsoftc$ [Install] WantedBy=multi-user.target The working directory I am working is owned by user root and group root When I run systemctl start gunicorn and then systemctl status gunicorn I see the following: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Fri 2020-12-25 20:54:10 UTC; 15min ago Process: 803756 ExecStart=/var/www/www.techsoftconsulting.mx/techsoftenv/bin/gunicorn --workers 3 --bind unix:/var> Main PID: 803756 (code=exited, status=203/EXEC) Dec 25 20:54:10 48B23E4 systemd[1]: Started gunicorn daemon. Dec 25 20:54:10 48B23E4 systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Dec 25 20:54:10 48B23E4 systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
Running untrusted code (Python-as-a-Service)
I would like to create a simple Python-as-a-Service service. This means the python code which executes the first http request does not trust the python code which executes the second http request. But both should be executed in the same interpreter to avoid constant starting/stopping of the interpreter. How could I clean up after the first http request was run and before the second http request gets executed. I would like to use Django for this, but AFAIK this does not matter much for the current question. -
How to load static file from JavaScript in Django?
Hello so I have been trying to play an audio element in my Django app and controlling it using JavaScript. I was trying to play the audio from localhost, but I got the following errors: And I guess it's because I made a mistake in loading the audio file in my JS code. import AudioPlayer from './AudioPlayer.js'; const audioPlayer = new AudioPlayer('.audioPlayer', [ {url: '../music/rainfall.mp3', name: 'Alleviating Rainfall'}, ]); I think I did wrong on the url: part so django does not load my mp3 file and serve it from the server. So my question is, how can I load static audio file in Django from JS? I know for HTML it's {% static "[filepath]" %} but what's for JS?? Since the JS itself is a static file.. Here's my file directory: -
Is the server running on host "postgres_db" (10.10.0.4) and acceptinG TCP/IP connections on port 5434?
This is docker compose for django environment: SECRET_KEY: "KEY" DEBUG: "True" NAME: "NAME" USER: "USER" PASSWORD: "PASSWORD" HOST: "HOST" PORT: "5434" depends_on: - postgres_db This is docker compose for postgres postgres_db: image: postgres environment: POSTGRES_HOST_AUTH_METHOD: trust POSTGRES_USER: ss POSTGRES_PASSWORD: ss PGDATA: /data/ss volumes: - postgres:/data/postgres ports: - "5434:5432" networks: main_network: ipv4_address: 10.10.0.4 restart: unless-stopped This is my database config data in django settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': "postgres_db", 'PORT': os.getenv('PORT') } } I can not find my mistake. I spent 4-5 hours but no success. still I get this error Is the server running on host "postgres_db" (10.10.0.4) and acceptinG TCP/IP connections on port 5434? when I write docker compose up -
Python deleting a repo from github with request module
I do not coding a this situation. I can create a repository in python using a request.post() but ı can not delete a this repository. Who want to help to me ? Code: def deleteRepository(self, repo, name): headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': 'token {}'.format(self.token)} response = requests.delete(self.api_url + '/repos/' + name + repo, headers = headers) return response.json() -
Django using modals for deleting a user
I want to delete users with modals in django. I have a deletion function which I don't know how I should return to template. views.py: @login_required(login_url='admin_signin') @admin_only def admin_profiles_deletion(request, username): context = {} account = Account.objects.get(username=username) account.delete() messages.success(request, "User deleted!") context['account'] = account return render(request, 'HOW SHOULD I REFER MODALS HERE?', context) And my urls.py looks: path('admin/profile/<str:username>/delete', views.admin_profiles_deletion, name='admin_profiles_deletion'), And finally my template is: <td class="text-center td-actions"> <a href="{% url 'admin_view_profiles' account.username %}"><i class="la la-eye view"></i></a> <a href="{% url 'admin_profiles_general_edition' account.username %}"><i class="la la-edit edit"></i></a> <a href="{% url 'admin_profiles_deletion' account.username %}" data-toggle="modal" data-target="#deleteaccount"> <i class="la la-close delete"></i> </a> <!-- Modal --> <div class="modal fade" id="deleteaccount" tabindex="-1" role="dialog" aria-labelledby="deleteaccountTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteaccountTitle">Delete confirmation</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h5>Do you want to delete?</h5> </div> <div class="modal-footer"> <div class="col-6 text-left"> <div class="previous"> <form method="POST"> {% csrf_token %} <input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes"> </form> </div> </div> <div class="col-6 text-left"> <div class="next"> <a class="btn btn-info btn-sm btn-block" href="{% url 'accounts' %}">No</a> </div> </div> </div> </div> </div> </div> </td> In modal I want to hit YES and then delete specific account. but I don't know how to … -
How to generate a url that redirects to a specific view of another application
I'm working on a website, where I want to show all my django project. So, I have a main app, where i'm generating template for all my projects my home template when we access to the website: <!doctype html> {% load static %} <html lang="fr"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="{% static 'home/css/style.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Nerko+One&family=Roboto&display=swap&family=Open+Sans&display=swap" rel="stylesheet"> <meta name="viewport" content="width=device-width"/> </head> <body> <header> <h1></h1> <span class="separator"></span> <h2></h2> <img src="{% static '/home/pictures/logo.png' %}" alt="logo" title="Ceci est mon logo" id="logo"> </header> <nav> <ul> <li><a href="" title="Aller à l'accueil">Accueil</a></li> <li><a href="#projects">Projets</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> <div class="contener"> <section> <h3>Projets</h3> <!-- conteneur --> <div id="projects"> {% for projet in projets %} <div class="project"> <a href="{% url 'projet-detail' projet.nom_lien %}"> <div class="picture"> <img src="{% static '' %}{{ projet.lien_image_presentation }}" alt="Présentation {{ projet.nom }}"> </div> <span>{{ projet.nom }}</span> <span class="date-project">{{ projet.date }}</span> </a> </div> {% endfor %} </div> </section> <section> <h3>Contact</h3> <div id="contact"> <p>Si vous désirez me contacter, n'hésitez pas à m'écrire à l'adresse <a href="mailto:aymerick.cotche@hotmail.fr"><b>aymerick.cotche@hotmail.fr</b></a></p> </div> </section> </div> <footer> <span>2020 © - Aymerick Cotche</span> </footer> </body> </html> template to see my project description : {% load static %} <html lang="fr"> <head> <meta charset="UTF-8"> <title>{{ projet.nom }} | {{ projet.auteur }}</title> … -
Purpose and use of Wagtail/Django template tags of the form {% block body_class %}template-homepage{% endblock %}
In the Wagtail docs (Your first Wagtail site) we are told to create a homepage.html template as follows: {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-homepage{% endblock %} {% block content %} {{ page.body|richtext }} {% endblock %} In the above code, what is that tag {% block body_class %}template-homepage{% endblock %} supposed to be doing? I can't find any mention of it in the text of the tutorial. The tutorial goes on to instruct us to create two more templates, blog_index_page and blog_page templates, both of which are to contain {% block body_class %} tags. Again, I can find no mention at all of those lines in the docs, let alone an explanation of how they might be used/modified. A search for "body_class" in the docs finds only the three code blocks just mentioned, and one other mention: in the version 1.2 release notes, under 'What's new — Minor features' the notation: "Simplified body_class in default homepage template." Any insight as to what I'm supposed to do with these tags? What special meaning, if any, does the tag-enclosed text have in the tutorial templates (for example, "template-homepage" in the code above)? -
Is there a page or an explanation of django testing functions?
I am looking at some tutorials on django testing from django.test import TestCase from .forms import ItemForm class TestItemForm(TestCase): def test_item_name_is_required(self): form = ItemForm({'name': ''}) self.assertFalse(form.is_valid()) self.assertIn('name', form.errors.keys()) self.assertEqual(form.errors['name'][0], 'This field is required.') I understand the importing and the class with it's parameters. I am struggling to understand the .assertXXX(). I tried looking in the documentation for django, for these functions and all I get are examples of them being used, not explanations of what they do. Then I went to GitHub to try and look under the tests folder for what the tests could potentially do and I do not fully understand their code. for example I understand that .assertEqual(<first>, <second>) compares the two parameters and checks if they are equal. I am looking for some site or some resource that can explain to me what they might potentially do, like a index or something that has similar documentation to JQuery. -
Multiple field text search in Django
I have an app "api", and a folder "models" in it. In that folder I have several ".py" files, such as "client.py", "therapist.py", "user.py" and etc. In "therapist.py" I have several classes, but I need just one class "TherapistProfile". In that class there are several fields, but I need just "name", "surname", "skills", "city" for searching. So the purpose is to search by writing a sentence. Example (of what user can write in the search bar): "Tommy davidson listening london" (and it has to be case insensitive). The words will be separated by space. Also it has to work if we miss any of the fields: "Tommy listening london" (we didn't write the surname) Also: "London listening tommy" (we are able to change the places of the words) Here is TherapistProfile class from models/therapist.py: class TherapistProfile(NonAdminProfile): user = models.OneToOneField(Therapist, on_delete=models.CASCADE, related_name='therapist_profile') skills = models.ManyToManyField(TherapistSkill, blank=True) city = models.ManyToManyField(TherapistCity, blank=True) ... PS The "name" and "surname" fields are in Therapist class (which inherits them from user.py). In TherapistProfile the field is written as "user". I kinda know the logic: I need to split the sentence into words by space and search each word in each field of each object (if you … -
Django how to limit template to only two posts
i would like to only show the last two posts added on the template (preferably the ones posted today only), i have seen this being done but not on class based views. from .forms import PostForm from .models import Post from django.views.generic import ListView from django.views import generic from django.urls import reverse_lazy class homeView(ListView): model = Post template_name = 'MAG-page.html' MAG-page.html {% for post in object_list %} <div class="col-lg-6 col-md-12"> <div> <!--Image--> <div class="view overlay rounded z-depth-1-half mb-3"> <img src="{{post.Thumbnail.url}}" class="img-fluid" > <a> <div class="mask rgba-white-slight"></div> </a> </div> <!--Excerpt--> <div class="news-data"> <a href="" class="light-blue-text"> <h6> <i class="fas fa-plane"></i> <strong> {{post.author}}</strong> </h6> </a> <p> <strong> <i class="far fa-clock"></i> {{post.Date}}</strong> </p> </div> <h3> <a> <strong>{{post.title|safe}}</strong> </a> </h3> <p> {{post.Text|safe}}</p> </div> {% endfor %}