Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to do search with pagination using Django
You can easily understand which functionality i'm trying to add this pagination Using option, i want to show limited data like if user select 10 then number of data should display 10 Next, if user enter page number 2 then it go to page number 2 form.html <form class="form-inline" method="GET" action="{% url 'bookings:cancelled_bookings_list' %}"> {% csrf_token %} <select class="form-control w-50" data-selected="Data" name="no_of_data"> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> <br> <div class="input-group"> <input type="text" class="form-control w-25" placeholder="Enter Page No" name="page_no"> <div class="input-group-append"> <button class="btn btn-primary" type="submit" id="button-addon2">Go</button> </div> </div> </form> views.py page = request.GET.get('page', 1) paginator = Paginator(bookings, PAGE_SIZE) try: bookings = paginator.page(page) except PageNotAnInteger: bookings = paginator.page(1) except EmptyPage: bookings = paginator.page(paginator.num_pages) if request.method == "GET": no_of_data = request.GET.get('no_of_data') page_no = request.GET.get("page_no") paginate_by = no_of_data -
Can DRF serializer combine a few fields into a nested JSON?
I have a model of a product for Internet shop. Can I write a serializer that will wrap up a few fields in a nested JSON? For example: class Product(models.Model): product_type = models.CharField( choices=ProductType.choices, max_length=20 ) vendor_code = models.CharField(max_length=20) name = models.CharField( max_length=100, default=vendor_code ) material = models.CharField( choices=Material.choices, max_length=20 ) coating = models.CharField( choices=Coating.choices, default=Coating.NO_COATING, max_length=20 ) gem_type = models.CharField( choices=GemType.choices, default=GemType.NO_GEM, max_length=20 ) gem = models.CharField( choices=Gem.choices, blank=True, null=True, max_length=20 ) I want some fields combined into nested JSON when serializing: { 'product_type': ..., 'vendor_code': ..., 'characteristics': { 'material': ..., 'coating': ..., ... } Is it possible in DRF? -
How to enter data without textarea Django?
I have a form that looks like stackoverflow textarea I am trying to add a product. The description of which will be entered through this form. But I don't know how to insert textarea or inpur here html: <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> </div> </div> </div> </div> </div> vievs: def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models: text = models.TextField('Текст статьи') -
How do I connect to my Django local webserver using another device through ip address?
I created a dummy website using Django, python, HTML, CSS, and JavaScript recently. After completing it I tested the website by starting the server. python3 manage.py runserver I was able to open the website in a browser in the local machine using the link 127.0.0.1:8000/ Now, I want to connect to this server using my android device. As my first step I started a hotspot on my android which I've connected my pc by wifi in order to bring the client and server in the same network. Then I figured out the local IP address of my PC and I've switched off the firewall on my PC. After doing that I ran the Django runserver command with this address, python3 manage.py runserver 0.0.0.0:8000 And just like before I am able to use the website without a problem in my local machine/PC. However, when I tried to connect to this with my mobile using the link, 192.168.45.220:8000 Where 192.168.45.220 is the IP address of the PC which I'm running as the current local server. I get a error message as The site can't be reached 127.0.0.1 refused to connect ERR_CONNECTION_REFUSED I don't understand what I am doing wrong. Can someone let … -
How to customize validation messages in Django
I would like to know how to customize the Validation message when using UniqueConstraint to create unique constraints on multiple columns (including foreign keys) of Model in Django. In Django, I am creating a system for parents to apply for school lunches for their children. An account exists for each parent, and one or more children are associated with one parent. When parents log in to the school lunch application screen, select their child and date, and press the school lunch application button to complete the application. The validation of this application form did not go well. We use UniqueConstraints for multiple columns (child, date) in the Lunch model to avoid duplicate lunch requests for the same child on the same date. By default, the error message is confusing, so I tried to change the validation message, but it didn't work. Specifically, I created check_duplicate as a class method in the Lunch model and called it from the clean method of the form (ModelForm). At this time, both the validation message that I created and the default message are displayed on the actual screen. ・Message I created (child has already applied for yyyy/mm/dd school lunch.) ・Default message (Lunch with this … -
is it posible to order_by "NOT ILIKE search%" in django?
i'm trying to sort the trigram search result in postgres not only by the distance but prefix and suffix too. I know the trigram result put more weight on leading matches but sometime suffix matches showing closer distance. is it possible to order by search_on NOT ILIKE keyword% in django? -
Edit Data in Django Unable to show the data
I'm using Django to build a website. Modal bootstrap is what I'm utilizing. All works good for add, and delete data. However, In the Django form, I am unable to appear the data stored in the database for the update. Appreciate your help maybe I did something wrong with my code. I am not sure if my html or modal is correct. Thank you -->> HTML <<-- <!-- Table Header --> <thead> <tr> <th>User ID</th> <th>Username</th> <th>First Name</th> <th>Middle Name</th> <th>Last Name</th> <th>Role</th> <th>Created Date</th> <th>Modified Date</th> <th>Status</th> <th>Settings</th> </tr> </thead> <!-- Table Body --> <tbody> {% for members in member %} <tr> <td>{{members.id}}</td> <td>{{members.username}}</td> <td>{{members.first_name}}</td> <td>{{members.middle_name}}</td> <td>{{members.last_name}}</td> <td>{% if members.role %}{{members.get_role}}{% endif %}</td> <td>{{members.created_date}}</td> <td>{{members.modified_date}}</td> <td> {% if members.status == 1 %} <button type="button" class="btn btn-success rounded-pill">{{members.get_status}}</button> {% elif members.status == 2 %} <button type="button" class="btn btn-danger rounded-pill">{{members.get_status}}</button> {% elif members.status == 3 %} <button type="button" class="btn btn-secondary rounded-pill">{{members.get_status}}</button> {% endif %} </td> <td> <a href="#" data-toggle="modal" data-target="#viewUserModal{{ members.id }}"><i class='bx bxs-folder-open' data-toggle="tooltip" title="View"></i></a> <a href="#" data-toggle="modal" data-target="#editUserModal{{ members.id }}"><i class='bx bxs-edit' data-toggle="tooltip" title="Edit"></i></a> <a href="#" data-toggle="modal" data-target="#deleteModal{{ members.id }}"><i class='bx bx-trash' data-toggle="tooltip" title="Delete" ></i></a> </td> </tr> {% include 'includes/modals.html' %} {% endfor %} </tbody> <!-- End of Table … -
How to use a function in another class and modify it Django
Sup, need to use a function in a different class without losing the model, while still being able to change the function(not important, I can rewrite func into more flexible func). Can't solve this issue at least 10 hours. Google didnt help =( I know code is a little dirty, I will clean that :D Don't worry class head(View): template_name = "dental/mainpage.html" model = signup def get(self,request): if request.method == 'GET': form = UserSign return render(request, "dental/mainpage.html", {"form": form}) def FormSign(self,request): if request.method == 'POST': form = UserSign if form.is_valid(): body = { 'Name': form.cleaned_data['Name'], 'email': form.cleaned_data['email'], 'Number': form.cleaned_data['Number'], } info_user = "\n".join(body.values()) send_mail( 'Sign', info_user, 'eric1122221@mail.ru', ['eric1122221@mail.ru'], fail_silently=False) return render(request, "dental/mainpage.html", {"form": form}) #self.template_name return render(request, "dental/mainpage.html", {"form": form}) class stockpage(ListView): template_name = "dental/stocks.html" model = stock context_object_name = "stocks" -
Uploading image via django from react is showing error of UnicodeDecodeError: 'utf-8'
I am building a Blog App in React and Django and I am trying to upload an image from react in django But It is showing UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 136: invalid start byte views.py class BlogCreateView(APIView): serializer_class = BlogSerializer def post(self, request, *args, **kwargs): print(request.body) data = json.loads(request.body) print(data) return Response({"status": "SUCCESS"}) serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ("id", "image") App.js function BlogCreate() { const [image, setImage] = useState(null); const saveBlog = () => { let form_data = new FormData(); form_data.append("image", image, image.name) const headers = { "Content-Type": "multipart/form-data", Accept: "application/json", } axios.post("http://127.0.0.1:8000/blog_create/", form_data, {headers:headers}).then((res) => { console.log(res) }) return ( <> <input type="file" onInput={(e) => setImage(e.target.files[0])} /> <button type='button' onClick={saveBlog}>Save</button> </> ) } } } When I use for loop like :- for data in request.data: json_accep = data.replace("'", "\"") get = json.loads(json_accep) print(get) then It is showing json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I have tried many times but it is still not working. -
Append List of String and Q Expression into Q Expression in Django
I am trying to convert a list of strings ( parenthesis, AND, OR ) and Q Expression into Q Expression. I have tried many things but still couldn't find a solution. The input list looks like ['(', <Q: (NOT (AND: name = XYZ))>, ')', 'AND', '(', '(', <Q: (AND: dob = 2020-04-04)>, ')', 'OR', '(', <Q: (AND: no_of_degree = 3)>, ')', ')'] And Desire output is ( ~Q( name = 'XYZ' )) & ( (Q(dob = 2020-04-04)) | (Q(no_of_degree = 3)) ) Any Idea how to do this? -
HTML Docs Not Updating from CSS
I am using a CSS file to update my HTML in a Django app, but despite the fact that my "style.css" sheet is linked to the HTML file, there are no updates occuring. "style.css" is in the same folder as my HTML document ("index.html"), but nothing is changing. I've pasted my code below: <head> <link type="text/css" rel="stylesheet" href="style.css" media="screen"/> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> I know that the CSS and HTML files are linked, because when I hover over the "style.css"href, I can press CTRL + click, and "styles.css" opens in a new window. I've been through four or five tutorials several times each, I have copied everything which they did, but mine is still not working. I've closed and restarted the app, I've re-started the local server, and I'm extremely confused how I can follow a tutorial exactly and still not get this to work. I tried moving "style.css" to its own folder ("styles"), and then changed href to href="styles/style.css" but it is still not working. Nothing I have done works, and no tutorial has been even remotely helpful. Any help or insight is really appreciated, as even on here, finding people with … -
How to reduce space between elements on a row in css bootsrap?
Can someone help me to reduce the extra space between the fields (Site ID and Switch) on my django form below? I am using bootstrap, css and html. I am new to CSS/Bootstrap therefore any guidance will be appreciated. Thanks! Here is code: {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <br> <br> <div class="row form-row spacer rootrow" style="width: 700px; padding: 0; margin: left;" id = "id_parent"> <div class="col"> <!-- <label>{{form.name.label}}</label> --> </div> <div class="col" style="width: 25px;"> <div class="form-group" style="width: 1300px; height: 20px;"> <!--this style= width value changes the width of the form row--> <div class="input-group"> {% for field in form %} <div class="col-auto"> <label for="{{field.id_for_label}}" >{{ field.label }}{% if field.field.required %}*{% endif %}</label> </div> <div class="col-auto"> <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'site' %} {% render_field field class="dropdownlistener" required=true %} {% endifequal %} </div> </div> </div> <div class="col-auto"> <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'switch' %} {% render_field field class="dropdownforswitch" required=true %} {% endifequal %} </div> </div> </div>``` -
How do I change the Django form.errors display text?
I want to remove the circled bit from being displayed. How would I be able to do this? {% if form.errors %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> <p class="m-0">{{ form.errors }}</p> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> </button> </div> {% endif %} This always displays property where the error is found error message error message ... I want to remove the property where the error is found. How would I do this? -
Django forms, django.core.exceptions.FieldError: Unknown field(s) (password1, password2) specified for User
After several hours of crooked searching, I still did not find a solution, so I am asking for your help. I decided to add a password confirmation to the registration, and in the forms.py - fields I added password1 password2 manage.py - File "C:\Users\User\Desktop\Work\StudyDjango\projects_practicles_\coolsite1\todo_list\views.py", line 3, in <module> from .forms import RegisterForm, TaskForm, LoginForm File "C:\Users\User\Desktop\Work\StudyDjango\projects_practicles_\coolsite1\todo_list\forms.py", line 28, in <module> class RegisterForm(ModelForm): File "C:\pthn\lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (password1, password2) specified for User forms.py - class RegisterForm(ModelForm): captchen = CaptchaField() email = forms.EmailField(required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class':'form-control'}) self.fields['email'].widget.attrs.update({'class':'form-control'}) self.fields['password'].widget.attrs.update({'type':'password','class':'form-control', }) # self.fields['password1'].widget.attrs.update({'class':'form-control'}) # self.fields['password2'].widget.attrs.update({'class':'form-control'}) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') and views.py - def user_registration(request): form = RegisterForm if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user_session = form.save() login(request, user_session) return redirect('all_task') else: return redirect('user_registration') else: return render(request, 'todo_list/register.html', {'form':form}) -
Html is not extending correctly only base.html
When trying to extend from base.html my home.html is not showing when at the url that shows home.html only the base.html is showing. I can't seem to figure out what the problem without extending my home.html shows up perfectly but when extending from base.html it seems like it doesn't want to work Base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href={% static 'css\base.css'%} </head> <body> <body> <nav class="navbar"> <ul class="navbar-nav"> <li class="nav-item">Home</li> <li class="nav-item">About</li> <!-- Dropdown will go here --> </nav> {% block body_block %} {% endblock %} </body> </body> </html> Home.html {% extends 'base.html' %} {% load static %} <div class="contianer"> <div class="heading">NEW RENTALS</div> {% for List in listings %} <div class="items"> <img src="{% static List.itempicture %}" alt="" /> <div class="Info"> <h1>{{List.title}}</h1> <p>{{List.about}}</p> <a class="button" href="{{ List.get_absolute_url }}">Contact</a> </div> </div> {% endfor %} </div> <link rel="stylesheet" href={% static 'css\home.css'%} -
Does durable Django atomic transaction imply we don't need savepoints
A Django atomic transaction has the durable and savepoint arguments. See docs. durable=True ensures the atomic block is the outermost atomic block. Per the docs: It is sometimes useful to ensure an atomic block is always the outermost atomic block, ensuring that any database changes are committed when the block is exited without errors. This is known as durability and can be achieved by setting durable=True A PostgreSQL SAVEPOINT establishes a new savepoint within the current transaction. Sounds like this is only needed if the atomic block is nested. I have the following questions: If durable=True then savepoint should ALWAYS be False, right? Because there's no point in using a savepoint if the atomic block is the outermost atomic block. If durable=True, should Django set savepoint=False for us? Reading through the source code, it doesn't appear to do it for us but I feel like it should. -
how to add like button to each blog post in the same page with django
i am building a blog platform, i tried to add like button to each post in the same page with Ajax so that whenever the like button is press it will automatically work without refreshing but it shows this error NoReverseMatch at / Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P<pk>[0-9]+)\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P<pk>[0-9]+)\\Z'] Exception Location: C:\Users\HP\anaconda3\lib\site-packages\django\urls\resolvers.py, line 803, in _reverse_with_prefix Raised during: blog.views.HomeView Python Executable: C:\Users\HP\anaconda3\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\HP\\Dacurate-1', 'C:\\Users\\HP\\anaconda3\\python39.zip', 'C:\\Users\\HP\\anaconda3\\DLLs', 'C:\\Users\\HP\\anaconda3\\lib', 'C:\\Users\\HP\\anaconda3', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\locket-0.2.1-py3.9.egg', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Sun, 11 Sep 2022 23:17:55 +0000 here is my view file views.py def CategoryView(request,cats): category_post=Post.objects.filter(category=cats.replace('-',' ')) return render(request,'category.html',{'cats':cats.title().replace('-',' '),'category_post':category_post}) def CategoryListView(request): cat_menu_list=Category.objects.all() return render(request,'category_list.html',{'cat_menu_list':cat_menu_list}) class UserRegisterView(CreateView): form_class=SignUpForm template_name='register.html' success_url=reverse_lazy('home') def LikeView(request, pk): post=get_object_or_404(Post, id=int(request.POST.get('post_id'))) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user.id) result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result,}) def FollowerView(request, pk): post=get_object_or_404(Post, id=request.POST.get('follow_id')) followed=False if post.followers.filter(id=request.user.id).exists(): post.followers.remove(request.user.id) followed=False else: post.followers.add(request.user.id) followed=True #return redirect (reverse('home', post.pk) + '#{{post.pk}}') #return HttpResponseRedirect(reverse('article-detail', args=[post.pk])+ '#{{post.pk}}') return redirect('home') class HomeView(ListView): model=Post template_name='home.html' ordering=['-id'] def get_context_data(self, *args, **kwargs): cat_menu=Category.objects.all() context=super(HomeView, … -
Docker + Django if_debug template tag is not working
I am running a docker-compose with nginx routing requests to my Django server, with this config: upstream django { server backend:8000; } server { listen 80; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } To use the {% if debug %} template tag I know I need both the correct internal IP and the DEBUG setting turned on. I get the correct internal IPs by running the following code snippet in my Django settings.py: import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip for ip in ips] + ['127.0.0.1'] When I docker exec -it backend sh, and import the DEBUG and INTERNAL_IPS settings, I get that the values are ['172.19.0.4', '127.0.0.1'] and True, respectively. Then, when I run docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) to check the containers' IP address, I see that the backend container that runs Django has an IP of 172.19.0.4, same as the internal IP. Despite this all, in the Django template, I get a Django debug mode error (further proving that debug is turned on) that says that an error got triggered on line 61!!! 57 {% if debug %} 58 <!-- This … -
path() got an unexpected keyword argument 'name'
I am new to Django and trying to set up my first app (home page) and I am currently following a tutorial. When i added in a new path into my urlspatterns list, and link it to the correct function, I get TypeError: path() got an unexpected keyword argument 'name' Below is my code: App Directory urls.py from argparse import Namespace from importlib.resources import path from unicodedata import name from django.urls import re_path from . import views urlspatterns = [ path('', views.index, name='index') # this is the main site path (home page) ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. # This is form the home page def index(request): return HttpResponse('<h1>Hey, Welcome</h1>') project directory urls.py """cheatChecker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from … -
How can my users delete a file that they uploaded using latest Django version?
I'm not getting an error message---but when the Delete button is pressed in my template, nothing happens. Does anyone see what's missing in my code below? settings.py MEDIA_URL = '/home/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'home/') models.py class Roll(models.Model): csv = models.FileField(default="", upload_to='home/') def delete(self, *args, **kwargs): self.csv.delete() super().delete(*args, **kwargs) views.py class DeleteRollView(LoginRequiredMixin, DeleteView): model = Roll form_class = RollForm template_name = 'users/delete_roll.html' @staticmethod def delete_roll(self, request, pk): if request.method == 'POST': roll = Roll.objects.get(pk=pk) roll.delete() return redirect('users:list_roll') delete_roll.html <input type="submit" value="Delete"/> -
Can't seem to make a simple Hello World app
sorry in advance if my format is off this is my first time posting to here. I'm having a really hard time getting started with Django I've followed the tutorial on the https://djangoforbeginners.com/hello-world/ and when I finished I still get the standard landing page is there something that I'm not getting ? #from project.urls from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path("admin/", admin.site.urls), path("", include("pages.urls")) # new ] # from app.urls from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] #from apps.views from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1>Hello, World!</h1>") -
Html file template for Django
I understand if this quetion isn't phrased correctly, but i trying because i cant find the answer. Hello, i have a quetion(sorry if its a simple quetion, i`m beginner in django). I want to create a template html file so that it copy each time. I understand that a block exists and can be modified through it, but I want to create a template that can be inserted in the right place in the HTML code, and edit the template as needed. Exampl what it looks like now : <!doctype html> <html lang="en"> <head> <title>TITLE</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS v5.2.0-beta1 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> </head> <body> <!--NAWBAR--> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <b class="navbar-brand" href="#">Tezla</b> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog:all_blogs' %}">Blog</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> … -
Django Is the server running on host "localhost" (127.0.0.1) and accepting web-1 | TCP/IP connections on port 5432?
I am trying to dockerize my Django project. I have the following config files: Dockerfile: FROM python:3.9-bullseye WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY csgo . RUN apt-get update -y \ && apt-get upgrade -y pip \ && pip install --upgrade pip \ && pip install -r requirements.txt CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] My docker-compose.yml looks like: version: '3' services: web: build: context: . dockerfile: Dockerfile env_file: - csgo.env volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 restart: always ports: - 5432:5432 env_file: - csgo.env environment: - POSTGRES_PASSWORD=postgres - DB_NAME=postgres - DB_USER=postgres - DB_PASSWORD=postgres - DB_HOST=localhost volumes: - ./db/psql-init/db.sql:/docker-entrypoint-initdb.d/db.sql - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: When I try to docker-compose up I get this error: django.db.utils.OperationalError: could not connect to server: Connection refused csgo-web-1 | Is the server running on host "localhost" (127.0.0.1) and accepting csgo-web-1 | TCP/IP connections on port 5432? csgo-web-1 | could not connect to server: Cannot assign requested address csgo-web-1 | Is the server running on host "localhost" (::1) and accepting csgo-web-1 | TCP/IP connections on port 5432? What could be the problem? Can you explain what it means by Is the server running on host "localhost" and why it wouldn't accept connection on port 5432? … -
How to convert string into list?
Well, I am using python. And I have case here. from my api. The following key and value is coming. games : ["['football','cricket']"] Now i want to get that football and cricket from coming games value and store in python list. expected output: print(games) ==> ["football","circket"] print(type(games)) ==> <class list> -
'WSGIRequest' object has no attribute 'htmx'
Hi just looking for some help at solving this error in Django whilst trying to call a view that to accept a htmx request. The final result is to display a popup Modal of images from a Gallery when a thumbnail is clicked. HTMX installed via script in head. View if request.htmx: slug = request.GET.get('slug') context = {'pictures': Media.objects.filter(slug=slug)} return render(request, 'main/gallery-detail.html', context=context) context = {'objects_list': Albums.objects.all()} return render(request, 'main/gallery.html', context=context) Relevant html with the button to open gallery of images. <a class="btn btn-primary" hx-post="{{ request.path }}?slug={{ img.slug }}" hx-target="#modal"> {{ img.slug }}</a> {% endfor %} <div id="modal">{% include "main/gallery-detail.html" %}</div>