Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx can not proxy pass to Django docker container
I'm running my Django app in docker-compose and I'm exposing port 8000. I have Nginx installed in the VM without docker and I want it to forward requets to my Django app, I tried to use host network in my docker-compose and create an external network but nothing worked and I'm always getting 502 Bad gateway this my nginx.conf: events { worker_connections 4096; ## Default: 1024 } http{ include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf server { listen 80; location /static/ { autoindex on; alias /var/lib/docker/volumes/app1_django-static; } location /media/ { autoindex on; alias /var/lib/docker/volumes/app1_django-media; } location / { proxy_pass http://localhost:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } #For favicon location /favicon.ico { alias /code/assets/favicon.ico; } # Error pages error_page 404 /404.html; location = /404.html { root /code/templates/; } } } and this is my docker-compose file: version: "3.2" services: web: network_mode: host image: nggyapp/newsapp:1.0.2 restart: always ports: - "8000:8000" volumes: - type: volume source: django-static target: /code/static - type: volume source: django-media target: /code/media environment: - "DEBUG_MODE=False" - "DB_HOST=.." - "DB_PORT=5432" - "DB_NAME=db" - "DB_USERNAME=.." - "DB_PASSWORD=.." volumes: django-static: django-media: -
Can Django return empty form fields one by one?
I want my Django view to return empty Form fields one by one. The form is a ModelForm inheriting from a single Model. I haven't tried anything because I don't know how can I make it to return one field instead of all. I might modify fields of ModelForm Meta class. -
Filter on related model annotated field with django & postgresql
A have model A and model B, model B has fields a = ForeignKey(A) and birth_date = DateField(). So my goal is to filter A by age which needs to be calculated from model B birth_date. For example I want to find all A where related B has age more than 20. How can It be done? -
Django REST: one PUT request to populate two models
I have two models with exact same fields in them: person log Essentially, on a PUT request to person, I would like to also make a POST-like behavior to log. How would I do that? -
Django: Update Comment section with new comments on a page with Multiple Posts
I am currently working on a post-comment system where a "Society" has many users, and these users can post their posts and others can comment. The functionality of the Society, users and everything is done. However, I am trying to understand how to create a page where I can display every single post, and their respective comment sections, while creating forms on the same page that allow them to post new comments. Essentially, it is like a post-detail view and its comment section, but for every post on a single page. I would also like to do so with AJAX, to prevent having to reload the whole page. Currently, I am looping over a form to create multiple occurrences of it, and I set auto_id to false in my view so that I do not need to worry about unique id's for the multiple Comment forms. I would really appreciate significant help in understanding how to create a page (like in a Facebook group) where users can post their Posts and their Comments all in the same page rather than having to go to a CreateView. I would post code, but this doesn't seem like too complicated of a model … -
How to process subdomain with another CMS with django?
I got a site on Django 1.9, for example domain name mysite.com. At the moment need to deploy forum on subdomain (forum.mysite.com). And this forum should be with phpBB platform. I try to use django-hosts. hosts.py: from django_hosts import patterns, host host_patterns = patterns('path.to', host(r'forum', 'forum.urls', name='forum'), ) But in fact I doesn't have forum.urls file. And now when I try to get access to the forum.mysite.com - server return me mainpage (markdown without static files). I have misunderstanding what should I do to subdomain work correctly. Can somebody give advice what should I do or where need to focus? -
Django - Update a foreing key relation
I'm having problems with a basic usage on Django (my first time). I'm writing an arcade manager, having Games and Cores(Emulators), that means I have a core field in games. This is the model file : class Core(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=255) bios = models.CharField(max_length=255, default="") def __str__(self): return 'Core {}'.format(self.pk) class Game(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=255) description = models.TextField() logo = models.FileField(blank=True, null=True, upload_to="games/logos/") is_archived = models.BooleanField(default=False) core = models.ForeignKey(Core, on_delete=models.PROTECT, related_name="games", default=1) def __str__(self): return self.name This is the views (maybe not interesting): class CoreViewSet(viewsets.ModelViewSet): serializer_class = CoreSerializer queryset = Core.objects.all() permission_classes = [IsAuthenticated] class GameViewSet(viewsets.ModelViewSet): serializer_class = GameSerializer queryset = Game.objects.filter(is_archived=False) permission_classes = [IsAuthenticated] And this is the serializers: class CoreSerializer(serializers.ModelSerializer): class Meta: model = Core fields = '__all__' class GameSerializer(serializers.ModelSerializer): nb_terminals = serializers.ReadOnlyField() total_donations = serializers.ReadOnlyField() core = CoreSerializer(many=False, read_only=False) class Meta: model = Game fields = '__all__' For the moment I can create, change and remove cores from the database but modifying a game's core (foreing key) is impossible and I dont know why. I will only change if I use core = serializers.PrimaryKeyRelatedField(queryset=Core.objects.all(), many=False) But then the core is only an id and not a serialized object, not what i … -
How to make whole div clickable and put a dynamic url in Django template?
I am trying to display a post (like a tweet in twitter) and when I display it I want the whole div to be clickable. So this works. Website is working the way I wanted with this code; <div onclick='location.href="{% url 'post' post.id %}";' style="cursor: pointer;"> <a href="#"> some other links </a> <a href="#"> some other links </a> </div> But it gives me some warnings in the terminal (VScode), each of the error is showing the same thing (div onclick line ) but strangely giving different errors. And I don't use javascript for this part of the code. I tried different syntax like changing " " to ''. but it doesn't solve the problem. Also in the code, it shows the line with red color as below, if it helps to figure what the problem is. Any advice would be appreciated. Thanks in advance. -
overriding update() method in ModelViewSet vs. overiding update() method in serializer
I am looking at code examples and I see both an update() method for serializers and for ViewSets. What is the difference between the two ? When should I override the update() method in the ViewSet and when should I override it in the Serializer ? -
MY class based detail view is not returning the template properly
In my article_details.html page I have written {{post.title}} but my the page is not showing the specific title. My app name is post and the model name is BlogPost. this is my views.py: from django.shortcuts import render from .models import * from .forms import * from django.views.generic import ListView,CreateView from django.views.generic.detail import DetailView def home(request): return render(request,'post/home.html') class HomeView(ListView): model = BlogPost template_name = "post/home2.html" class ArticleDetailView(DetailView): model = BlogPost template_name = "post/article_details.html" class AddPostView(CreateView): model = BlogPost template_name = "post/add_post.html" fields = '__all__' this is my urls.py from post import views from django.urls import path from .views import HomeView,ArticleDetailView,AddPostView app_name = 'post' urlpatterns = [ path('',views.home,name="home"), path('home2/',HomeView.as_view(),name = "home2"), path('article/<int:pk>',ArticleDetailView.as_view(),name = "article-details"), path('add_post/',AddPostView.as_view(),name="add_post"), ] this is my list page: post/home2.html <ul> {%for post in object_list %} <li><a href="{%url 'post:article-details' post.pk %}">{{post.title}}</a>-{{post.author}}<br/> {{post.body}}</li> {%endfor%} </ul> and this is my detail page:article_details.html: <h1>{{post.title}}</h1> <small>by:{{post.author}}</small><br/> <hr> <br/> <p>{{post.body}}</p> enter code here -
I cannot not redirect to login page and cannot save the users after verifying OTP
i have created a django project in which when a user creates an account it will aend an OTP to the users email and if the OTP is verified it should save the user redirects to the login page. it is sending the mail but when the user verifies the OTP its not saving the user and not redirecting users to the login page. views.py from django.shortcuts import render, redirect from django.core.mail import send_mail from django.contrib.auth.forms import UserCreationForm from random import randint from django.http import HttpResponse from .user_forms import * from sm.views import index from django.views import View from django.contrib.auth.decorators import login_required def signin(request): global OTP OTP = '' form = UserForm() if request.method == 'POST': OTP = randint(1111, 999999) OTP = OTP form = UserForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') send_mail( 'Quarantine Community', f"""Thanks for using 'Quarantine community'.We are still developing our server. OTP for your new account is {OTP}. If you have any feedback,you can give us any time.""", 'QuarantineCommunityWeb@gmail.com', [email], fail_silently=False ) return redirect('otp') elif request.method == 'GET': otp = request.GET.get('otp') if otp == OTP: form.save() send_mail( 'Quarantine Community', """Thanks for using 'Quarantine community'.We are still devoloping our server. If you have any feedback,you can gine us.""", … -
How to set Boolean = True unique per model with Fk
How can I save Place model with only one unique True? so if I user have 10 program and only 1 can be is active=True? so if I update some to True , that Program which has True became False this User. I need def save? My models: class Program(models.Model): user = models.ForeignKey('User', models.CASCADE, related_name="program") title = models.CharField(max_length=255) is_active = models.BooleanField(default=False) -
Ruby on rails to django migrate with same user credentials
I have ruby on rails applications, which is using Devise gem for authentication on top of same DB i wanted to use Django with same user name and password. Just vice-versa of this -
tinymce not showing in django form
How can I make it so this HTMLField text = HTMLField('body',max_length=4000) will also appear in the form because right now it shows it only in the admin page and not in the website. -
REST API: Complete beginner at coding tries to code a REST API on Python [closed]
Utter beginner in the realm of coding here. I've been asked by a potential employer to give a go at building a REST API. I won't reveal the task itself as it would defeat the purpose of me actually learning from this project and doing it my own way. This can be in whatever language, framework and library I like. I have chosen to do it in Python with the Django Framework as it seems to work best for beginners from research. I'll probably also do it on Nano, to improve my ability with Terminal. I'm more so looking for pointers: Where to start? What to research? A decent basis to get me going in the right direction. I've never built an API before and am just looking for some guidance to get me going. I'm currently using a 2014 Macbook Pro. Thank you for taking the time to read this post. Any help is massively appreciated -
Accessing an element in django (for)
I have a Django template with the following code which creates multiple buttons and tries to hide/show description text on a click (on the same button in each card): {% for comida in comidas %} {% if comida.slug_food == page.slug %} <div class="food2"> <div id="food-title">{{comida.titulo}}</div> <div id="food-price">{{comida.precio|floatformat:"-1"}}€</div> <button class="button" onclick="showDescription()">ver+ <div id="food-description" > {{comida.descripcion|safe}} </div> </button> <div id="add-cart">AÑADIR AL PEDIDO</div> {% if comida.imagen != null %} <img src="{{comida.imagen.url}}"></img> {% endif %} </div> {% endif %} {% endfor %} where comidas is a list of strings, and later in the script block I have function showDescription(){ var showText = document.getElementById("food-description"); if (showText.style.display === "block"){ showText.style.display = "none"; } else { showText.style.display = "block"; } } The function runs, but as you may expect, it runs only on the first element of my for loop. My question is ¿anyone can help me? i want work all my buttons and not only the first element. -
How to access specific object from the database in Django to display it in the webpage?
I am trying to display the title and description from an SQLite database in Django? I have all the data from my database and from views file I have returned it as context. Here's the model.py file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() Here's my views.py file: def home(request): posts = Post.objects.all() search_query = request.GET.get('q') if search_query: posts = posts.filter( Q(title__icontains = search_query) | Q(content__icontains = search_query) ) context={ 'posts': posts } return render(request,'blog/home.html', context) And here the HTML code:- {% for post in posts %} <div class="slide-description"> <label class="slide-0"> <h1 class="text-slide">{{Here i want to print the title 1}}</h1> <h5>{{Here I want to print the content 1}}</h5> <a href="/" class="readmorebutton">Read More</a> </label> <label class="slide-1"> <h1 class="text-slide">{{Here i want to print the title 2}}</h1> <h5>{{Here I want to print the content 2}}</h5> <a href="/" class="readmorebutton">Read More</a> </label> <label class="slide-2"> <h1 class="text-slide">{{Here i want to print the title 3}}</h1> <h5>{{Here I want to print the content 3}}</h5> <a href="/" class="readmorebutton">Read More</a> </label> <label class="slide-3"> <h1 class="text-slide">{{Here i want to print the title 4}}</h1> <h5>{{Here I want to print the … -
How to solve an error on django admin interface
enter image description hereHi i am using Django admin to work on some task. i have created a model and added project name. so whenever i am creating a project say 'project5' and adding details and if again i am creating another project with same name and same details it is being created. What i want is i do not want the project name created to be with same details. it should give error. Please let me know how to fix this. Here below i have created a model with a class name and some fields. i have sorted it with unique=True Also i have created different users who can further create project name. if user1 has created project1, I also want user2 to create project1. i mean same user cannot create project with same name but different users can create project with same name.Please let me know how to fix this enter image description here. -
pipenv problem getting MarkupSafe to automatically install as a dependency
I'm using @arocks DjangoPatternsBook and code. I have the book and would like to follow along with the code, but I think I found a bug because it's failing for me right at the starting line on two different computers using different python environments, so I don't think it's my environment that's causing the problem. From the book section Starting the project: First, clone the example project from GitHub: $ git clone https://github.com/DjangoPatternsBook/superbook2.git Next, install pipenv system-wide [this is what I did, using brew on MacOS and using dnf on Fedora 32] or locally, but outside a virtualenv as recommended in pipenv installation documents. Alternatively, follow these commands [I did not do this]: $ pip install -U pip $ pip install pipenv Now go to the project directory and install the dependencies: $ cd superbook2 $ pipenv install --dev This is where it fails for me with the message: [pipenv.exceptions.InstallError]: ['Looking in indexes: https://pypi.python.org/simple', 'Collecting markupsafe==1.0', ' Using cached MarkupSafe-1.0.tar.gz (14 kB)'] [pipenv.exceptions.InstallError]: ['ERROR: Command errored out with exit status 1:', ' command: /home/alpha/.local/share/virtualenvs/superbook2-HNnQDu9M/bin/python3 -c \'import sys, setuptools, tokenize; sys.argv[0] = \'"\'"\'/tmp/pip-install-5kl59pd3/markupsafe/setup.py\'"\'"\'; __file__=\'"\'"\'/tmp/pip-install-5kl59pd3/markupsafe/setup.py\'"\'"\';f=getattr(tokenize, \'"\'"\'open\'"\'"\', open)(__file__);code=f.read().replace(\'"\'"\'\\r\\n\'"\'"\', \'"\'"\'\\n\'"\'"\');f.close();exec(compile(code, __file__, \'"\'"\'exec\'"\'"\'))\' egg_info --egg-base /tmp/pip-pip-egg-info-bk6ldht4', ' cwd: /tmp/pip-install-5kl59pd3/markupsafe/', ' Complete output (5 lines):', ' … -
how to write django rest framework update / partial_update for list of objects: drop 1 object and add another on
I have a list of objects in my json object using django-rest-framework. for my ModelViewSet how would I override an update() or partial_update() method to drop the first object: { "a": "a", "a": "a", "a": "a", "a": "a", } and add a new object to the very bottom: { "d": "d", "d": "d", "d": "d", "d": "d", } [{ "a": "a", "a": "a", "a": "a", "a": "a", }, { "b": "b", "b": "b", "b": "b", "b": "b", }, { "c": "c", "c": "c", "c": "c", "c": "c", }] the resulting object would look like this: [ { "b": "b", "b": "b", "b": "b", "b": "b", }, { "c": "c", "c": "c", "c": "c", "c": "c", }, { "d": "d", "d": "d", "d": "d", "d": "d", }] -
upstream prematurely closed connection while reading response header from upstream based on 502 Bad Gateway error
in Django app, I tried to get some images from static and media files it runs correctly locally but in production, it takes about 30 and then error 502 Bad Gateway I tried so much for days and I don't know what is the problem my nginx config : server { listen 80; server_name 23.96.58.116 www.cancerdetection.info; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/shaker/mysite/deepmodel; } location /media/ { root /home/shaker/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } and the error file : 2020/08/21 10:45:41 [error] 26835#26835: *4 upstream prematurely closed connection while reading response header from upstream, client: 197.60.99.165, server: 23.96.58.116, request: "GET /deepmodel/Examine/1 HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/deepmodel/Examine/1", host: "23.96.58.116", referrer: "http://23.96.58.116/basicapp/patient_list/" 2020/08/21 10:56:01 [error] 27231#27231: *2 upstream prematurely closed connection while reading response header from upstream, client: 197.60.99.165, server: 23.96.58.116, request: "GET /deepmodel/Examine/1 HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/deepmodel/Examine/1", -
Django No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Hi I am trying to create a blog using the Django webframework. I get the error, No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. The urls.py is given below, from django.urls import path from .views import ( BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, ) urlpatterns = [ path('post/<int:pk>/edit', BlogUpdateView.as_view(), name='post_edit'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('', BlogListView.as_view(), name='home'), ] The models.py is given below, from django.db import models from django.urls import reverse # Create your models here. MAX_LENGTH = 500 class Post(models.Model): title = models.CharField(max_length=MAX_LENGTH) author = models.ForeignKey('auth.User', on_delete=models.CASCADE,) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) Where am I going wrong? -
pytest: Test database constraints
I wrote the following test for my Django application. The IntegrationDaily model has a constraint of max. 100 capacity. Therefore the entry will fail "on purpose". However, pytest.raises(Exception) seems to be the wrong approach to validate that. I also tried to import TransactionManagementError instead but that didn't solve it either. import pytest from tests.factories.spaces import IntegrationDailyFactory from myapp.spaces.models import IntegrationDaily def describe_element_capacity_validation(): def with_is_failling(): with pytest.raises(Exception) as exc: daily_element = IntegrationDailyFactory(capacity=300) assert IntegrationDaily.objects.count() == 0 -
i am trying to save data in database and it is throwing error like- Attribute error: 'tuple' object has no attribute 'get'
Internal Server Error: /newPage/ Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\deprecation.py", line 96, in call response = self.process_response(request, response) File "C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' [21/Aug/2020 12:19:10] "POST /newPage/ HTTP/1.1" 500 58604 [21/Aug/2020 12:19:13] "GET / HTTP/1.1" 200 10523 My view.py code is as below. @csrf_exempt def newPage(request): # pdb.set_trace() data = json.loads(request.body.decode('utf-8')) try: f_name = data['f_name'] print(f_name) l_name = data['l_name'] print(l_name) email_id = data['email_id'] print(email_id) mobile_no = data['mobile_no'] print(mobile_no) address_line = data['address_line'] print(address_line) city = data['city'] print(city) region = data['region'] print(region) pin_code = data['pin_code'] print(pin_code) course_name = data['course_name'] print(course_name) location = data['location'] print(location) # date = data['date'] # print(date ) save_user_details = models.user_details.objects.create_user_details(f_name,l_name,email_id,mobile_no,address_line,city,region,pin_code,course_name,location) save_user_details.save() return 'saved',save_user_details except Exception as e: return e,None -
IntegrityError at /entry/21/add_comment NOT NULL constraint failed: auctions_comment.text
I am trying to create an e commerce website where there is a problem occurring in the comment section where we need to add Comments I created a model which calls Listing to get the listing id so that each listing have their own comment section models.py class Comment(models.Model): listing_id=models.ForeignKey(Listing,on_delete=models.CASCADE) uname=models.CharField(max_length=64,default="None") text=models.TextField() datetime=models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.uname} {self.cmt} {self.datetime}" views.py def add_comment(request,id): if request.user.username: list=Listing.objects.get(id=id) newItem = Comment() newItem.listing_id = list newItem.uname = request.user newItem.text=request.POST.get('comment') newItem.save() return redirect('add_comment',id=id) else: return redirect('index') urls.py path("entry/<int:id>/add_comment",views.add_comment,name="add_comment")