Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OAuth2 grant for a concrete scenario
I have to use the OAuth2 protocol to perform the authorization in our system. The idea is to have a separated Authentication/Authorization server and a resource server (an API, could be more in the future). Then we have a web application (backend+frontend) that needs to use the API (the resource server). It is important to say that this web application needs user + password to perform the authentication, and user and pass will be placed at the authentication/authorization server. So: WebApp -> uses user + password to authenticate against -> auth server Then we need to perform the authorization. Which OAuth2 grant is the right one here? I have reviewed all the OAuth2 grants but it is not clear because here I don't have a "third party" with their own credentials to apply Auth Code + PKCE. The web application I mentioned it is being developed by our own organization and the credentials are centralized in the auth server. So I have a separated API and a web app that needs to use the API to authenticate and to access to the protected resources. The ** password grant flow** is the one closer to my thoughts but I read that … -
Cannot import name error in Django split models
I have split the Django models into multiple model files following the follow file tree structure, +-api(app)-+ +-__init__.py +-models -+ | +-__init__.py +-model1.py +-model2.py +-model3.py +-serializers-+ | +-__init__.py +- model1_serializer.py +-views +-apps.py ... my __init__.py in models looks like, from .model1 import * from .model2 import * and serializer __init__.py files look like this, from .model1_serializer import MBTITypeSerializer I have splitter views files and serializer files. When I try to import models some of them imports without any problem, but some imports not working. I have observed if I change the import order in __init__.py file the working imports change. This is how I tried to import models, in serializers from api.models import MBTIType ... Here is the error trace, Traceback (most recent call last): File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "D:\ \implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\\implementation\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\\implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\\implementation\backend\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "D:\\implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\\implementation\backend\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\\implementation\backend\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\\implementation\backend\venv\lib\site-packages\django\apps\config.py", line 301, in … -
Does Django clean malicious requests for safety?
I am wondering if using the below method is considered safe if the param being passed by client side is not checked. classmodel.objects.filter(id=1).update(data=user_passed_param) Can user send something malicious to the database that causes any issue? I do understand this is not raw sql request being used here meaning User cant delete anything in the Database as Django will be updating the data field only if that field was TextField or CharField it will be updated similarly to a string “user_passedtextetc” meaning user cant pass anything to the database like in a raw sql request. -
How to collect all validations errors when using custom class validator
I'm using a custom class validator to validate serializer fields, and I would like to raise ValidationError for all fields so API error response has fields with all errors instead of a single error, instead, now I'm getting the validation error only for single fields. Before I've used method validations inside my serializer and it worked as I need, but this is not the case with class validators. Here is how validators look like class TitleValidator: MIN_TITLE_LENGTH = 20 def __call__(self, attrs: dict): title = attrs.get("title", "") if len(title) < self.MIN_TITLE_LENGTH: raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}") return title class SlugsValidator: def __call__(self, attrs): slug = attrs.get("slug", "") if len(slug) < 10: raise ValidationError("Slug must be at least 10 characters long") return slug -
change the label of a field in a django form
I am working on a blog website project. I am using Django crispy form to create blog posts. Users can post articles by clicking the post button. On the add post page, users have to provide title, content, image. User also have to select category. blog/model.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True, blank=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(null=True, blank=True, default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = models.TextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) views.py from django.shortcuts import render from .models import Post from django.views.generic import CreateView from django.contrib.auth.mixins import LoginRequiredMixin class UserPostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'image', 'cid'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) post_form.py {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Add Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-primary btn-sm btn-block"> Post </button> </div> </form> </div> {% endblock … -
Django: get only objects with max foreignkey count
question is quite simple but possible unsolvable with Django. For example i have a model class MyModel(models.Model) field_a = models.IntegerField() field_b = models.CharField() field_c = models.ForegnKey(MyOtherModel) Question is how to select only objects that have maximal count of relations with MyOtherModel and preferable(almost mandatory) with only single queryset? Lets say, we have 100 entries alltogether, 50 pcs. point to field_c_id=1, 40 pcs. to field_c_id=2 and rest 10 pcs. entries to field_c_id = 3. I need only those which point to field_c_id=1? as 50 would be maximal count. Thanks... -
How to exclude routes with mozilla-django-oidc
In a django app how can I exclude Authorization for some endpoints? I am using mozilla-django-oidc . With a custom class EnhancedOIDCAuthentication(OIDCAuthentication): in order to get the roles from the JWT. For requests with a valid JWT token the authorization works fine. However, I am trying to find a way to exclude some APIs. I have tried @permission_classes([IsAuthenticated]) but without any effect. This class works only rest_framework.authentication The official documentation doesn't state something https://mozilla-django-oidc.readthedocs.io/en/stable/index.html -
Redirection after submit not working after adding extra code on top. Probably a priority problem
I have a script that redirects the user to the previous page_id after submit: a user would connect to page page_A Would click on product_1, Be redirected to product_1 page, Leave a review and upon clicking submit be redirected to page_id This has been working fine for a while. I decided to implement djang-hitcount in a function base view (used the code here how to use Django Hitcount in a function based view rather than a class?), as I wanted to see how many unique IP addressed where connecting. Since then the comment submission code is not working anymore. As an example: If User land on Page_A the URL would show this: http://localhost:8000/Page/A When clickin on product_1, the url would then display the following:http://localhost:8000/product/1?next=/Page/A When submitting a review the user would be redirected to : http://localhost:8000/Page/1 However now, the user is redirected to http://localhost:8000/Page/1 which obvioulsy does not exist - it should be Page A, but instead attributes the product_id to the page_id. I suspect it's because the new django-hitcount code has taken over some of the initial logic. Maybe some indention problem? Here it goes: Views.py def show_event(request, event_id): submitted = False form = 'ReviewForm' formonpage = 'ReviewForm' ###<-- … -
Django and Flutter configuration
How do i configure Django and Flutter for local development and how do i configure them for the deployment in a server? (Flutter as a frontend web project). I have tried to add static files directories in settings file. But I'm not sure what value do i give to this variable. Do i assign os.path.join(BASE_DIR, 'flutter_project/build/web/assets') to static files directories or do i have to assign something else? Now that you’re ready to post your question, read through it from start to finish. Does it make sense? -
AttributeError: module 'signal' has no attribute 'SIGHUP'
I am trying to integrate mod_wsgi into my django project on Windows 10. While I was able to install mod_wsgi into my virtual environment, I am running into errors while trying the command python manage.py runmodwsgi. (venv) PS D:\Tutorials\Python\Projects\ADSS> python manage.py runmodwsgi Successfully ran command. Server URL : http://localhost:8000/ Server Root : C:/Users/admin/AppData/Local/Temp/mod_wsgi-localhost-8000-admin Server Conf : C:/Users/admin/AppData/Local/Temp/mod_wsgi-localhost-8000-admin/httpd.conf Error Log File : C:/Users/admin/AppData/Local/Temp/mod_wsgi-localhost-8000-admin/error_log (warn) Operating Mode : daemon Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.cp1252 Traceback (most recent call last): File "D:\Tutorials\Python\Projects\ADSS\manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py", line 162, in handle signal.signal(signal.SIGHUP, handler) AttributeError: module 'signal' has no attribute 'SIGHUP' Google seems to suggest that signal.SIGHUP, signal.SIGUSR1 and signal.SIGWINCH as being used by my mod_wsgi installation aren't supported on Windows. So I tried the following two methods in .\venv\Lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py: … -
Request Pending After A DELETE request
I am working with Reactjs and I am having and issue while sending request, Last week everthing was working perfectly and then I started to face that request issue. When I send GET, PUT, POST request everything works fine with no problems, when I send a DELETE request it gets sent and I recieve a response with status 204, but any type of request I send after it, it stucks in a pending state forever. I tired different Projets same issue, different PC same issue. When I access my dev server from another PC everythings works perfectly no problems, seem like the problem happens only when I send request from the same machine where the dev server is strated. I pulled an old version of the code where I was sure everything were fine and I got same issue, I tried to empty cache, different browsers, I event emptied my whole disk and installed windows again. I tried the DELETE request with Postman and it stucked in pending state. I tried different backends same problem. The Back-end is with Django, I Don't have access the back-end code but I tried same proccess with Postman and there was no issue. api … -
Fetching users data based on username input in urls
I am little bit new to django and was working on my first instagram clone project all by myself. I got confused in a place where I needed to fetch user data based on 127.0.0.1:8000/username and I found a useful but useless answer(for me) from medium(.com) .The author was using class based view. In class based view, I didnot get any documentation to use multiple models as much as I searched so i had to do it with function based view as I have not learned class based view yet.I had to use post model, profile model and User model to get data for profile page. This is the code that somehow worked but should I use this view? from django.contrib.auth.models import User from .models import Profile #profile view def profile_data(request, username): mydata = User.objects.get(username=username) myprofile = Profile.objects.filter(user=mydata) mycontext ={'profile': myprofile} return render(request,'firstapp/profile.html', context=mycontext) #in urls.py, from firstapp import views path('<str:username>/', views.profile_data , name='profile'), #in models.py, from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) fullname = models.CharField(max_length=100) def __str__(self): return self.fullname In firstapp/profile.html, <a href="#" class="text-3xl mt-5 text-center">{{user.profile.fullname}} But I got confused on how to attatch my Profile model in it. So I created this, my own function-based … -
How do I import multiple views for urls.py?
I need to import views from horoscopes and dates. but when importing them into urls.py there is a conflict because of which only one views is perceived. so that's the question, how do I import multiple views? ` from django.contrib import admin from django.urls import path import horoscopes import dates urlpatterns = [ path('admin/', admin.site.urls), path('horoscopes/leon', horoscopes.views.monday), path('dates/monday', dates.views.monday), ] ` I've tried both and: ` import horoscopes import dates urlpatterns = [ path('admin/', admin.site.urls), path('horoscopes/leon', horoscopes.views.monday), path('dates/monday', dates.views.monday), ` as well as: ` from django.contrib import admin from django.urls import path from horoscopes import views as horoscopes_views from dates import views as dates_views urlpatterns = [ path('admin/', admin.site.urls), path('horoscopes/leon', views.leon), path('dates/monday', views.monday), ] ` both options ignore one of the views -
Get data from django user model
This is my model: from django.contrib.auth.models import User class User_Model(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) nickname = models.CharField(User.username, max_length=2000, null=True) def __str__(self): return f"{self.user}" I would like to save into nickname in this model value of "username" from User model. I want to use it later in vievs.py to send them as context class Users(ListView): model = User_Model context_object_name = "users" paginate_by = 10 template_name = "Messenger/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(User_Model.objects.values('nickname'))) return context Generally i try to do stuff like here but i want to list nicknames: https://www.youtube.com/watch?v=jqSl36xR9Ys I tried to get those from one to one field but i think i done this wrong way -
Page not found 404 django
Can anyone help me with this please? When I try to access i get the following error: Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in backend.urls, Django tried these URL patterns, in this order: admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py from django.contrib import admin from django.urls import path, include from Notes.views import NotesViewset from rest_framework.routers import DefaultRouter router=DefaultRouter() router.register('/posts',NotesViewset) urlpatterns = [ path('admin/', admin.site.urls), path(' ', include(router.urls)) ] views.py from django.shortcuts import render from .models import Note from rest_framework import viewsets from .serializers import NoteSerializer class NotesViewset(viewsets.ModelViewSet): serializer=NoteSerializer queryset=Note.objects.all() admin.py from django.contrib import admin I'm new to programming and I hope someone can help me. Thanks -
How to resolve a 502 Bad Gateway when deploying Django App on Azure with Gunicorn and Nginx
I've been trying to deploy a Django app on Azure for about a week. My instructor followed the exact same setup I used and he was able deploy the same app to Azure. I've followed several tutorials, this one from Digital Ocean in particular, and I always get the same result. When I go the the IP address I get a 502 Bad Gateway. The only change I make from the tutorial is opening up ports 8000 and 80. I do that through Azure's Networking settings. I've tried all of the troubleshooting recommendations at the end of that tutorial. I've restarted Gunicorn, Nginx, and even the VM. On Azure I have a Standard B1s VM running Ubuntu 22.04. I do not have a custom domain, just the static IP assigned by Azure. I can deploy the app on the development server just fine. If I bind 0.0.0.0:8000 to gunicorn that also will display the site (minus styling). Gunicorn starts and runs. When I check the status after starting the service it shows the active green dot. Immediately after trying to access the site via the IP address, if I check Gunicorn status again it reads: gunicorn.socket: Failed with result 'service-start-limit-hit' … -
How to format template with django?
I have a django application. And I try to format some data. So I have this method: def show_extracted_data_from_file(self, file_content): self.extractingText.extract_text_from_image(file_content) regexes = [ self.verdi_total_number_fruit_regex(), self.verdi_fruit_name_regex(), self.verdi_total_fruit_cost_regex(), ] matches = [self.findallfruit(regex) for regex in regexes] return tabulate( zip_longest(*matches), # type: ignore headers=[ "aantal fruit", "naam fruit", "kosten fruit", ], ) that produces this result: 6 W a t e r m e l o e n e n 4 6 , 2 0 7 5 W a t e r m e l o e n e n 5 7 7 , 5 0 9 W a t e r m e l o e n e n 6 9 , 3 0 but as you can see it is one horizontal output. But I want every item under each other. that it will looks like: 6 Watermeloenen 577,50 75 Watermeloenen 69,30 9 watermeloenen 46,20 and the template: <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form.as_p }} </div> <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table> <tr> {% for cell in content %} <td>{{ cell }}</td> {% endfor %} </tr> </table> </div> </div> </div> </div> … -
Django ModelForms using get_or_create
I am using ModelForms to create and render my form, and it is working fine. I however want to use get_or_create method instead of using if form.is_valid(): method but i do not know ho to how to use it with ModelForms. views.py def books(request): genres_names = Genre.objects.all() if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") genres_name = request.POST.get("genres") genres, created = Genre.objects.get_or_create(name=genres_name) try: if form.is_valid(): genre = form.save(commit=False) genre.save() if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create(genre=genre, book_title=name, book=f) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form":form, "genres_names":genres_names}) models.py class Genre(models.Model): genres = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Genre" def __str__(self): return self.genres class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books") genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class BookInfo(forms.ModelForm): class Meta: model = Genre fields = ["genres",] widgets = { "genres":forms.TextInput(attrs={"list":"genres"}) } class BookFile(BookInfo): book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + ["book",] my template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" … -
ModuleNotFoundError: No module named 'sandbox': Docker Build failed with error code [1]
I'm building a django oscar commerce v 3.2 project(https://github.com/django-oscar/django-oscar) on ubuntu 20.04 on GCP with a virtual environment using python 3.8.14 and getting the following error when i run the docker build command using docker-compose -f docker-compose-full.yml up ModuleNotFoundError: No module named 'sandbox' The trace is with regards to the following line in my settings.py: from sandbox.environment import EnvironmentChecker My project folder structure is as follows : django-commerce |- src |- sandbox | |- __init__.py | |- environment.py | |- settings.py | |- manage.py | |- urls.py | |- wsgi.py | |- uwsgi.ini |- DockerFile |- MakeFile |- Manifest.in |- setup.py |- setup.cfg The top lines in my Settings.py import os import sys import logging.config from django.utils.translation import gettext_lazy as _ from sandbox.environment import EnvironmentChecker Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Path helper location = lambda x: os.path.join( os.path.dirname(os.path.realpath(__file__)), x) My wsgi.py # isort:skip import os import sys root_path = os.path.abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(root_path, 'django-commerce')) sys.path.insert(0, root_path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application # isort:skip application = get_wsgi_application() I've also tried adding django-commerce.sandbox to my INSTALLED_APPS in settings.py as a last try but its not working. I've spent hours trying this to work. Help appreciated. … -
Django DEBUG False not working in the Production Environment
I am new to Django and Python world, I am currently working on an Dajngo site, which is hosted on a Ubuntu20.04 VM. Upon hosting the site to the production, I noticed that, although the DEBUG is set to False in the prodiuction settings. I still see the Django DEBUG erros as if the DEBUG is set to True . When I run python manage.py runserver command on the VM I get the below error. CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Folder structure . ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-310.pyc │ ├── urls.cpython-310.pyc │ ├── views.cpython-310.pyc │ └── wsgi.cpython-310.pyc ├── settings │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── base.cpython-310.pyc │ │ ├── local.cpython-310.pyc │ │ └── production.cpython-310.pyc │ ├── base.py │ ├── local.py │ └── production.py base.py (Common settings) import os from os.path import dirname, join import posixpath from posixpath import join from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '393266f4-9cc7-4cfe-96a8-2f2809e53e32' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #ALLOWED_HOSTS = [] # Application references INSTALLED_APPS = [ # … -
OperationalError at /admin/card/group/ no such table: card_group
i created a table named group and also run makemigrations and migrate and also registered it in admin.py but it is showing error when i opening it in admin panel. this is my models.py class group(models.Model): dish_category = models.CharField(max_length=255) def __str__(self): return self.dish_category this is my admin.py from .models import group admin.site.register(group) i also reset db and run migration again but it not works the groups table is showing in db but when i click it it shows error that OperationalError at /admin/card/group/ no such table: card_group -
How to create dynamically jstree in django
how to create dynamic jstree in django website Actually, I don't know what type of json data send in ajax request for creating jstree. -
Django Rest Framework very slow on Azure
I had migrated from Heroku to Microsft Azure, and the speed is really very slow, my App service is having the following specs : P1V2 210 total ACU 3.5 GB memory Dv2-Series compute equivalent then when it comes to my Azure Database for PostgreSQL flexible server, the following are the specs : General Purpose (2-64 vCores) - Balanced configuration for most common workloads Am sure all these Specs are higher than the default Heroku specs it used to give, but why is my Django project very slow when it comes to response time of the API requests ? -
Loading category tags with load more button
i am new to jquery , i have implemented a load more button on my blog app using jquery however the categories tags doesnt get displayed on the html when i click on the load more button Every thing works fine so far, i can't just display the tags on the post card, it keeps returning undefined note: 'i am getting my categories with a many to many field relationship' enter image description here Here is my views : ` def home(request): post = BlogPost.objects.all()[0:5] total_post = BlogPost.objects.count() context = {'post': post, 'total_post':total_post} return render(request,'blog/home.html', context) def load_more(request): # get total items currently being displayed total_item = int(request.GET.get('total_item')) # amount of additional posts to be displayed when i click on load more limit = 3 posts = list(BlogPost.objects.values()[total_item:total_item+limit]) print(BlogPost.objects.all()) data = { 'posts':posts, } return JsonResponse(data=data) here is my template: <div class="blogpost-container"> <div class="blogposts" id="blog-content"> {% for post in post %} <div class="post"> <img id="img-src" src="{{post.image.url}} " image-url="{{post.image.url}}" alt=""> <p><strong>{{post.title}}</strong></p> {% for category in post.category.all%} <h3>{{category}}</h3> {%endfor%} <a id="post-detail-link" href="{% url 'detail' post.id %}" detail-url="{% url 'detail' post.id %}"><h2>{{post.summary}}</h2></a> </div> {%endfor%} </div> </div> <div class="add-more" data-url='{% url "load_more" %}'id="add-btn"> <button type="button" class="more-content">load more</button> </div> <div class="alert no-more-data" role="alert" id="alert"> No … -
How to make a '\n' or '<br/>' work rather than display it using django and html template?
I'm facing a serious problem with html and django. What I want to do: Create a table Fill the table with python string The most important one that I want to make line break for the string What I've tried: Use '\n' in the string Use '' in the String But they don't work, they are both displayed on the browser, I don't how to fix it. Can anyone help, Thanks a lot. ` <table border='1'> {% for x in datas %} <tr> <td>{{ x.0 }}</td> <td>{{ x.1 }}</td> <td>{{ x.3 }}</td> </tr> {% endfor %} </table> x.3 is a string and I tried both '\n' and <br/> in it `