Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to change the admin panel for User app
When Users of Admin Panel get Permissions for Editing, there is no way of selecting which countries they have access to. My database has multiple countries, and a user with specific permission can do that in any country. I should be able to give "Groups" and "Users" access to only one or some countries [Currently there is no Country Selection Criteria] , So for each User or User-Type created in the Admin panel, there should be an additional selection for the Country Data of Database he can access So how should I create the models in models.py and admin.py? I am quite new to Django. My code for models.py class MyUser(models.Model): COUNTRY_CHOICES = ( ('SA', 'Saudi Arabia'), ('IN', 'India'), ('UAE', 'United Arab Emirates'), ('UK', 'United Kingdom'), ('KW', 'Kuwait') ) user = models.OneToOneField(User, on_delete=models.CASCADE) country_selection = MultiSelectField(choices=COUNTRY_CHOICES) For admin.py from django.contrib import admin from django.contrib.auth.models import User from django.db import models from .models import Guide, MyUser from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class GuideAdmin(admin.ModelAdmin): date_hierarchy = 'date' raw_id_fields = ("country",) list_display = ['en_title', 'country', 'date'] search_fields = ['country__ISOCode', 'en_title'] # readonly_fields = ('slug', 'preload_image', 'feature_image', 'images') ordering = ['-date'] class UserInline(admin.StackedInline): model = MyUser can_delete = False verbose_name_plural = 'user' class … -
Problems with django form fiels for-loop
I've just started to learn Django recently. When implementing a Registration page with a website template(with css, js and some other files), I came across a problem with respect to form fields in for-loop. My form consists of 4 fileds: username, email, password1, password2. According to Django mannual, it can be achieved in html templates using: {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} and I noticed it has the same result as using {{ form }}. I want to fit it into my templates, which is: {% for field in form %} <div class="form-group"> <label for="{{ field.label }}" class="col-lg-2 control-label">{{ field.label }}</label> <div class="col-lg-10"> <input class="form-control" id="{{ field.label }}" placeholder="{{ field.label }}" type="text"> </div> </div> {% endfor %} By doing so, I can get the styles I need, but since the type in <input> is hard-coded as text, when inputing password it shows the characters instead of hidden as expected. -
how to translate fields of registration page in django
hey everybody i'm trying to translate a web app with i18n localization i have made .po file and compile messages but there is some view like registration log in and some other words automatically generated by django which is not correct how we should handle this part for example how i can access to this field in auto generated form registration. django registration field translation please help i have no iadea how i can change this tags. -
Pass variable to custom template loader
I want to make something like this work : context = { 'looking_for_this': '12345', } t = Template("Stuff {% include 'dynamic_template' %} stuff") c = Context(context) result = t.render(c) So I want 'dynamic_template' to be loaded by custom loader, I can make it, but I can't seem to find a way to pass a variable so i can use it in loader ("looking_for_this") . class CustomLoader(BaseLoader): is_usable = True def __init__(self, *args, **kwargs): self.looking_for_this = "????" super(CustomLoader, self).__init__(*args, **kwargs) def get_template_sources(self, template_name, template_dirs=None): yield Origin( name=template_name, template_name=template_name, loader=self, ) def get_contents(self, origin): return f"{self.looking_for_this}" I need it because i need to load 'dynamic_template_12345' template. It doesn't have to be context, I could pass it via reference, just can't find the place. Any hints ? Thanks -
How to set sass_path to node_modules when deploying on heroku
I am deploying my django-react app on heroku. I had this error before, that I solved by running this command SET SASS_PATH=.\node_modules. It worked fine locally. But when i deploy my project on heroku i get this error again. my index.scss files have nothing but scss for material web react components. index.scss @import "@material/react-card/index.scss"; @import "@material/react-button/index.scss"; @import "@material/react-icon-button/index.scss"; @import "@material/react-typography/index.scss"; @import "@material/react-drawer/index.scss"; @import '@material/react-list/index.scss'; @import '@material/react-menu-surface/index.scss'; @import '@material/react-menu/index.scss'; @import "@material/react-text-field/index.scss"; @import "@material/react-chips/index.scss"; @import "@material/react-layout-grid/index.scss"; @import "@material/react-list/index.scss"; @import '@material/react-line-ripple/index.scss'; @import '@material/react-floating-label/index.scss'; package.json "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "./node_modules/.bin/webpack --config webpack.config.js", "watch": "npm run start -- --watch --mode development", "postinstall": "npm run start" }, "engines": { "npm": "6.12.0", "node": "12.13.0" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.8.7", "@babel/preset-env": "^7.8.7", "@babel/preset-react": "^7.8.3", "babel-cli": "^6.26.0", "babel-loader": "^8.0.6", "babel-plugin-transform-class-properties": "^6.24.1", "babel-preset-es2015": "^6.24.1", "babel-register": "^6.26.0", "clean-webpack-plugin": "^3.0.0", "css-loader": "^3.4.2", "extract-text-webpack-plugin": "^4.0.0-beta.0", "node-sass": "^4.13.1", "style-loader": "^1.1.3", "sass-loader": "^8.0.2", "webpack": "^4.41.6", "webpack-bundle-tracker": "^0.4.3", "webpack-cli": "^3.3.11" }, "dependencies": { "@material-ui/core": "^4.9.3", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "^4.0.0-alpha.44", "@material/react-button": "^0.15.0", "@material/react-card": "^0.15.0", "@material/react-checkbox": "^0.15.0", "@material/react-chips": "^0.15.0", "@material/react-drawer": "^0.15.0", "@material/react-floating-label": "^0.15.0", "@material/react-icon-button": "^0.15.0", "@material/react-layout-grid": "^0.15.0", "@material/react-line-ripple": "^0.15.0", "@material/react-list": "^0.15.0", "@material/react-material-icon": "^0.15.0", "@material/react-menu": "^0.15.0", "@material/react-text-field": "^0.15.0", "@material/react-typography": … -
Hello, I'm new to Django Rest_Framework. I am trying to implement a function-based view but facing problem with the put method
I want to know how we can access a particular object at id and then update it. I'm getting the 405 method not allowed error. Is it possible to do that or I have approach the problem in a different way? views.py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from home.models import example from home.serializers import exampleSerializer @api_view(['GET', ]) def exampleview(request): try: ex=example.objects.all() except example.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method=="GET": serializer=exampleSerializer(ex, many=True) return Response(serializer.data) @api_view(['PUT', ]) def exampleputview(request): try: ex1=example.objects.get(id=id) except example.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method=="PUT": serializer=exampleSerializer(ex1, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(status=status.HTTP_404_NOT_FOUND) urls.py from django.contrib import admin from django.conf.urls import url from home import views urlpatterns = [ url('admin/', admin.site.urls), url('home/',views.exampleview), url('home/<int:id>/',views.exampleputview), ] -
django admin site change the display label of field
I hope the title is enough to understand what my issue is, I just want to change the default label Fathers Lastname: into Lastname without changing the table field name in the models this is my models.py class ParentsProfile(models.Model): Fathers_Firstname = models.CharField(max_length=500,null=True,blank=True) Fathers_Middle_Initial = models.CharField("Middle Initial",max_length=500,null=True,blank=True, help_text="Father") Fathers_Lastname = models.CharField(max_length=500,null=True,blank=True) -
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) …