Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I assign the testcases reviewer
I configed the email settings and could receive registration email, forgot-password email etc. successfully. But, I can not receive the review notification email when I input reviewer email. I still do not find any solution in the userguide. So How do I fix this? -
how to use django model object in django templates?
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the ActivityPeriod(model) of that user. Please check my code for the clarity: Here is my code: views.py from .models import User,ActivityPeriod def call_response(request): user = User.objects.all() return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod}) Test/list.html {% for user in users %} 'real_name': {{ user.real_name}}}, 'activity_periods': {% with activity=activityperiod.objects.get(id =user) %} {{ activity.start_time }} {% endwith %} {% endfor %} But i am getting an error: Could not parse the remainder: '(id' from 'activityperiod.objects.get(id' What is the correct way? Can anyone please share it with me. -
Django admin list page takes forever to load after overriding get_queryset method
I have this model admin - class NewsAdmin(ImageWidgetAdmin): image_fields = ['featured_image'] list_per_page = 20 list_display = ('heading', 'category', 'status', 'is_active', 'created_at', 'published_at', 'created_by', 'published_by') list_editable = ('category', 'status', 'is_active') list_filter = ('published_at', 'created_at', 'status', 'is_active', 'created_by', 'published_by',) search_fields = ('heading', 'category', 'tags', 'source') actions = [enable_object, disable_object, status_draft, status_private, status_public] actions_on_bottom = True It only takes max 400ms to load. Here's the django-debug-toolbar image - djdt image without get_queryset But when I override the get_queryset method for language filtered objects - def get_queryset(self, request): queryset = super(NewsAdmin, self).get_queryset(request) return queryset.filter(language=request.LANGUAGE_CODE) It takes around 17-18 seconds which is nuts!! Here's the django-debug-toolbar image - djdt image with get_queryset Even same this is happening for the front end queries as well! For details - I have database table with around 400k records and here's the model - class News(BaseEntityBasicAbstract, HitCountMixin): NEWS_STATUS = ( ('draft', _('Draft')), ('pending', _('Pending')), ('review', _('Review')), ('public', _('Public')), ('private', _('Private')) ) backup = models.BooleanField(default=False) prev_id = models.BigIntegerField(null=True, blank=True) language = models.CharField(max_length=10, choices=LANGUAGES, default='bn') heading = models.CharField(max_length=255, null=True, blank=True, verbose_name=_('News Heading'), help_text=_('Provide a news heading/caption.')) sub_caption = models.TextField(max_length=255, null=True, blank=True, verbose_name=_('Summary'), help_text=_('Provide summary of the news.')) url = models.CharField(max_length=255, unique=True, verbose_name=_('URL/Slug/Link'), help_text=_('Unique url for the news without whitspace.')) content = … -
Why my django form cleaned data returns None everytime?
I am using the self-referential Foreign Key in my models. In the views when I used the form.cleaned_data.get('parent') it returns None but when I used request.POST.get('parent') it returns the value. Why the cleaned_data is not working here? models class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True, max_length=50) title = models.CharField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) forms class CreateCategoryForm(forms.ModelForm): class Meta: model = Category fields = ['title', 'slug'] views def create_category(request): form = CreateCategoryForm() categories = Category.objects.order_by('-created') if request.method == 'POST': form = CreateCategoryForm(request.POST) if form.is_valid(): # parent = request.POST.get('parent') # works # parent = form.cleaned_data.get('parent') # returns None category = form.save(commit=False) category.parent = form.cleaned_data.get('parent') category.save() messages.success(request, 'Created Successfully.') return redirect('list_categories') return render(request, 'add_category.html', {'form':form, 'categories':categories}) template <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label>Category Name</label> <input type="text" name="title" class="form-control" value="{{form.title.value|default_if_none:''}}"/> {% if form.title.errors %} <span class="error">{{form.title.errors|striptags}}</span> {% endif %} </div> <div class="form-group"> <label for="select" class="">Category Parent</label> <select name="parent" id="exampleSelect" class="form-control"> <option selected>Select</option> {% for category in categories %} <option value="{{category.pk}}">{{category.title}}</option> {% endfor %} </select> </div> -
Django : no such table
I am using a ManyToMany relationship using an intermediate table (keyword through) in django and I get a OperationalError at /admin/workoutJournal/workout/add/ no such table: workoutJournal_workoutexercise My code is the following : class Exercise(models.Model): name = models.CharField(max_length=120, default='') def __repr__ (self): return 'self.name' def __str__ (self): return self.name class planesOfMovement(models.TextChoices): SAGITTAL = 'SA', _('Sagittal') FRONTAL = 'FR', _('Frontal') TRANSVERSAL = 'TR', _('Transversal') planesOfMovement = models.CharField( max_length=2, choices=planesOfMovement.choices, default=planesOfMovement.FRONTAL, ) class typeOfMovement(models.TextChoices): PUSH = 'PS', _('Push') PULL = 'PL', _('Pull') CARRY = 'CA', _('Carry') LOAD = 'LO', _('Load') typeOfMovement = models.CharField( max_length=2, choices=typeOfMovement.choices, default=typeOfMovement.LOAD, ) class Workout(models.Model): date = models.DateField(default=datetime.date.today) exercises = models.ManyToManyField(Exercise, through='WorkoutExercise') def __str__(self): # __unicode__ on Python 2 return self.name # class Meta: # db_table = "workoutJournal_Workout_exercises" # necessary to update migrations when modifying the through # # argument of an existing relation class WorkoutExercise(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.DO_NOTHING) workout = models.ForeignKey(Workout, on_delete = models.PROTECT) sets = models.PositiveIntegerField() reps = models.PositiveIntegerField() tempo = models.CharField(max_length = 11, validators=[ RegexValidator(r'[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}', message='Please format your tempo as [0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}') ]) Any idea what I am doing wrong ? -
making the whole page blur when I click on a certain button
so, I have a button and I want the whole body to go blur when I click on it and show an alert or a pop-up message. this is what I have been trying to do: function myFunction() { $('body').css("filter","blur(2px)"); alert("hello"); } <div class="phone_num d-none d-xl-block"> <a class="boxed-btn3" href="{% url 'homepage' %}" onclick="myFunction">{% trans 'try' %}</a> </div> but I have a couple of issues: 1- the blur doesn't last until I click okay to the alert and moves to the next page right away. 2- the alert is way up on the top of the page o can I some how move to the middle of the page? -
Get latest ID in Django returns object is not iterable
I tried to get the latest id in Django but get the error. def getlatestid(request): cot_info = COT.objects.latest('id') return JsonResponse({"data": list(cot_info)}) TypeError: 'COT' object is not iterable -
Get latest ID in Django returns object is not iterable
I tried to get the latest id in Django but get the error. def getlatestid(request): cot_info = COT.objects.latest('id') return JsonResponse({"data": list(cot_info)}) TypeError: 'COT' object is not iterable -
How to reuse Django app into another project
I have made a user registration app in a Django project. I want to add this app (reuse) into another project. How can I do this ? -
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed
I am getting contentNotRenderedError while upgrading from Django 1.10 to Django 1.11. I am fairly new to the framework and don't know what's going on. Could anyone help or give me some clues? HTTPServerRequest(protocol='http', host='mywebsite', method='GET', uri='/api/v1/lanManagerOptions?routerId=1', version='HTTP/1.0', remote_ip='127.0.0.1', headers={'X-Forwarded-Proto': 'http', 'Host': 'mywebsite', 'Connection': 'close', 'X-Request-Id': 'dacd3c74a93922893b2009c24a3c4bed', 'X-Real-Ip': '65.153.116.34', 'X-Forwarded-For': '65.153.116.34', 'X-Forwarded-Host': 'mywebsite', 'X-Forwarded-Port': '443', 'X-Scheme': 'https', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0', 'Accept': 'application/vnd.api+json; charset=utf-8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/vnd.api+json; charset=utf-8', 'Origin': 'https://dcm-fbar-temp6-3707.dcm.public.aws.mywebsite.com', 'Referer': 'https://dcm-fbar-temp6-3707.dcm.public.aws.mywebsite.com/dcm.html', 'Cookie': '_ga=GA1.2.1664587868.1582810494; experimentation_subject_id=ImQ0NjI4N2VlLTI4MmYtNDQzYS1iOTAxLWMwOTA5MzU4MWVlNiI%3D--cb04922dd4b62d7113de78a524ca37a8316e0779; _gid=GA1.2.1519592971.1590643532; sessionid=wmxk23fb5j3r7qwzr7s0hk0tm64xhb24; jwt=<jwt>; _gat=1'}) Traceback (most recent call last): File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/web.py", line 1511, in _execute result = yield result File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/gen.py", line 1055, in run value = future.result() File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "<string>", line 4, in raise_exc_info File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/gen.py", line 1069, in run yielded = self.gen.send(value) File "<string>", line 6, in _wrap_awaitable File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 280, in get await self._handle_request(*args, **kwargs) File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 272, in _handle_request response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 179, in get_response response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 44, in middleware_mixin__call__ response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 44, in middleware_mixin__call__ response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 44, in middleware_mixin__call__ response = await response … -
Error while uploading images with EasyMDE
I am using EasyMDE text editor on my Notemaking website, but for some reason, the uploadImage functionality doesn't work. This is how I instantiate EasyMDE. var easyMDE = new EasyMDE({ autofocus: true, autorefresh: true, spellChecker: false, minHeight: '180px', uploadImage:true, }); Can some one help me fix this issue or point me in the right direction of how to solve it? -
How To Change HTML In A Live Editor
For a personal project I am trying to create a theme editor with Angular (version 8.2.14) for my frontend and Django (version 3.0.5) for my backend. I am then using Jinja2 for the various themes. Right now I am stuck on how to have a live preview of the theme with inputs available to change the theme accordingly. Right now in my Angular component I load the Jinja2 template into an iframe. The system works flawlessly on initial load using JSON to set the variables, but I just can't figure out the live editor. I feel as if I am halfway there but missing something. So far I have a function in my typescript that sends a post message on every key press. sendToFrame(event, id) { // event is the keypress // id is what is set to the data attribute const iframe = document.getElementById('preview') as HTMLIFrameElement; if (iframe && iframe.contentWindow) { const message = {'id': id, 'value': event.target.value}; iframe.contentWindow.postMessage(message, '*'); } } then in the head of my Jinja2 theme I receive that message and use vanilla JS to change what I need to. window.addEventListener('message', function(event) { let elementToChange = document.querySelector('[data-theme-editor-setting="' + event.data.id + '"]'); elementToChange.innerHTML = event.data.value; }, … -
How to use check_password function in django
I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm. I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does? def save(request): if request.method == 'POST': name = request.POST.get('name') password = request.POST.get('pass') enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32) a = signup(username = name, password = enc_pass) a.save() return render(request,'save.html') def login(request): if request.method == 'POST': username = request.POST.get('user') password1 = request.POST.get('password1') p = check_password(password=password1) if signup.objects.filter(username__exact=username).exists() and p is True: return HttpResponse("Success") else: return HttpResponse("Invalid Credentials") return render(request, 'login.html') -
Not Found: /available.html "GET /available.html HTTP/1.1" 404 2319
I am trying to create a path for the second function on my views page so I can create a buyers page and connect it to the database, but I am having difficulties finding help online for this specific problem so if someone could help and also show me a good series to watch to help with the creation of this private server ran website. Page not found (404) Not Found: /favicon.ico [01/Jun/2020 23:18:35] "GET /favicon.ico HTTP/1.1" 404 2310 Request Method: GET Request URL: http://127.0.0.1:8000/available.html Using the URLconf defined in TJWEXOTICS.urls, Django tried these URL patterns, in this order: admin [name='home-page'] [name='available-page'] The current path, available.html, didn't match any of these. it says this after i run the server and then try to go to the pythons page: You're seeing this error because you have DEBUG = True in your Django settings file. Change that to >False, and Django will display a standard 404 page. heres the urls.py paths: from django.urls import path from . import views urlpatterns = [ path(r'', views.title, name='home-page'), path(r'', views.available, name='available-page') ] Here is the views.py code: from django.shortcuts import render from django.template import loader from django.http import HttpResponse from .models import Snake # Create … -
How to change the django cms admin logo?
Is there any way to change the Django CMS admin logo? I tried many things to change the logo of Django cms admin but unable to. Can anyone help me? -
Django Web Application, Facebook login
I am building a basic social media web application and I would like my only login point to be via facebook login. After doing a fare amount of research, I have seen multiple third party authorization frameworks that plug in with facebook, but I was wondering if there were any opinions on what the best foot forward would be. Additionally, how would I go about still being able to use sessions/cookies within Django if I use fb login? All answers are appreciated! -
Calling obj_id in html using django
I have this code in my html {% for gradelevel in gradelevels %} <tr> <td class="tdcell"><input type="hidden" name="id" value="{{gradelevel.id}}">{{gradelevel.id}}</td> <td colspan="2" class="tdcell"><input type="text" value="{{gradelevel.Description}}" name="gradelevel"></td> <td colspan="2" class="tdcell"> <select name="status"> <option>{{gradelevel.Status}}</option> <option value="Active">Active</option> <option value="Inactive">Inactive</option> </select> </td> </tr> {% endfor %} this is what its looks ln web view this is my logic on updating what i selecting data to update def UpdateEducationLevel(request): id = request.POST.get('id') print("id", id) desc = request.POST.get('gradelevel') status = request.POST.get('status') update = EducationLevel.objects.get(id=id) update.Description=desc update.Status = status update.save() why is it i can update the College record but when i tried to update for example Grade 1 it didnt update. when i tried to print the id = request.POST.get('id') print("id", id) i always get ("id", 14) -
What do I do with all the logic in my django views when converting my project to django rest api with reactJS?
I created a web app all in django. I am now wanting to practice using reactJS on the front end, therefore it seems I need to make my django app an api end point to send and receive json data from reactJS. Now, my understanding is the api views are all very simple just to post and get data. My question is, where do my normal views go? I'd assume these views and logic all now has to go in reactJS front end with JS? For example, one view in my current django app is what to do after user submits a youtube channel in a form. The view goes through all the logic (ie if it exists and is registered, show all the related comments, if the channel exists but not registered, register and save in db, if doesn't exist on youtube notify and stay on current page. This logic has to be now put on front end if I switch to using django rest api? I can't get my head around this. Thanks! -
django model reference, Add more contraint to reference
I have question about Django model referrence I want to add more contraint to ForeignKey or ManytoManyField like this : * question_id = models.ManyToManyField(Question(open==True)) * Or put another similar contraint : Acctually I don't want to show question that is not open as a selection in Answer form like image bellow, ofcourse i have do it by some query but does Django has any built-in support for it, i have try some way but it 's not worked. Thanks! class Answer(models.Model): """Give answers""" answer = models.TextField() question_id = models.ManyToManyField(Question(open==True)) upVote = models.IntegerField(default=0) downVote = models.IntegerField(default=0) def __str__(self): """return string """ return self.answer -
Django: django.db.utils.OperationalError: no such table: #deprecated_bug_assignee when to use "POST" method, but "GET" method is ok
GET Method can reponse data, happened error when to use "POST" method,the error is “ django.db.utils.OperationalError: no such table: #deprecated_bug_assignee ”, but "GET" method is ok, why? they are using the same table ! views.py from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class DeprecatedBugAssigneeList(APIView): """ 列出所有的snippets或者创建一个新的snippet。 """ def get(self, request, format=None): dbsa = DeprecatedBugAssignee.objects.using('slave').all() serializer = DeprecatedBugAssigneeSerializer(dbsa, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = DeprecatedBugAssigneeSerializer(data=request.data) if serializer.is_valid(): bug_serializer = serializer.save() bug_info = DeprecatedBugAssignee.objects.filter(bugid__exact=request.data['bugid']) bug_serializer.add(*bug_info) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py from apps.cn_relnotes.models import DeprecatedBugAssignee, DeprecatedBugCode class DeprecatedBugAssigneeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DeprecatedBugAssignee fields = ('bugid', 'oassignee', 'nassignee', 'opdatime', 'operatornm', 'state', 'duration') models.py from django.db import models class DeprecatedBugAssignee(models.Model): bugid = models.IntegerField() oassignee = models.CharField(max_length=255) nassignee = models.CharField(max_length=255) opdatime = models.DateTimeField() operatornm = models.CharField(max_length=255) state = models.CharField(max_length=64, blank=True, null=True) duration = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = '#deprecated_bug_assignee' unique_together = (('bugid', 'opdatime'),) urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from apps.cn_relnotes import views urlpatterns = [ url(r'^v1/bug/$', views.DeprecatedBugAssigneeList.as_view()) ] urlpatterns = format_suffix_patterns(urlpatterns) -
Error after replacing appname with appname.apps.appnameConfig
As I write some code in appnameConfig.ready() for running them at the beginning of server start. I just change appname to appname.apps.appnameConfig in settings.INSTALLED_APPS and error occur as below: File "/home/user/venv/venv/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/home/user/venv/venv/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/home/user/venv/venv/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What's wrong is it? -
Django: What could cause duplicate permissions to be created in the auth_permission table?
I'm currently working on a Django app that has been maintained for 4+ years at this point. I joined the team not too long ago. I was getting complaints about group permission issues, and after a lot of inspection, I found out that there were many duplicate permissions. id | name | content_type_id |codename ----+----------------+-----------------+-------- 1 can add x 1 add_x 2 can add y 2 add_y 3 can add y 1 add_y I see this kind of behavior in the table where the name/codename is a duplicate of some other valid entry, but then the content_type_id arbitrarily uses some other content_type_id that doesn't relate to it at all. It doesn't happen to every permission, but there are a quite a few in which it is happening. This is a pattern I have observed if the database that this app is connected to has been continually migrated/upgraded over years, then the auth_permission table seems to have this issue of duplicate permissions with random content_type_id. However, when I run the app on my local with the latest version and run the migrations on a fresh db, I get no such issues. I suspect it has to do something with migrations. Is … -
Better way to deal with private API which doesn't support CORS
I'm working on the Imperva API with axios. After digging the document of the API and doing some tests, the API seems like doesn't support CORS. Since that the Imperva API requires user to send requests with key, I think is not a good idea to use something like cors-anywhere. My current plan is to set up a CORS proxy on my backend server(Django). However, I'm not sure if this is a good way to solve the problem and also not sure if Django can do this trick. Please give me some advices on this. Thanks a lot! -
(Django, Python) json.decoder.JSONDecodeError: Expecting value: line 17 column 2 (char 636)
I have been trying to make an order/cart app for a sandwich shop. While I am testing I keep getting the error that has to do wich decoding the JSON data front-end engineers send me. Below is the POST request that the server receives. { "default_ingredients": [ { "id": 1, "name": "이탈리안 화이트 (top)", "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_BreadItalian_customizer_large.png", "price": "0.00", "ingredient_category_id": 1 }, { "id": 23, "name": "토마토", "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/OptionsIds/10133_customizer_large.png", "price": "0.00", "ingredient_category_id": 3 }, ], "added_ingredients": [ { "id": 18, "name": "살라미", "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_TurkeyBasedHamSalamiBologna_customizer_large.png", "price": "0.00", "ingredient_category_id": 2 }, { "id": 19, "name": "페퍼로니", "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_Pepperoni_customizer_large.png", "price": "1800.00", "ingredient_category_id": 2 }, ], "product_name": "이탈리안 비엠티", } And below is my views.py for the order app import json import ast import jwt import bcrypt from django.views import View from django.http import JsonResponse from .models import ( Order, Cart, CartIngredient, DestinationLocation, OrderStatus ) from product.models import ( Product, Category, SubCategory, Nutrition, Ingredient, ProductIngredient ) from store.models import Store from account.models import Customer from codesandwich.settings import SECRET_KEY def login_required(func): def wrapper(self, request, *args, **kwargs): header_token = request.META.get('HTTP_AUTHORIZATION') decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['email'] try: if Customer.objects.filter(email=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "customer does not exist"}) except jwt.DecodeError: return JsonResponse({"message": "WRONG_TOKEN!"}, status=403) except … -
Django: Static files are not found
I'm trying to add some static files to my project. I have tried adding a static folder to my app. I have two apps: Authentication (authn), Main (main). I have a lot of CSS/js content and I don't really know which is the best method to save the files, maybe all static files should be in one directory 'staticfiles' or each app should have 'static' folder. I have tried adding static folder to one of my apps, at this time - authn. And by trying to load the static files I firstly did python manage.py collectstatic, that put my all files into one folder, but I got two different folders now - admin, main. After tried putting all my static files into a static folder in authn app, but the static files were not loading after that. Here are my project structure and some photos and logs of the console, pycharm.