Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist: account/register.html
I am tryinging to create my own customized registration form. I already created register.html file in the templates folder, and I set the templates setting like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTH_USER_MODEL= "account.Account" This is views.py for registration_view: from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from account.forms import RegistrationForm def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: #GET request form = RegistrationForm() context['registration_form'] = form return render(request, 'account/register.html', context) and this is my urls.py: from django.contrib import admin from django.urls import path from personal.views import ( home_screen_view, ) from account.views import ( registration_view, ) urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"),] I am watching this tutorial Can someone please tell me how can I solve this issue? -
add_error(fieldname, ...) in Django Rest Framework (DRF)
I have a model serializer like this: class MySerializer(ModelSerializer): class Meta: model = MyModel fields = ('myfield', 'otherfield') I need to check a cross-field condition, say, x.myfield > x.otherfield. (There are actually several otherfields and several conditions.) I need detailed and easy-to-grasp human-readable error messages. I currently generate them (actually only the first) in MySerializer.validate() via raise ValidationError(message), but then the message comes under the non-field-errors key, which is ugly and difficult for the users. It would be much nicer to attach it to myfield. In Django forms, I would use add_error('myfield', ...), but I could not find a similar thing in rest framework. What is a suitable idiom here? -
Django's Get Queryset as Generic Function
Can It be possible if I create a common get_queryset and use it for all the class. If yes, what can be the drawback of this. -
How to pass custom input field inside a form to Django CreateView and to the Model
I will keep the description as short as possible So frontend an image is compressed Via CompressorJs In HTML: <form class='form' action="" method="post" enctype="multipart/form-data"> {%csrf_token%} {{form.as_p}} <p> <input name='photo_1' id='id_photo_1' value='${base64data}'> </p> <!-- this will be created --> <button>Submit</button> </form> <div class='Uploader'> <input type="file" id="upload" accept="image/*"> </div> <script> document.getElementById('upload').addEventListener('change', (e) => { var file = e.target.file new Compressor(file, { quality: 0.5, maxWidth:910, success(result) { var reader = new FileReader(); reader.readAsDataURL(result); reader.onloadend = function() { var base64data = reader.result; var img1 = `<p> <input name='photo_1' id='id_photo_1' value='${base64data}'> <img src='${base64data}' > </p>`; $(".form").append(img1); } }, error(err) { console.log(err.message); }, }); } }); </script> In Models.py: class Card(models.Model): photo_1 = models.ImageField(upload_to='photos/cards/%Y%m/', blank=True) In Views.py: class AddCardView(CreateView): model=Card form_class = CardForm template_name='card/addcard.html' def form_valid(self, form): form.instance.poster = self.request.user return super(AddCardView, self).form_valid(form) In Form.py before: fields=(photo_1,) In Form.py after: fields=(#I removed it so the createview generated one doesn't show up in the html page) My original plan is to set the createView generated input field to hidden, Then replace the value with JS, But then I learned you can't change the value of file=input due to security reasons, The default Id and name for the CreateView generated file=input is id_photo_1 and photo_1, So I set … -
Django REST: projects vs apps
I am developing a REST API using Django Rest Framework. This API deals with a high number of resources that are divided into "business areas". I should be developing this API so that the resources from the different business areas are independent and can be used individually in contexts other than the project I am working on. My question is: should I be using different DRF projects, or different Django apps for each business area? I.e., Should I organize like this: |- businessarea1_api_project |- core_app |- api_documents |- businessarea2_api_project |- core_app |- api_documents Or like this: |- big_api_project |- businessarea1_api_app |- businessarea2_api_app I am assuming that using different apps helps me in the sense that I can use Django's reusable apps to create a package for each business area, and then I can install them in the projects they are required. Using different projects helps in the sense that i have an individual API running for each business area that can be called whenever needed, together with other APIs or not. Is this it? Are there other factors that I should be considering? Which one is better? Thank you! -
add django native authentication as the second layer of authentication, after user login via LDAP authentication
I have used Django2 to build a web app. I configured LDAP login as the auth method to login to the website. But now the client need another layer to authenticating the user logged in by LDAP. They want to map the user logged in using LDAP to the django user table, and query the user type to guide the different user to different pages. I have already disabled django native auth to give way to ldap auth, how could I add it back as the second layer to check user identify after user logged in by ldap? settings.py: AUTHENTICATION_BACKENDS = ( 'bookdb.backends.LDAPBackend', ('django.contrib.auth.backends.ModelBackend'), ) INSTALLED_APPS = [ 'django.contrib.auth', ] backends.py from django.contrib.auth import get_user_model UserModel = get_user_model() class LDAPBackend: def authenticate(self, request, username=None, password=None, **kwargs): now = datetime.datetime.now() text = str(now.day) + 'ls@bBk3y' def computeMD5hash(my_string): m = hashlib.md5() m.update(my_string.encode('utf-8')) return m.hexdigest() username = username.lower() try: headers = {'Authorization': computeMD5hash(text).upper()} body = {"username": username, "password": password} response = requests.post(url="https://XXX/REST/json/service/loginStaff", json=body, headers=headers) result = response.json() if result['code'] != "OK": return None except Exception as e: print(e) user, created = UserModel.objects.get_or_create(username=username) return user def get_user(self, user_id): try: return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None What I want to achieve is, when user login … -
Django Error ''WSGIRequest' object has no attribute 'Players''
I am trying to create a detailed page for each player from the Players model, but for some reason, I am getting this error. How can I fix this? My models.py: class Players(models.Model): name = models.CharField(max_length=255) position = models.CharField(max_length=255) image_url = models.CharField(max_length=2083) My views.py: def PlayerDetailView(request, player): model = Players player = request.Players context = {'player' : player} return render(request, 'player_detail.html', context) My player_detail.html: {% extends 'base.html' %} {% block content %} <h1>{{ player.name }}</h1> <img class="card-img-top" width="20" height="300" src="{{ player.image_url }}"> {% endblock %} My urls.py: path('players/<str:player>', views.PlayerDetailView, name='player-detail'), -
Django Reverse for '' not found
while working with Django URLs I ran into a problem that i cannot understand. I will bring 2 examples that are implemented in a similar way but only one is working. The dashboard and users-list (dashboard not working) urlpatterns = [ path('', views.home, name='home'), path('dashboard/', views.dashboard, name='dashboard'), path('users-list/', views.users_list, name='users-list'), ] The html of both links <li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{% url 'dashboard' %}" aria-expanded="false"> <i class="mdi mdi-av-timer"></i> <span class="hide-menu">Dashboard</span> </a> </li> <li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{% url 'users-temp-records' %}" <i class="mdi mdi-account-multiple-outline"></i> <span class="hide-menu">Users</span> </a> </li> views @login_required def dashboard(request): user = request.user entranceRecords = None if user.is_staff == True: entranceRecords = TbEntranceRecord.objects.all().order_by("-create_time") else: entranceRecords = TbEntranceRecord.objects.filter(people_name=user.username).order_by("-create_time") page = request.GET.get('page', 1) paginator = Paginator(entranceRecords, 10) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context = { 'title': 'Dashboard', 'records': data, } return render(request, 'app/common/dashboard.html', context) @ login_required def users_temp_records(request): user = request.user entranceRecords = None if user.is_staff == True: entranceRecords = TbUserTemperatureRecord.objects.all().order_by("-create_time_date") page = request.GET.get('page', 1) paginator = Paginator(entranceRecords, 12) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context = { 'title': 'Users Records', 'records': data, } return render(request, 'app/admin/users/users_temp_records.html', context) … -
'QuerySet' object has no attribute 'order_by' While accessing model's field in view
I am building a BlogApp and I am stuck on an Error. I am trying to give user an option to order_by the results ( blogs ) with choices. AND i am trying to access model's field in view it is keep showing me. 'QuerySet' object has no attribute 'order_by' models.py ORDER_CHOICES = [ ('date_added':'date_added'), ('likes':likes), ] class Blog(mdels.Model): user = models.ForeignKey(User,models=on_delete.CASCADE) blog_title = models.CharField(max_length=30) blog_description = models.CharField(max_length=300) order_by = models.CharField(max_length=30,choices=ORDER_CHOICES) likes = models.ManyToManyField(User, related_name='likes', blank=True) views.pp def posts(request): post = Blog.objects.filter(user=request.user) if post.order_by == 'date_added' : order_bys = Blog.objects.filter(user=request.user).order_by('-date_added') elif post.order_by == 'likes': order_bys2 = Blog.objects.filter(user=request.user).order_by('likes') context = {'order_bys':order_bys,'order_bys2':order_bys} return render(request, 'posts.html', context) posts.html {% for ord in order_bys %} {{ ord.blog_title }} {% endfor %} {% for ord2 in order_bys2 %} {{ ord.blog_title %} {% endfor %} When i run this code and check browser it is keep showing me :- > 'QuerySet' object has no attribute 'order_by' I have no idea what am i doing wrong. Any help would be much Appreciated. Thank You in Advance. -
Django model can't be render in html
There are some models that I've created but it wont render in template, there are some that are ok so i just use the same method to create the other model but when i try manage.py runserver some of the model is not render, i already do manage.py makemigrations and manage.py migrate, sorry this is my first time asking question here and thank you This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import FrontPage, DailyQuote, Photo, kate # Create your views here. def front(request): photo = Photo.objects.all() content = {'photo': photo} return render(request, 'front.html', content) def home(request): page = FrontPage.objects.all() args = {'page':page} return render(request, 'Home.html', args) def ytvideos(request): return render(request, 'ytvideos.html') def reading(request): page = FrontPage.objects.all() Fullpage = {'page': page} return render(request, 'Reading.html', Fullpage) def KGK(request): Thekate = kate.objects.all() Therealkate = {'Thekate': Thekate} return render(request, 'KGK.html', Therealkate) This is my HTML {% extends 'front.html' %} {% block head %} {% endblock %} {% block content %} <div class="container-fluid"> {% for i in kate %} <div class="card text-center"> <div class="card-header"> <b>kate</b> </div> <div class="card-body"> <h5 class="card-title">{{ i.katetitle }}</h5> <p class="card-text">{{ i.katecontent }}</p> <a href="#" class="btn btn-primary">Read More</a> </div> </div> {% endfor %} </div> {% … -
How can I change the db_column name of foreign key in Django?
How can I change db_column of Foreign Key in Django? class A(models.Model): it_id = models.CharField('IT ID', max_length=10) class B(models.Model): it_id = models.ForeignKey('A', related_name='item', on_delete=models.PROTECT, db_column='it_id') when I call objects, >>> B.objects.all().values() <QuerySet [{'it_id_id'}:'xxx']> It is 'it_id_id'.... How can I change 'it_id' from 'it_id_id'? -
How can i read the data of headers of a post request sent by python requests?
Looking for the help, I am making a post request to an django application with AUTH-TOKEN in the header and trying to access it on view but not able to. python app import requests import json URL = "http://127.0.0.1:8000/test/api/" request_data ={ 'order':{ 'id':'order.id', 'payment_collection_status': 'transaction_status', 'payment_collection_message': 'transaction_message' } } request_headers = {'AUTH-TOKEN':'webhook_auth_token'} json_data = json.dumps(request_data) response = requests.post(url = URL,headers=request_headers, data = json_data) print(response) django application view from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def request_handle(request): if (request.method=='POST'): print(request.body) print(request.META["AUTH-TOKEN"]) return HttpResponse('<h1>hello</h1>') but not able read the header data it is throwing an error: KeyError: 'AUTH-TOKEN' -
manage.py cant find any urls in myapp.urls file. Says something about circular import
I seem to find the following error despite making a number of changes in my app.urls file and in my project.urls file. I can't seem to put my finger on it, here is the code: app.urls file from django.urls import path from . import views urlpatterns = [ path('', views.home_page, name = 'home_page'), ] project.urls file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Success.urls')), ] views.py file from django.shortcuts import render from django.http import HttpResponse enter code here Create your views here. def home_page(request): hello = 'hello world' return HttpResponse (hello) -
openpyxl.load_workbook takes a long time in Django
I have an excel conversion function in my Django project. I have some processes like a copy of the data from one excel to another excel. While it was working very fast about a week ago, it suddenly started to work slowly in openpyxl.load_workbook part. I do not know why? I am using the remote desktop connection with Azure server. We should use read_only=False because we have to copy operations. Any help would be appreciated. Note: load_workbook parts take about 1 minute. views.py def excel_convert(path, target_path): pythoncom.CoInitialize() save_path = target_path.replace('.xlsx','.xlsm') wb_to_load = openpyxl.load_workbook(target_path, read_only=False, keep_vba=True) ws_to_load = wb_to_load['OCR'] wb = openpyxl.load_workbook(path, read_only=False, keep_vba=True) ws = wb['OCR'] n_row = ws_to_load.max_row n_col = ws_to_load.max_column for row_idx in range(1, n_row + 1): # Iterate through rows for col_idx in range(1, n_col + 1): # Iterate through columns current_cell = ws_to_load.cell(row=row_idx, column=col_idx) value = current_cell.value # Get cell object by row, col ws.cell(row_idx, col_idx).value = value if current_cell.has_style: ws.cell(row_idx, col_idx).font = copy(current_cell.font) ws.cell(row_idx, col_idx).border = copy(current_cell.border) ws.cell(row_idx, col_idx).fill = copy(current_cell.fill) ws.cell(row_idx, col_idx).number_format = copy(current_cell.number_format) ws.cell(row_idx, col_idx).protection = copy(current_cell.protection) ws.cell(row_idx, col_idx).alignment = copy(current_cell.alignment) wb.active = wb['Finansal Tablolar_formul'] wb.save(save_path) wb1 = openpyxl.load_workbook(save_path) wb2 = openpyxl.load_workbook(save_path, keep_vba=True) wb2.save(save_path) excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True ex = excel.Workbooks.Open(save_path) … -
Heroku deployment: Django site does not exist
Morning, I have deployed my site to Heroku and got the errors as per the attached images. I checked migrations, have SITE_ID=1. Would anybody be able to help to solve this issue? Not sure if related while deploying to Heroku I had an issue with loaddata utf-8 decoder and converted JSON file with online tool to comply with utf-8. I manage to loaddata thereafter but got these errors. thank you[ -
How to write data from Django model to Redis DB using HSET in Python standalone script?
I am trying to write data to redis DB from Django Model using HSET command. Below is a standalone script in Django project:- File name: - insertToRedis.py import redis, django def writeOnRedis(): r = redis.Redis( host='XXX.XXX.XX.XXX', port='6379') #imported model from MainApp.models import Employee allEmployees =Employee.objects.all() # Here I want to insert this all Employees object to Redis with HSET command # But don't know how to do this. # CONDITION: e_name is key and the remaining fields are values #why this condition? --> I want to query Redis DB by E_name if __name__ =='__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') django.setup() writeOnRedis() my employee model looks like this:- file name:- models.py from django.db import models class Employee(models.Model) e_id = models.IntegerField() e_name = models.TextField() e_designation = models.TextField() e_salary = models.FloatField() def __str__(self): return self.e_name Question: How can I query the model in such a way that e_name, e_id, e_designation, and e_salary will be the output? And How this Output can be passed to HSET as an input. Version: Django==3.1.7 redis_version:6.0.9 I am a newbie to Django and Redis, any suggestions will help me a lot. Thanks in advance. -
Django does not throw threat exceptions
Could you please help me? Django does not threat the exceptions. I would like when it returns the integrity exception block when this case occur. But nothing, it continue to the else block which raise the integrity exception. I tried with from django.db.utils import IntegrityError and from django.db import IntegrityError datafile = csv.DictReader(datafile, delimiter=',') for row in datafile: row = {k: None if not v else v for k, v in row.items()} try: road_type_id = row['id'] name = row['name'] roadtype = RoadType( road_type_id=road_type_id, name=name, congestion=CONGESTION_TYPES[row['congestion'].lower()], default_speed=row.get('default_speed', None), default_lanes=row.get('default_lanes', None), default_param1=row.get('default_param1', None), default_param2=row.get('default_param2', None), default_param3=row.get('default_param3', None), color=row.get('color', None)) except IntegrityError: e = 'this data already exists in the database' return render(request, template, context={'e': e}) else: roadtype = RoadType( road_type_id=road_type_id, name=name, congestion=CONGESTION_TYPES[row['congestion'].lower()], default_speed=row.get('default_speed', None), default_lanes=row.get('default_lanes', None), default_param1=row.get('default_param1', None), default_param2=row.get('default_param2', None), default_param3=row.get('default_param3', None), color=row.get('color', None)) -
Django/Djagno REST field lookup "range" does not return a range, but rather single value results
I am trying to return a range of objects containing date attributes. Using the field lookup range, it only returns objects with the start range. For example: If start of the range is equal to 2021-05-19 and end of the range is equal to 2021-05-21, only objects with the date 2021-05-19 are being returned. urls.py urlpatterns = [ ... path('weekly/<str:activity_date>/', views.ActivityDateList.as_view(), name='weekly_dates'), ... ] views.py from django.shortcuts import render from rest_framework import generics from .serializers import ActivityListSerializer from .models import Activity from keeper import serializers ... class WeeklyActivityView(generics.ListAPIView): serializer_class = ActivityListSerializer def get_queryset(self): end_of_week = "2021-05-21" # Temporary test date activity_date = self.kwargs['activity_date'] return render(Activity.objects.filter(activity_date__range=(activity_date, end_of_week))) models.py class Activity(models.Model): activity_name = models.CharField(max_length=200, blank=False) activity_duration = models.CharField(max_length=300, blank=False) activity_date = models.DateField(auto_now=False, blank=False) def __str__(self): return f"Activity: {self.activity_name} Started at: {self.activity_start} Activity Duration: {self.activity_duration}" serializers.py from rest_framework import serializers from .models import Activity from rest_framework.reverse import reverse class ActivityListSerializer(serializers.ModelSerializer): absolute_url = serializers.SerializerMethodField() class Meta: model = Activity fields = [ 'activity_name', 'activity_duration', 'activity_date', 'absolute_url' ] def get_absolute_url(self, obj): return reverse('activities_detail', args=(obj.pk,)) Only single dates are being returned: Objects with other dates exist: How can I return objects with date attributes within the range specified? -
DJANGO RANGE IN LIST
I have 1 problem is filter in a list of range. Does django have any method for filter in range of a list? For example: I have a list list_a = [(100,200), (300,400)] i tried Models.objects.filter(field_wanna_search__range__in=list_a) but it not work Can anybody help me on this! -
How to set value for time input in HTML? (I am using Django)
Inside a form, I want to input time. For this I am using the HTML input type="time" . I tried to set a value, but it does not appear Time value just appears empty <input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time }}"> This is how I tried to get it done. When the time default value did not appear, I tried formatting it like this- <input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time|time:'h i A' }}"> But it still doesn't work... I'm a newbie, and I'm not familiar with Javascript, so I would appreciate it if the answers were kept simple. Thank You -
Django sphinx docs made by cookicutter folder confusion
I'm a bit confused by the folder structure the sphinx makes for its documentation when starting a fresh new Django project with cookiecutter. I have my project set up in docker, as per instructions, everything is serving fine and I have the following folder structure for the documentation. When I run the command make html in the docs container (or by using the docker-compose local.yml file) I get the following structure. A new folder "html" is created and it's containing everything from the surrounding folders. Is this correct? Am I understanding the process correctly? For me, it looks like some bad settings for some source folder somewhere. I'm an experienced python dev, familiar with Docker as well, but I'm pretty new to Django and sphinx. Can somebody please guide me to the right path, possibly share their Django sphinx docs workflow? Thank you very much. -
foreignkey( settings.AUTH_USER_MODEL) should set its value to the current user automatically butI got this field is required?
Error when I send POST a request with {'title': 'bla bla'} I got this error { "created_by": [ "This field is required." ] } But when I send POST a request with {'title': 'bla bla','created_by':1} it work fine. MY Code #models.py from safedelete.models import SafeDeleteModel, NO_DELETE class MyModel(SafeDeleteModel): title = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #views.py class MySer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' class MyView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = MyModel.objects.all() serializer_class = MySer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) goals automatically add the currently authenticated user. I tried replace (SafeDeleteModel) with (models.Model)` set a defualt value created_by = models.ForeignKey( settings.AUTH_USER_MODEL,defualt=settings.AUTH_USER_MODEL on_delete=models.CASCADE) but nothing worked -
how to use try accept in a better way while making an object of model class to get data?
looking for help to handle the exception in a better way, I am new to python and django so if any one can suggest me that what can i write in place of pass, as i dont have any code to write there can i return Response(status=status.HTTP_200_OK) where pass is written or is there any thing which is better than this ? if(computedsignature==signature): try: order=Orders.objects.get(id=id) except (Payments.DoesNotExist): pass payment_collection_webhook_url=order.payment_collection_webhook_url application_id = order.applications try: application = Applications.objects.get(id=application_id) except (Applications.DoesNotExist): pass if(transaction_status=='SUCCESS'): try: payment= Payments.objects.get(orders=order,direction=direction) except (Payments.DoesNotExist): payment.save() -
How can i make a field editable in django admin when another boolean field is true or false?
here are my codes. i have viewed a couple of website and all am getting is just making the field readonly. -
Is there a way to check if some value is IN request.session.name?
Can anybody clarify, please? I got a Cart object in request.session I want to check if request.session.cart CONTAINS item.id as a key from template {% if game.id in request.session.cart %} I know that game.id is FOR SURE in that cart object, but template doesn't react on that. I HAVE a context processor added