Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django URL Linking Problems
I am working on an online school project, I just linked Lesson Playlist, with class's subjects so when you click on a class you get it's subjects page, and in the subject page there are playlists of lessons, examle: Math's lessons playlist (playlist use IDs not slugs), My problem is at linking the playlist URL in the HTML page so my question is How to link lessons to materials(subjects) in the HTML page? My codes: HTML PAGE: <html> {% load static %} <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="/static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> <button class="bt1"><a href="/signup">انشاء حساب</a></button> </ul> </nav> {% for playlist in playlist.all %} <div class="div1"> <img src="/static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">{{playlist.title}}</h1> </div> {%endfor%} <li><a href="#"> HelloWorld </a></li> {% for lesson in material.lesson_set.all %} <li><a href="{% url 'lessons' classes.id playlist.id lesson.id %}">World1</a></li> {% endfor %} </div> </body> </html> MODELS.py: from django.db import models from users.models import * # Create your models here. class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title class Material(models.Model): name= models.CharField(max_length=200, default=1) title= … -
Django template fetching value from option tag
I want to fetch selected option value, and then display content dependent of chosen option template <div class="match-wrapper"> <select name="team"> {%for team in teams%} <option class='option-select' value="{{team.0}}">{{team.0}}</option> {%endfor%} </select> {%if option.value == 'AGO'%} <span>AGO</span> {%else%} <span>Not AGO</span> {%endif%} </div> views.py def profile(request): teams = ['AGO', 'K1CK', 'DV1', 'PIRATESPORTS', 'IHG', 'DC', 'PRIDE', 'AVEZ'] context = { 'teams':teams, 'ago_players':ago_players, } return render(request, 'profilecontent/profile.html', context) -
Django page not reloading when files change
I use a Django library called "django-livesync" https://github.com/fabiogibson/django-livesync I'm working from home now (you know, coronavirus) and everything works fine in my django project but when I change some file the page is not reloading. In my settings.py: INSTALLED_APPS = [ ... 'django.contrib.messages', 'livesync', 'django.contrib.staticfiles', ... ] MIDDLEWARE = [ ..., 'livesync.core.middleware.DjangoLiveSyncMiddleware' ] DEBUG = True Something must be working because when I check the chrome console I see this object: Do you guys have any clue of why this isn't reloading the page when there's a change? -
Django Admin "model list view" and "model form view" WITHOUT any model. Just from raw python dict
This is kinda difficult for me as Django is not my first choice framework and I need to maintain a project. Project is fairly complex with several apps, separate postgres schema for each app etc ... We use Django Admin for most of our daily life emergencies and there is one thing I need to do and don't have any idea how to proceed. I have a json object in REDIS. I want to list it and browse it just like any other model in Django Admin. Just listing, without any sorting, querying, adding etc, nothing but list, and details view. class DictViewAdmin(admin.ModelAdmin): actions = [] list_display = ( 'key', 'value' ) def get_queryset(self, request): # TODO: get queryset like object filled with data drom a dict() pass def has_add_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False I even tried to create a custom Manager and a simple dummy Model but without any success. For those who will ask abut "Why not a database ?". This Redis is core functionality of tens of other servers, This is just not possible to rewrite all of them in given time. -
Windows-Django- can't import own modules-says module not found
Both views.py and xyz.py are in app folder.But when I import xyz.py django says "ModuleNotFound" -
Updating Balance In Django
I m new to Django.. I have two models I want to update my account based on the transaction debit or credit. If Debit Account.Balance = Account.Balance - Transaction.Amount If Credit Account.Balance = Account.Balance + Transaction.Amount class Account(models.Model): customer = models.ForeignKey(Customer, on_delete = models.CASCADE, related_name='acccustomer') Account_Number = models.CharField(max_length=20, null=False) Account_Type = models.CharField(max_length=20, null=False) Balance = models.IntegerField(default=1000) def __str__(self): return self.Account_Number + "-" + self.Account_Type + "-" + str(self.Balance) class Transaction(models.Model): account = models.ForeignKey(Account, on_delete= models.CASCADE, related_name='account') Transaction_Type = models.CharField(max_length=10, null=False) Amount = models.PositiveIntegerField() Initiated_Date = models.DateField(null=False) Posted_Date = models.DateField(null=False) Status = models.CharField(max_length=10, null=False) def __str__(self): return self.Transaction_Type + "-" + str(self.Transaction_Amount) Any help would be appreciated. -
Django reading a file from s3
django 3 docker s3 heroku How do you READ a file from s3. I have a django app where I am uploading a word doc to s3, but then later I need to have the document in memory to make changes to it. I can upload a doc and can create a download link, but can't seem to read it. One method suggested downloading the file locally and then reading it, but when you are using django and docker in production, that doesn't really makes sense. Do I have 2 file storage systems (s3 and nginx or whitenoise?). This is a django deployed to heroku app. I am so confused right now. Will post an example later -
How to switch local and deployment environment in django setting
I know I can set Config Var in Heroku that I can save my secret key and other credential(etc. db information). So I have this setting, # settings.py from os.path import abspath, dirname, join import psycopg2 import dj_database_url BASE_DIR = dirname(dirname(abspath(__file__))) SECRET_KEY = ['ENV_SECRET_KEY'] DEBUG = True DATABASES['default'] = df_database_url.config(conn_max_age=600, ssl_require=True) I want to switch base on the environment. For example, # local_setting.py django_secrety_key = 'foo' django_db = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'example_db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } # settings.py from os.path import abspath, dirname, join import psycopg2 import dj_database_url from local_setting import * BASE_DIR = dirname(dirname(abspath(__file__))) SECRET_KEY = if local django_secret_key, else ['ENV_SECRET_KEY'] DEBUG = if local True else False DATABASES['default'] = if local django_db else df_database_url.config(conn_max_age=600, ssl_require=True) How can I set local so that I can check it uses local_setting?? -
how to insert primary key value in another table in django
i have created model code is blow here from django.db import models Create your models here. class EmployeeDetail(models.Model): emp_fname = models.CharField(max_length=50, default="") emp_lname = models.CharField(max_length=50, default="") emp_uname = models.CharField(max_length=100, default="") emp_email = models.EmailField(max_length=254, default="") emp_password = models.CharField(max_length=100, default="") emp_dob = models.DateField(max_length=50, default="") emp_doj = models.DateField(max_length=50, default="") emp_designation = models.CharField(max_length=100, default="") emp_salary = models.IntegerField() emp_leaves = models.IntegerField() emp_contact = models.CharField(max_length=12, default="") emp_photo = models.ImageField(upload_to="employee/images", default="") def __str__(self): return self.emp_fname class Post(models.Model): emp_id = models.ForeignKey('EmployeeDetail', on_delete=models.CASCADE) title = models.CharField(max_length=255) content = models.TextField() author = models.CharField(max_length=15) timeStamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' by ' + self.author and i have view.py file is blow here from django.shortcuts import render, redirect from .models import EmployeeDetail, Post from django.http import HttpResponse from django.contrib import messages # Create your views here. def login(request): # messages.success(request, 'Welcome to Login Form') if request.method == "POST": uname = request.POST['uname'] password = request.POST['password'] employee = EmployeeDetail.objects.filter(emp_uname=uname, emp_password=password) # print(employee) if employee: uname = request.POST['uname'] request.session['emp_uname'] = uname return redirect('employee/home') # return redirect('employee/home') else: messages.error(request, 'Wrong Details') return render(request, 'login.html', {}) return render(request, 'login.html', {}) def create_post(request): if request.session.has_key('emp_uname'): name = request.session['emp_uname'] query = EmployeeDetail.objects.filter(emp_uname=name) if request.method == "POST": title = request.POST.get('title') eid = request.POST.get('eid') euname = request.POST.get('ename') content … -
Django ORM: Equivalent of SQL `NOT IN`? `exclude` and `Q` objects do not work
The Problem I'm trying to use the Django ORM to do the equivalent of a SQL NOT IN clause, providing a list of IDs in a subselect to bring back a set of records from the logging table. I can't figure out if this is possible. The Model class JobLog(models.Model): job_number = models.BigIntegerField(blank=True, null=True) name = models.TextField(blank=True, null=True) username = models.TextField(blank=True, null=True) time = models.DateTimeField(blank=True, null=True) What I've Tried My first attempt was to use exclude, but this does NOT to negate the entire Subquery, rather than the desired NOT IN: query = ( JobLog.objects.values( "username", "job_number", "name", "time", ) .filter(time__gte=start, time__lte=end, event="delivered") .exclude( job_number__in=models.Subquery( JobLog.objects.values_list("job_number", flat=True).filter( time__gte=start, time__lte=end, event="finished", ) ) ) ) Unfortunately, this yields this SQL: SELECT "view_job_log"."username", "view_job_log"."group", "view_job_log"."job_number", "view_job_log"."name", "view_job_log"."time" FROM "view_job_log" WHERE ( "view_job_log"."event" = 'delivered' AND "view_job_log"."time" >= '2020-03-12T11:22:28.300590+00:00'::timestamptz AND "view_job_log"."time" <= '2020-03-13T11:22:28.300600+00:00'::timestamptz AND NOT ( "view_job_log"."job_number" IN ( SELECT U0."job_number" FROM "view_job_log" U0 WHERE ( U0."event" = 'finished' AND U0."time" >= '2020-03-12T11:22:28.300590+00:00'::timestamptz AND U0."time" <= '2020-03-13T11:22:28.300600+00:00'::timestamptz ) ) AND "view_job_log"."job_number" IS NOT NULL ) ) What I need is for the third AND clause to be AND "view_job_log"."job_number" NOT IN instead of the AND NOT (. I've also tried doing the sub-select … -
How can I combine DetailView with a custom form?
I have a detail view in which I display post's title, date, content underneath that I have a button to add a comment which takes to me an other page which has a form to create a comment, what I want to do is have that form on detail view page instead of redirecting to another page. My Post: My comment form: My PostDetailView and CreateCommentView class PostDetailView(DetailView): template_name = 'blog/detail_post.html' context_object_name = 'post' model = Post def CommentCreateForm(request,pk): if request.method == 'POST': post = get_object_or_404(Post,pk=pk) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail',pk=post.pk) else: form = CommentForm() return render(request,'blog/create_comment.html',{'form':form}) My urls.py: urlpatterns= [ path('new/',views.PostCreateForm.as_view(),name='post_create'), path('',views.PostList.as_view(),name='post_list'), path ('post/<int:pk>/',views.PostDetailView.as_view(),name='post_detail'), path('comment/new/<int:pk>',views.CommentCreateForm,name='add_comment'), ] my detail_post.html: {% extends 'blog/base.html' %} {% block content %} <div class="post-title"> <a href="{% url 'post_detail' pk=post.pk %}"><h1>{{ post.title }}</h1></a> </div> <div class="post-date"> <p><b>Published on: </b>{{ post.create_date|date:"d, F Y" }}</p> </div> <div class="post-content"> <p>{{ post.content|safe|linebreaksbr }}</p> </div> <div class="add-comment"> <a class="btn btn-primary" href="{% url 'add_comment' pk=post.pk %}">Add comment</a> </div> <div class="post-comments"> {% for comment in post.comments.all %} {% if comment.approved %} <p><b>Posted By:</b>{{ comment.author }}</p> <p>{{ comment.content|safe|linebreaksbr }}</p> {% endif %} {% endfor %} </div> {% endblock %} my create_comment.html: {% extends 'blog/base.html' %} … -
Displaying multiple images to same Post
MODELS: class Activitati(models.Model): data_publicarii = models.DateField(default = "AAAA-LL-ZZ") titlu = models.TextField(max_length = 50, blank = False) text = models.TextField(blank = False) def get_absolute_url(self): return reverse('activitati', kwargs={'pk':self.pk}) class Images(models.Model): post = models.ForeignKey(Activitati, on_delete = models.CASCADE, default = None) image = models.ImageField(upload_to ='images/', blank = True, null = True) def __str__ (self): return self.post.titlu + 'Image' VIEWS: def activitati_list(request): activitati = Activitati.objects.all() post = Images.objects.all() ordering = ['-data_publicarii'] return render(request, 'activitati_list.html', {'activitati':activitati,'post':post}) TEMPLATE: {%for p in post.images_set.all%} <div class="zoom"> <img src="{{p.image.url}}" class=photo> </div> {%endfor%} Why doesnt it display anything ? i dont know what i am missing ? In the template, if i write 'post.all' instead post.images_set.all it displays all images for each post, but this is not what i want. Where can I find more documentation about that '_set' ? -
Django ManyToManyField Validate Unique Set
models.py class MyProduct(models.Model): name = models.CharField() codes = models.ManayToManyField(Code) Hi, I'm trying to validate the ManyToManyField for the unique set. it shoud validate that similar set should not repeat again on another record, In the django docs , it mentioned clearly that ManyToManyField cannot be unique=True or unique_together. So how can I handle this validation, I am not able to find the solution for this. I request please guide me for some suggestion for this, it will be helpfull for me. Thanks in advance. -
How to fetch the ID of the request user in Django?
I am creating a profile page, and need to fetch the id of the requesting user, so I can then loop it's information. I am using this view: def profile(request, id): cl = Clients.objects.get(id=request.user.id) ... But when I try access the page I get the following error: profile() missing 1 required positional argument: 'id'. Isn't the id=request.user.id passing the ID? -
Why Does not work Class_Name(Products.objects) in Django?
Class_Name(Products.objects)does not working Here says no attribute objects in Products Any one Can See in Here : https://github.com/kazisohag/django.git Please solve my problem as soon as possible And help me. -
ImportError: cannot import name 'views' from 'textutils' in Django
urls.py file from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), ] views.py file from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello") Error Occur ImportError: cannot import name 'views' from 'textutils' I Am New Here So Don't Know The Proper Method Of Posting Questions. I Hope You Understand, Please Help Me To Get Out Of This Problem ! -
Need _id from mongodb in django [closed]
I am using MongoDB in Django. i need to return _id (the object field). how can i do that? I am not using any kind of template just JSON response. data1=Filter_data.objects.get(user_id=raw_data["user_id"],post_id=raw_data["post_id"]) -
Need to set current.username in author comment section
I've created Comment section. The main goal is that only registered users can post comments and only from their usernames. For now, I have a problem from who (username) the post is posting. On screenshot, you can see, that I can choose to post comment from user:JOHUA, but I'm currently logged in from user:JOHN I need to set permission for user to post comment only from his username (maybe I should remove username variable in models.py, forms.py and admin.py and to set it by default like user:username, or maybe you know how to remove other usernames from Username column, so register user can only choose his username. I have been puzzling over this problem for a long time, so definitely need community help! HERE IS SOME CODE: models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') username = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.username) forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['username', 'email', 'body'] admin.py from django.contrib import admin from .models import Post, Category, Comment class CategoryAdmin(admin.ModelAdmin): pass @admin.register(Comment) … -
Auth0 save 'sub' instead of 'username'
I finished implementing auth0 to my django and react app. But ever since I signup with a new user, the 'sub' is saved as the username instead of the real 'name'. Is there a way to fix this? django admin user page -
Directed graphs: sons that a mother had with a given father
I am using queries of the form "all descendants of node X with an ascendant called Y". It turns out that Django returns different results depending on which of the parents of the target node one specifies as Y. Illustration: Consider the simple model class Person(models.Model): name = models.CharField(max_length=200, unique=True, blank=False) descendants = models.ManyToManyField("self", symmetrical=False, related_name='ascendants') def __str__(self): return self.name Create a graph with 3 nodes: mother = Person(name="Mother") mother.save() son = mother.descendants.create(name="Son") father = son.ascendants.create(name="Father") Thus, "Father" and "Mother" are the ascendants of "Son". This is the puzzling part. I want to retrieve the sons that "Mother" had with "Father". However, the code q1 = mother.descendants.filter(ascendants__name="Father") print("mother descendants with an ascendant called Father = ", q1) produces an empty QuerySet, which seems incorrect. In contrast q2 = mother.descendants.filter(ascendants__name="Mother") print("mother descendants with an ascendant called Mother = ", q2) correctly produces <QuerySet [<Person: Son>]>. Is this a bug of Django? Thanks! -
What can be the best way for automatic deployment of my application on AWS?
I have an app created in Django and React, but there are few problems that I am facing mainly :- As I will have a large database(postgres) exclusily for a single user, I am creating different AWS instance(t2.micro) for every user. (we are a startup so economical to use t2.micro) Whenever there is a new user then I have to go and manually install postgres, setup nginx and other important things and this is just for Django in EC2, I am not even talking about React in S3. Solutions I am looking for :- If there is a way to automatically create an AWS EC2 instance and deploy backend also same thing for AWS S3 and deploy frontend, whenever there is a new user. There are a lot of things that I will be running when the backend starts namely Huey, Installing Postgres and Creating User for it, installing Redis, making migrations and other trivial stuff. Is there a way to automate every single thing? Things to consider :- We are a startup and can not depend on paid services really much. Please do not ask me to use a single server for every user as we are using 3rd … -
How to find out which data is tenants data in postgres uisng django
so i have 10 tenants, i am using Django with django-tenants with postgresql, every tenants have users, which user data is which tenant data -
Django View Error: Local variable referenced before assignment -> Flaw in if-statement?
In my Django view I have the following if-loop: for i in queryset: if i['mnemonic'] == '#0602###95EUR00': cash_ps_totbank_eur = i['value'] cash_ps_totbank_eur_sub1 = i['value'] if i['mnemonic'] == '#0602###90EUR00': cash_ps_totbank_eur += i['value'] # Working cash_ps_totbank_eur_sub2 = i['value'] if i['mnemonic'] == '#0602###95USD00': cash_ps_totbank_usd = i['value'] cash_ps_totbank_usd_sub1 = i['value'] if i['mnemonic'] == '#0602###2095900': cash_ps_totbank_usd += i['value'] # NOT working & throwing error cash_ps_totbank_usd_sub2 = i['value'] When loading the template, Django throws me an error saying local variable 'cash_ps_totbank_usd' referenced before assignment. I do the same thing here as eight lines above, namely adding a value to a varible that was initiated in the if-loop before and hence should have already a value assigned to it. With the variables ending on _sub1 and _sub2 i tried to check, if there is maybe an error with the equality-check between the queryset and the string. But this is not the case. The variables with _sub1 and _sub2 work perfectly fine and get the correct values assigned to. Any idea what I am missing here? -
Django make query dynamically for filter
this code works well from django.db.models import Q filtered = Article.objects.filter(Q(authers__id=2) | Q(issues__id=1) | Q(issues__id=3) ) However now I have list like this below, and want to make filter dynamically. ids = [1,2,3] for id in ids: eachQ = Q(authers__id=isId) #then...... how can I make query ??? -
Djanng filter for many to many by multiple
Auther has the manytomany entity Article I can use filter for manytomany like this a = Author.objects.get(id=1) Article.objects.filter(authors=a) However I want to filter auther a and auther b like Article.objects.filter(authors=a and authors=b) How can I make it??