Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
displaying and submitting different forms in single template in Django according to request
I am a newbie and I am working on a project in Django 3.1.2, Here I am creating a profile page where User(admin) can see/edit his/her profile details and also change password. All these functionalities I want to perform on single page but I can't understand the logic . models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') These are the functions I have created but not able to call the functions according to requirement. views.py def profile(request): form = EditProfile() return render(request, 'admin1/profile.html', {'form': form}) def changePassword(request): if request.method == 'POST': print("hi") form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! return redirect('admin-profile') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'admin1/profile.html', { 'form': form }) def editProfile(request): form = EditUserProfile(request.POST, request.FILES, instance=request.user) if request.method == 'POST': form = EditUserProfile(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect('view-profile') context = {'form': form} return render(request, 'admin1/profile.html', context) urls.py path('profile/', views.profile, name="admin-profile"), path('editProfile/', views.editProfile, name="admin-edit-profile"), path('changePassword/', views.changePassword, … -
Foundation Modal instantly closing
Hi guys how are you doing? This is my first Django project, and Im using Foundation for building my frontend (all new to me). I want to display a foundation reveal modal, and it opens, but instantly closes, not letting me push the close button or do anything. I can see the modal well created, with the button and correct context var, but in less than a second it closes and page is refreshed This is my html code {% extends "panel.html" %} {% load static %} {% block panel-content %} <div class="grid-x medium-10"> <h3 class="cell medium-12" style="text-align: center;color: wheat;">Usuarios del Sistema</h3> <div class="cell medium-12">&nbsp </div> <div class="cell medium-11 small-9"></div> <a href="{% url 'users_app:user-register' %}" class="success button cell medium-1 small-3"><i class="fi-plus"></i>&nbsp Agregar</a> <table class="cell medium-12"> <thead> <th>Usuario</th> <th>Nombre</th> <th>Teléfono</th> <th>Última Conexión</th> <th>Rol</th> <th>Estado</th> <th>Acciones</th> </thead> <tbody> {% for user in users %} <tr> <td>{{ user.user_name }}</td> <td>{{ user.full_name }}</td> <td>{{ user.phone }}</td> <td>{{ user.last_login }}</td> <td>{{ user.get_role_name }}</td> <td> {% if user.is_active %} <span class="label success">Activo</span> {% else %} <span class="label alert">Inactivo</span> {% endif %} </td> <td> <div class="button-group"> <a href="#" class="button warning tiny"><i class="fi-eye"></i></a> {% if user.is_superuser %} <a href="#" class="button tiny disabled"><i class="fi-pencil"></i></a> <a href="#" class="button alert tiny … -
My Blog shows Same Content in Every post (Django)
I have created a blog using Django, I can add blogs in Django admin, but when I view blogs in my site, it shows the same content in every blog as was in the first blog that I added. -
CartItem matching query does not exist
So I get CartItem matching query does not exist error when I try to add to cart, I'm trying to check if the user already has that item in their cart and if they do not then it is supposed to be added, if they do then it will not be added again, When i click add to cart it gives me CartItem matching query does not exist. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem from django.contrib.auth.decorators import login_required from .forms import BookForm # Create your views here. def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already … -
Pagination using javascript only
I'm working on a Django project my code is javascript heavy, I want a way to do pagination with javascript only first i'm fetching from all_posts url to get all posts data fetch('/all_posts') .then(response => response.json()) .then(posts => { display_posts(user, posts) }) then the method display_posts create a card for each post and append it to <div id="all_posts"> in index.html function display_posts(userr, postss){ for (post in postss){ //create each post_container //put data inside it document.querySelector('#all_posts').append(post_container) } I can't go back to do it with Django loops and pagination in html, I want a way to do it using javascript only can anyone help me please and provide me with code examples on how to it using any plugin, thanks in advance -
does a user changing the title / slug cause an issue if i continue to get the correct post by pk?
Currently i have a django project where a user can ask a question and the title becomes the slug. MEaning the url is website/pk/slug To get to the url i use a basic DetailView which just uses the model. URLs path('question/<int:pk>/<str:slug>/', QuestionDetailView.as_view(), name='question-detail'), path('question/<int:pk>/<str:slug>/update/', QuestionUpdateView.as_view(), name='question-update'), View class QuestionDetailView(DetailView): model = Question When the user changes the title of the question, i do not update the slug but only the title. class QuestionUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Question form_class = QuestionForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): question = self.get_object() if self.request.user == question.author: return True return False This mean is the original url upon question creation was website/1245/How-do-i-blah i can still get to the question with any slug after website/1245/ i would think this might be a problem but i cannot see why, as google will index the slug and as i am looking up by pk if the title changes it should automatically return the right question. Why do i think this might cause problems in the future? And should i be looking up the question by pk and slug. -
How to make Django-Admin timezone aware?
I want to show all the datetime fields in databases in a different timezone than the default ('UTC') timezone only for the admin. I found a few proposed solutions which are more catered towards saving timezones per user. However I am looking for a solution which only solved the problem for the admin. Any suggestion will be much appreciated. -
Memcached not caching page if it's requested by artificial request. Django
I use memcached for caching a page for 1 hour. My settings are following: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } I use method decorator to cache the view. @method_decorator(cache_page(60 * 60), name='dispatch') I want to warm up cache every hour. I do it by emulating request to the view. login_url = LOGIN_URL target_url = TARGET_URL request = requests.session() response = request.get(login_url) token = response.cookies['csrftoken'] data={'username': username, 'password': password,'csrfmiddlewaretoken':token} response = request.post(login_url, data=data) response = request.get(target_url) However, unlike requesting the view myself (by hands) it doesn't work. What am I doing wrong? -
TypeError: __init__() missing 2 required positional arguments: 'to' and 'on_delete'
I am just fresher and trying to build my first Blog App. after setup every thing... I wrote some codes in models.py file ----- Models.py file code ================= from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=250) summary = models.TextField() slug = models.SlugField() body = models.TextField() author = models.ForeignKey() auther = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title ============= ============= ============ ======= but it is giving me error -- File "E:\BlogProject\blog\blogapp\models.py", line 6, in class BlogPost(models.Model): File "E:\BlogProject\blog\blogapp\models.py", line 12, in BlogPost author = models.ForeignKey() TypeError: init() missing 2 required positional arguments: 'to' and 'on_delete' ========== ============== ============== I will be very thankful for your suggestions. Thanks -
Should I add third party data to web application database?
I have a Django application that users fill in some background information, such as "graduated university". These fields are optional, so for some users, they can be empty. Given that, I have another service that crawls the web for the missing information. This service is completely decoupled from the Django application. It has its own schedule and saves the scraped data to S3 as JSON periodically. The Django application has admin pages that summarize user information. For these pages, I need to use the real application data which is stored in the application database, as well as the scraped data that resides in S3. Currently, I have a Django model named ScrapedUser that has a JSON field named data. To populate this model, I manually sync it with the data in S3. (Download files from S3 and create a ScrapedUser instance with it etc.) My question is, to use those different data sources together, should I populate my real user data in the application database with the third party data that I scraped from the web? In other words, I wonder if it would be better to map scraped information at ScrapedUser to the real User model. To better illustrate … -
Django ajax GET 403 (Forbidden)
I have a page of articles and a Load More button with ajax call in my Django app. The problem is that the Load More button works just when the user logged in to the site. If an anonymous user clicks on the button, it doesn't work, and sees the error below in the chrome console: In the network tab in chrome console I see this error: But I don't want to identify the user who clicked the button and want to show more posts to everyone! The ajax call is : // Load more posts in the main page $('.load-more').click(function () { var card_count = $(".card-count").length; $.ajax({ url: 'load-more', method: 'GET', data: { "card_count": card_count, }, success: function (data) { // Append more articles to the article List }, error: function (data) { } }); }); I do some search and tried some ways to pass the csrf_token or skip it: This link & This link But still stuck on this. How can I get rid of this error? Thanks for your help. -
Django CSRF cookie sending images with axios client
Good day. I need to send an image by the post method of a client with axios to a Django server but I get the following message on the server. Forbidden (CSRF cookie not set.): And the client gives me the following answer xhr.js:177 POST http://127.0.0.1:8000/xxxx/ 403 (Forbidden) How is it possible to solve this problem? It is possible to disable the CSRF cookie= This is the client code: var formData = new FormData(); formData.append("imagen", await fetch(`${filepath}`).then((e) => { return e.blob() }) .then((blob) => { let b: any = blob b.lastModifiedDate = new Date() b.name = '' return b as File }) ); const axios = require('axios'); axios({ url:url, method:'POST', data:formData }).then(function(res: any){ console.log(res) }).catch((error: any) =>{ console.log(error) //Network error comes in }); And this is the server view function (It just check the info to debug) def completeInfo (request): print(request) return HttpResponse("Bad Response") -
Django Wagtail [Errno 111] Connection refused form submission
I have a site that I made using Wagtail (Django) and set up a contact form with a landing page. When using this contact form on localhost, I can successfully add information on the contact form and submit it, which takes me to the landing page. However, I have hosted this on heroku, and now have a problem with submitting the contact form. When I have submitted the contact form, it gives me an error that the connection was refused [Errno 111]: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/core/views.py", line 24, in serve return page.serve(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/contrib/forms/models.py", line 300, in serve form_submission = self.process_form_submission(form) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/contrib/forms/models.py", line 341, in process_form_submission self.send_mail(form) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/contrib/forms/models.py", line 346, in send_mail send_mail(self.subject, self.render_email(form), addresses, self.from_address,) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/admin/mail.py", line 62, in send_mail return mail.send() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/app/.heroku/python/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/app/.heroku/python/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, … -
How to customize UserCreationForm validation in django
I'm currently trying to build user registration form using UserCreationForm but it doesn't suit my needs. First of all, Username field accepts not only alphabet symbols and digits but also @ . + - _. I want to make it accept only latin and cyrillic leterrs and digits but I could not find any information. Also i want to change it's other properties like maximum length. Also after we make these changes will both client and server sides validation process deny banned symbols? Here is some code I already have in forms.py: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and views.py: def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'register.html', context) -
Error Django Pillow : profiles.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed
Hi, I want to install Pillow + Django in Docker but Not works. ERRORS: profiles.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: profiles.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. My Stack Python 3.8 Django 3.1 Environtment: Docker : python:3.8.3-alpine Thanks so much -
Hello, I'm a. beginner at Django API and http GET Method doesn't work. It prints an error
In urls.py, which is in 'users' folder, which is containing migrations folder, localhost: 8000 /users is scripted. Then I typed http GET localhost:8000 on the command line after which Virtual environment had been activated. But It prints this error. http: error: ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10172bd60>: Failed to establish a new connection: [Errno 61] Connection refused')) while doing a GET request to URL: http://localhost:8000/ What's the problem? I've been stuck into this step so I couldn't go forward anymore. Please give me some help! -
What are the most important features in django?
I know this is off topic but i think a lot of people learning a lot of code and most companies require something more specific always. For example most of the websites out there have the same features. Ex Login,Register,API services etc. But in general, what are the most important Django features-skills a developer need to have? -
How to query the total number of "interest= Pending" object for any of my post added together?
In my project, anyone can submit any interest to any post, limited to 1 interest per post. Right now, i am trying to query the TOTAL number of interests (that is not accepted yet, meaning the status is still pending) that has been sent to any of my post, like all of them added up together, and I want that to be displayed in my account page. Is that possible to query it from the template based on the current code i have, and how can i do it? I have been trying the past hour but it hasn't be successful :( All help is appreciated thank you! models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField(max_length=5000, null=False, blank=False) class Interest(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) my_interest = models.TextField(max_length=5000, null=False, blank=False) class InterestInvite(models.Model): ACCEPT = "ACCEPT" DECLINE = "DECLINE" PENDING = "PENDING" STATUS_CHOICES = [ (ACCEPT, "accept"), (DECLINE, "decline"), (PENDING, "pending"), ] interest = models.OneToOneField(Interest, on_delete=models.CASCADE, related_name="interest_invite") status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING) views.py def account_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) context['account'] = account … -
How can I filter a intersection of manytomany field in django?
i want to filter query , and one of field is manytomany . how to filter intersection in manytomany fields my model is: class Event(models.Model): category = models.ManyToManyField(Category, blank=True) title = models.CharField(max_length=400) views: search_subcategory = Q() if subcategory != 'null': total_filter.append('subcategory') subcategory = subcategory.split(",") for i in range(0, len(subcategory)): subcategory[i] = int(subcategory[i]) for x in subcategory: search_subcategory &= Q(subcategory=x) search_title = Q() if title != '': total_filter.append('title') search_title = Q(title__icontains=title) filter_query = Event.objects.filter(search_category & search_title).distinct() -
why 502 error in google app engine flexible environment django?
I want to deploy Django + CloudSQL (Postgresql) + app engine flexible environment in google cloud. My app.yaml setting runtime: python #gunicorn env : flex entrypoint : gunicorn -b 127.0.0.1 -p 8000 config.wsgi --timeout 120 #instance_class : F4 beta_settings: cloud_sql_instances: icandoit-2021start:asia-northeast3:test-pybo=tcp:5434 runtime_config: python_version: 3 gcloud app logs tail result 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [1] [INFO] Starting gunicorn 19.7.1 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1) 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [1] [INFO] Using worker: sync 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [8] [INFO] Booting worker with pid: 8 2021-02-03 11:09:18 default[20210203t170353] [2021-02-03 11:09:18 +0000] [1] [INFO] Handling signal: term 2021-02-03 11:09:18 default[20210203t170353] [2021-02-03 11:09:18 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-02-03 11:09:19 default[20210203t170353] [2021-02-03 11:09:19 +0000] [1] [INFO] Shutting down: Master 2021-02-03 11:09:19 default[20210203t170353] [2021-02-03 11:09:19 +0000] [1] [INFO] Handling signal: term 2021-02-03 11:09:19 default[20210203t170353] [2021-02-03 11:09:19 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-02-03 11:09:20 default[20210203t170353] [2021-02-03 11:09:20 +0000] [1] [INFO] Shutting down: Master 2021-02-03 11:14:25 default[20210203t195827] "GET /" 502 django and gunicon works normally. Why Do I Have 502 Errors? -
Elastic Apm python agent connection problem
I have a very basic django apm agent setup: ELASTIC_APM = { # Set required service name. Allowed characters: # a-z, A-Z, 0-9, -, _, and space 'SERVICE_NAME': 'bourse', # Set custom APM Server URL (default: http://localhost:8200) 'SERVER_URL': '127.0.0.1:8200', 'LOG_LEVEL': "debug", 'LOG_FILE': "/home/hamed/Desktop/log.txt",} my apm server is up and running on localhost:8200. But it seems my apm agent can't make a connection to the apm server.Here is a part of my log file that I think cause the problem: Skipping instrumentation of urllib3. Module botocore.vendored.requests.packages.urllib3.connectionpool not found HTTP error while fetching remote config: HTTPConnectionPool(host='config', port=80): Max retries exceeded with url: /v1/agents (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe2625ed610>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) this is my apm agent log file. ps: On my apm server I'm not receiving any request from my agent. I checked the apm server log files. Please help me. I'm stuck. -
NoReverseMatch at /products/update/6/ Reverse for 'product_update' with arguments '('',)' not found
I want to go to the product update method through the URL with the product ID by clicking on the product list but this error is coming. I don't understand what I did wrong here. The following codes are given. Product list: {% for product in products %} <tr> <td> <img width="55px" height="55px" src="{{ product.photo.url }}" /> </td> <td><input class="groupCheck" type="checkbox" value="{{product.id}}" id="{{product.id}}"/></td> <td> <a class="btn product-update" href="{% url 'accpack:product_update' pk=product.id %}">{{product.product_code}}</a> </td> <td>{{product}}</td> <td> <a class="far fa-plus-square fa-1x js-create-product_attribute" data-url="{% url 'accpack:products_attributes_create' pk=product.id %}" data-toggle="modal" data-target="#modal-product_attribute"></a> &nbsp <a class="far fa-edit fa-1x js-create-product_attribute" data-url="{% url 'accpack:products_attributes_update' pk=product.id %}" data-toggle="modal" data-target="#modal-product_attribute"></a> </td> <td>{{product.cost_price}}</td> <td>{{product.sale_price}}</td> <td>{{product.quantity_per_unit}}</td> <td>{{product.brand}}</td> </tr> {% endfor %} url: # Product url url('products/$', views.product_index, name="products"), url('products/create/$', views.product_create, name="product_create"), url('products/update/(?P<pk>\d+)/$', views.product_update, name="product_update"), view: def product_update(request, pk): product = get_object_or_404(Product, pk=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=product) else: form = ProductForm(instance=product) return save_product_form(request, form, 'products/partial_product_update.html') partial_product_update.html: <form id="Form" method="post" action="{% url 'accpack:product_update' pk %}" class="col s12" enctype="multipart/form-data"> {% csrf_token %} <br> {% crispy form form.helper %} <br> </form> Traceback: Traceback (most recent call last): File "C:\Users\Dell\anaconda3\envs\webapp\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\anaconda3\envs\webapp\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\MEGA\djangoprojects\myprojects\accpack\views\products.py", line 52, in … -
Conditional Counter in Django template for loops
I want my for loop to end after the if-condition is satisfied thrice while rendering my "products" details in my eCommerce website. category.html {% for item in subcategory %} {% with counter="0" %} <div> <h5 class="my-0" style="font-weight: 700;">{{ item.title }}</h3> </div> <div class="row"> {% for i in products %} {% if i.category.id == item.id %} {{ counter|add:"1" }} {% if counter == "3" %} {{ break}} {% endif %} <div class="col-3 p-0 px-1 my-3"> <a href="{% url 'product_detail' i.id i.slug %}"> <img class="w-100" id="catbox" src="{{ i.image.url }}" alt=""> </a> </div> {% endif %} {% endfor %} <div class="col-3 p-0 my-3 text-center" style="border-radius: 10px;background: url({% static 'images/temp.jpeg' %}); background-size: cover;"> <div class="h-100 w-100 m-0 p-0" style="background: rgba(0, 0, 0, 0.61);border-radius: 10px;"> <div style="position: relative;top: 50%;transform: translateY(-50%);"> <a href="{% url 'category_product' item.id item.slug %}" class="text-white " href="#"><strong>SEE ALL</strong></a> </div> </div> </div> </div> {% endwith %} {% endfor %} I want the second for loop, i.e., {% for i in products %} to break once the if condition, i.e., {% if i.category.id == item.id %} inside it is satisfied thrice. But the counter I set to 0 is incremented to 1 repeatedly instead of being incremented recurrently with the for loop. Since there … -
Make Django db optional, but still functional if needed
So in my django project i have my databse set up like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("DEFAULTDB_NAME"), 'USER': env("DEFAULTDB_USER"), 'PASSWORD': env("DEFAULTDB_PASS"), 'HOST': env("DEFAULTDB_HOST") }, "remote": { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("REMOTEDB_NAME"), 'USER': env("REMOTEDB_USER"), 'PASSWORD': env("REMOTEDB_PASS"), 'HOST': env("REMOTEDB_HOST") } } What i want is for the remote database to be optional, so if i run my server it works even if the connection to remote databse fails. I have tried the solution mentioned here, But with this if the connection is lost when i start the server i can't use my remote database until i restart my server -
Access all content from a post in Django
I apologize in advance if the question is poorly written. tried my best to explain my problem as good as i could :). Thanks for helping! I have currently made a django web server. i am trying to access all the content from all my different posts and display them by eachother within "ul" and "li" HTML tags. I am currently only able to display the Main Posts title, and not the rest of the content. The result i am currently getting is this. My Book List: * The Hunger Games and the result i am wanting to get is this. My Book List: * Title: The hunger games * Author: Suzanne Collins * Publisher: Scholastic Press * Published: 2008-09-14 I've tried multiple solutions to try and make it work. But i cant find any solution on youtube or any related social media website, so i resorted to here. models.py file from django.db import models # Create your models here. class Books(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) publisher = models.CharField(max_length=50) pulished = models.DateField() def __str__(self): return self.title Views.py file from django.shortcuts import render from .models import Books # Create your views here. def book_list(request): books = Books.objects.all() context = …