Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango QuerySet filter query using a model attribute
Let's say I have a model Example class Example start_time = models.DateTimeField(db_index=True) duration = models.IntegerField(default=0) And a QuerySet class class ExampleQuerySet def live_objects(): self.active().filter(start_time__gte=get_minutes_before(get_utc_now(),5), start_time__lte=get_minutes_after(get_utc_now(), self.duration)) The objective of the live_objects() method is to return those objects which have their current time > start time and current time < start time + duration of the object But this above query is failing with the error that self object doesn't have duration attribute How do I go about writing a query where I can filter out objects that are currently live ? -
How to put up new content some part of a div is pressed
The title is probably confusing but there isnt a better way to ask the question. Im making a job searching website using django. Im not really experienced in the front end. I want a list of job offers to be showing and when one of them is clicked I want a enlarged version with additional info(Apply button, detailed description) to appear of the specific job offer clicked. Sort of like how it linkedin does it. This is the code I am using for listing out all of the jobs. I know I will probably need a dynamic url but from there I dont know how to implement it on the front end. Comps is just a list of all of the objects in a Model for Companies. {% for comp in comps %} <div class="CompList"> <span>{{comp.jtitle}}</span> <h2>{{comp.name}}</h2> <h3>{{comp.country}}, {{comp.city}}</h3> </div> {% endfor %} -
Ldap authentification with django
I'm trying to set up ldap connexion with django but it won't work. So, I tried this to test if it's working and it's returns <(97, [], 1, [])>. import ldap server = 'ldap://Server' user_dn = 'Test' password = 'Formation123' con = ldap.initialize(server) con.simple_bind_s(user_dn, password) But when I try to connect on the admin page of django it doesn't work. Here's my config and my directory.enter image description here Thank you for your help. enter image description here -
Django: Why am I getting a 400 bad request error?
I am developing a web application on django + react And I needed to make a request in which I pass a list with ids, but I have a '"POST /api/questions/ HTTP/1.1" 400 39' views.py questions = [] class TestQuestionList(APIView): def get(self, request): global questions romms = TestQuestionBlok.objects.filter(id__in=questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) def post(self, request, format=None): global questions serializer1 = TestQuestionSerializers(data=request.data) if serializer1.is_valid(): print(serializer1.data['answers']) return Response(serializer1.data, status=status.HTTP_200_OK) return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class TestQuestionSerializers(serializers.ModelSerializer): class Meta: model = TestQuestionBlok fields = ('answers', ) Testpage.jsx import React, {useState, useEffect} from 'react'; import axios from "axios"; import { useParams } from "react-router-dom"; import "../styles/Testpage.css" function Testpage() { axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" useEffect(() => { axios({ method: 'POST', url: 'http://127.0.0.1:8000/api/questions/', data: { question: [1, 3] } }) }, []) return ( <div> a </div> ); } export default Testpage; How can I fix this ? -
How do i get my like button to show up on my blog posts?
I got some problems getting my like button to show am not sure what to enter into the post_detail.html to get the like button to show up on the blog posts. i tried {% include and putting the entire code from main.html in to the post_detail.html etc But all i get is errors what is the correct way to get the code from main.html to show up on the blog post post_detail.html ? would really appreciate some help cause i been stuck on this for very long and cant figure it out how to get the like button to show up on blog posts. newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return … -
Django filebrowser functions
I am writing a code for a customer who needs a filemanager with version control for every file and hidden files based on logged in user. I was wondering if the filebrowser can be used and extended or would it be much faster if I make my own code with my own views and templates? Thanks -
Django Parsing filtered queryset into json without loop
I have lastSpecifiedHours variable that filters last 48 hours actions. I need to return that as JSON as plate, time, longitude, latitude. Built as below but I used loop for that. I wonder is there anyway making same return without loop? def lastpoint(request): if request.method == "POST": #post vehicle plate as vplate plate = request.POST.get("vplate") #hours can be got with post if necessary hours = 48 vehicle = Vehicle.objects.get(plate = plate) lastSpecifiedHours = datetime.now(tz=timezone.utc) - timedelta(hours=hours) resultJson = [] #Cached result for optimization results= NavigationRecord.objects.filter(vehicle=vehicle, datetime__gte=lastSpecifiedHours) for result in results: resultJson.append({"Plate": vehicle.plate, "Date Time": result.datetime, "Longitude": result.longitude, "Latitude": result.latitude}) return JsonResponse(resultJson, safe=False) -
How to get value from foreign key and next foreign key?
We need to get cost from Reward, but we must use TwitchUser it`s my models.py class TwitchUser(models.Model): username = models.CharField(max_length=250, verbose_name='username', null=True) refresh_token = models.CharField(max_length=300, verbose_name='refresh_token', null=True) id = models.CharField(max_length=150 ,primary_key=True) login = models.CharField(max_length=250, null=True) avatar = models.CharField(max_length=400, verbose_name='avatar') params = models.ForeignKey('Parametrs', on_delete=models.CASCADE) class Parametrs(models.Model): skip = models.ForeignKey('Reward', on_delete=CASCADE) chat_bot = models.BooleanField(default=False) class Reward(models.Model): id = models.CharField(primary_key=True, max_length=50) title = models.CharField(null=True, max_length=50) cost = models.IntegerField(default=0) background_color = models.CharField(max_length=30, verbose_name='color', default='FFD600') cooldown = models.IntegerField(default=30) type = models.CharField(max_length=100, ) -
Cannot connect to redis://localhost:6379// while using docker-compose
This may be a simple question but I've just started to learn docker and I am making my first project with it. I have a django project using celery and Redis. I've made Dockerfile and docker-compose.yml: Dockerfile FROM python:3.8 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools ARG PROJECT=djangoproject ARG PROJECT_DIR=/var/www/${PROJECT} RUN mkdir -p $PROJECT_DIR WORKDIR $PROJECT_DIR COPY requirements.txt . RUN pip install -r requirements.txt EXPOSE 8000 STOPSIGNAL SIGINT CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] Docker-compose.yml: version: "3" services: redis: image: redis:latest container_name: rd01 ports: - '6379:6379' restart: always expose: - '6379' django: container_name: django_server build: context: . dockerfile: Dockerfile image: docker_tutorial_django volumes: - ./parser_folder:/var/www/djangoproject ports: - "8000:8000" links: - redis depends_on: - celery celery: build: . command: celery -A Parsing worker -B --loglevel=DEBUG volumes: - ./parser_folder:/var/www/djangoproject links: - redis When I execute docker-compose up I get an error consumer: Cannot connect to redis://localhost:6379//: Error 99 connecting to localhost:6379. Cannot assign requested address.. I tried to change ports and write the command for Redis in docker-compose.yml but it won't working. Help me to figure it out … -
Watch star rating in page and rate in the other
I am new to Django and I'm using Star-Rating. I would like to know if there is a possibility a user can see the ratings on one page without the opting to rate and on another page, the same user can rate -
Invalid HTTP_HOST header: Django deployment
I have a very strange problem. I published my site with NGİNX, then I added a subdomain. Invalid HTTP_HOST header: 'm.bakuklinik.shop'. You may need to add 'm.bakuklinik.shop' to ALLOWED_HOSTS. I get this error. I refreshed the setinngs.py file on the server and did it as follows. ALLOWED_HOSTS = ['159.223.235.76', 'www.bakuklinik.shop', 'bakuklinik.shop', 'm.bakuklinik.shop',] But again I got the same error. Then I deleted the www.bakuklinik.shop url to see if it would work. It shouldn't work, but it does. even when i delete settings.py file it works. I guess I need to make changes elsewhere. I would be glad if you help. -
Bad Request Python Django on User Registration and Email Confirmation
So I implemented by User Registration Class, and it was working fine and then tried sending out Email Confirmation through Send Grid which also worked fine. Then I added some conditions. Basically, the workflow is: User signs up by sending relevant info. The 'is_active' field is set to False initially Then a PatientSerializer object is created of the request, which is saved in the database IF valid. Created a token through libraries to verify email address Created a TokenSerializer object by passing the ID in the request and the token created in (3) and saved it if it's valid Under the same if block, a message was made through the SendGrid API and was sent to the user Then there's just except and else statements to catch errors My models.py file: from django.db import models from django.contrib.auth.models import User class Token(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') token = models.CharField(max_length=256, blank=True, null=True) My serializer.py file: from pyexpat import model from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import Token class TokenSerializer(serializers.ModelSerializer): class Meta: model = Token fields = ('user', 'token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] … -
ndarray is not C-contiguous what is the error?
ndarray is not C-contiguous Request Method: POST Request URL: http://127.0.0.1:8000/rainfall Django Version: 4.0.4 Exception Type: ValueError Exception Value: ndarray is not C-contiguous -
Django is annotating wrong Count (possibly duplicates?)
I have a model ChatMessage that has a field sender which is a ForeignKey to User model. I'm trying to annotate a number of all the ChatMessage objects that haven't been read (eg. have seen_at__isnull=True). For a given user, there is only one sent message with seen_at__isnull=True but Django returns 11. User.objects.select_related(...).annotate( sent_unread_messages=Count('sent_chat_messages', filter=Q(sent_chat_messages__seen_at__isnull=True))) do you know where is the problem? -
How to associate parent table instance with newly child table instance through foreign keys in Django?
I'm new to Django and reactJS. I'm creating models with foreign key relationships in Django models. But when I send data from React to my Django rest API, it creates the parent table object on the basis of a foreign key value instead of associating it with the existing value. How can I associate with the newly created child instance instead of creating the parent object? I'm searching for the last 2 days but nothing worked for me. What I'm doing wrong? It gives me this response header in my reactJS application: {"store_title":[" store data with this store title already exists."]} My models are: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) class StoreData(models.Model): STATUS=( ('A','Active'), ('P','Pending approval'), ('B','Blocked'), ) store_title=models.CharField(max_length=50,primary_key=True, null=False) tagline=models.CharField(max_length=100,null=False, default='') store_type=models.CharField(max_length=10,null=False, default='') description=models.CharField(max_length=500,null=False, default='') user=models.ForeignKey(User,on_delete=models.CASCADE,null=True) logo_img=models.ImageField(upload_to=user_directory_path, default='') brand_img=models.ImageField(upload_to=user_directory_path, default='') link=models.CharField(max_length=100, default='') date_created=models.DateField(default=timezone.now) status=models.CharField(max_length=20,choices=STATUS,default='A') def __str__(self): return str(self.store_title) class Categories(models.Model): title=models.CharField(max_length=50, default='none') thumbnail_img=models.ImageField(upload_to=user_directory_path, default="") store_title=models.ForeignKey(StoreData, on_delete=models.CASCADE, default='') def __str__(self): return str(self.title) My serializers are: class StoreSerializer(serializers.ModelSerializer): class Meta: model = StoreData fields = '__all__' class CategorySerializer(serializers.ModelSerializer): def __init__(self, data): self.store_title=serializers.SlugRelatedField(queryset=StoreData.objects.filter(pk=data['store_title'])) class Meta: model = Categories fields = '__all__' And my rest API is: @api_view(['POST']) def addCategory(request): serializer=CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() … -
How to become a profitable full stack developer?
I am a front-end developer. I already know React and Next.js technologues and have done many projects. I want to become a full-stack developer, so what is the right roadmap to achieve the goal. I also would like to know what technologies are in demand on the back-end side including programming languages, frameworks, databases, etc. I would be glad to see your suggestions. -
why company choose web framework to build e-commerce?
I am wondering why some companies use web framework like spring, laravel, django..etc to build e-commerce website while there are good solutions like wordpress, wix..etc thank you -
How much can i earn from selling APIs? [closed]
I'm a collage student learning python and i watched Anía Kubów's video on selling APIs, so i thought it would be a nice way to earn some money on the side without it taking up to much of my study time. I was planing to use flask or django for making APIs, and i was wondering does anyone have any experience with this and can you earn some decent money doing this (by decent i mean not too much, just something to help me get by). And if not does anyone have an idea about some other way for me to earn money from programming without it taking up too much of my time. Thank you. -
Adding a signup option on the far right on HTML
I would like to add a signup button on the far right of my webpage. When ever I try to edit something before the closing header tab it randomly appears in a spot I do not want.. how do I go on and add it correctly? Assume I want to add something as simple as <p align="right"></p><li><a href="/">Sign Up</a></li></p> Eventually what i'll get is enter image description here {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Movies</title> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> <!-- Icon --> <link rel="icon" href="{% static 'img/icon.jpg' %}" type="image/icon type"> <!-- Sign up button --> <!-- Link Swiper's CSS --> <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/script.js' %}"></script> <!-- Demo styles --> <style> </style> </head> <body> <div class="wrapper"> <header class="header"> <figure class="logo"><a href="/"><img src="{% static 'img/logo.png' %}" alt="Logo"></figure></a> <nav class="menu"> <ul> <li><a href="/">Home</a></li> <li><a>Genres</a> <ul> <li><a href="{% url 'movies:movie_category' 'action' %}">Action</a></li> <li><a href="{% url 'movies:movie_category' 'comedy' %}">Comedy</a></li> <li><a href="{% url 'movies:movie_category' 'drama' %}">Drama</a></li> <li><a href="{% url 'movies:movie_category' 'romance' %}">Romance</a></li> </ul> </li> <li><a>Year</a> <ul> <li><a href="{% url 'movies:movie_year' year=2022 %}">2022</a></li> <li><a href="{% url 'movies:movie_year' year=2021 %}">2021</a></li> <li><a href="{% url 'movies:movie_year' … -
What is the correct way to add dynos to Django/Heroku project?
This is continuation of my previous question: What is the propper way to debug gunicorn? Currently I am having error code=H14 desc="No web processes running" wihch suggests that there are no dynos. I tried to fix this by doing heroku ps:scale web=1, but instead got error: Scaling dynos... ! ▸ Couldn't find that process type (web).. This answer suggests "simple disable/enable through heroku dashboard". However I can't see any way I can do that. Some other possible solutions suggested that the problem is with the Procfile, its location or its content. Here is my Procfile web: gunicorn kauppalista.wsgi --log-file - Here is my folder structure: folder my_project │ requirements.txt │ runtime.txt │ folder .git │ folder my_project-env │ └───folder my_project │ │ folder my_project (main Django app) │ │ folder django app 1 │ │ folder django app 2 │ │ manage.py │ │ Procfile -
several successive answers to a single question on one page (POST request, django)
I'm very news to django and need help for structuring a project. I would like to make a page (one page) which shows the image of a person; the user must recognize the person and write his/her name on a field. The answer gets processed and if it's wrong, the player can try again. I can do it with two pages (choose image, show image, take answer; then show verdict, return). But I can't seem to fathom the structure of the index view for doing it all on the same page. So the page should behave differently if an answer has been given already, or not; if no, it should take a random image, and show it; if yes, it should compare the POST request result to a variable. How do I write this? Here is the views.py : from django.http import HttpResponse from django.template import loader, Context, Template from .models import Mystere, Image, Indice from .forms import Prop from django.shortcuts import get_object_or_404, render from scripts import load_data def index(request): template = loader.get_template('home.html') load_data.run() global p, i p = Mystere.objects.create(id=0) i = Image.objects.all().first() i = i.image p = Mystere.objects.all().last() p = p.individu rep=Prop() context = {'question': i, 'form': rep, } … -
Django viewflow custom permissions
Probably something simple. I am trying to follow the cookbook example on the following link https://github.com/viewflow/cookbook/tree/master/guardian. With the exception of a couple of unrelated differences between the example and my own code (I am not using frontend and am using custom views). Everything else works as expected. I do not understand what I am getting wrong on the permissions side of things. I am getting a "403 forbidden" error whenever a user other than the one that started the process tries to interact with the flow. This happens irrespective of the assigned user's assigned permissions - is this the expected behavior or should I open a ticket on Github? While I am trying to understand if viewflow can support what I am trying to accomplish - I would like to leave apply the permissions checking on my own views (rather than the built in checks). I saw that there was a pull request https://github.com/viewflow/viewflow/issues/252 - however, I do not understand how to implement it. Any help would be appreciated! Been stuck on this for quite a while The permissions are defined in a custom user class accounts/models.py class Department(models.Model): name = models.CharField(unique=True, max_length=250) description = models.TextField(blank=True) objects = managers.DepartmentManager() class … -
django search and pagination using ajax
I want to implement search functionality and pagination in my django project by using ajax call.Without ajax call it works fine.But I want to implement without page reload.So in the console am getting searched string(search is done by using username) like results:username. I want to display that matched records from the mysql database in the form of a table.There are total 6 fields. Here, after searching the username the result should be displayed under the search box as table entries.How to modify my script and views for getting results in the form of table entries?Here it do not need to load all records.The table records should be fetch after search. user_management.html <form method="get" action="/home" id="form_search"> <div class="input-group"> <input name="results" id="results" type="text" placeholder="search" class="form-control form-control-lg" /> <div class="input-group-append"> <button class="btn btn-dark btn-lg" id="q" >Search</button> </div> </div> </form> </div> </div> </div> <div class="card-body" > {% if word %} {% for words in word %} <table class="table table-bordered" style="width:85%;margin-right:auto;margin-left:auto;" id="example" > <thead class="table-success"> {% endfor %} <tr> <th scope="col">Id</th> <th scope="col">Username</th> <th scope="col">Name</th> <th scope="col">Admin</th> <th scope="col">User</th> <th scope="col">Status</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> {% for words in word %} <tbody> <tr> <th>{{words.id}}</th> <th>{{words.username}}</th> <th>{{words.first_name}}</th> <th>{{words.is_superuser}}</th> <th>{{words.is_staff}}</th> <th>{{words.is_active}}</th> <th><a href="/update_user/{{words.id}}" class="btn btn-success" … -
Django: Change the parent, when the child get dleted(unidirectional OneToOne)
First of all, I am sorry for my poor English. I want to change Photo 'labeled' field False when I delete LabeledPhoto object. #models.py class Photo(models.Model): image = models.ImageField(upload_to='shoes_data/%Y/%m/%d', name='image') created = models.DateTimeField(auto_now_add=True) labeled = models.BooleanField(default=False) class LabeledPhoto(models.Model): labeled_image = models.OneToOneField(Photo, on_delete=models.PROTECT, related_name='labeled_image') topcategory = models.CharField(max_length=64) subcategory = models.CharField(max_length=64) labeler = models.CharField(max_length=32) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) I tried like this but, It didn't work # views.py class LabeledPhotoDelete(DeleteView): model = LabeledPhoto template_name = 'label/labeled_photo_delete.html' success_url = reverse_lazy('photo:labeled_list') def delete(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() labeled = LabeledPhoto.objects.get(id=self.object.pk) labeled.labeled_image.labeled = False labeled.save() self.object.delete() return reverse(success_url) Thank you in advance for your help. -
What is problem with ALLOWED_HOSTS = ['*'] in django in production.?
If source code is hidden what is point of not using * wild card object in django. Why Not to use this in production.?