Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku and AWS, Disappearing images
I have built a heroku app that basically stores photos that I upload. I have set up an AWS account with an s3 bucket and I have also set up my IAM user for full access. When I upload my images via the website, everything goes well and the images show in my bucket and on my albums, but I've just logged onto my website after around 24hrs and all the images I uploaded are gone and some are just not rendering. Now I know that this would happen if I was trying to store them on Heroku, but does anyone have any ideas why they're disappearing whilst I'm using AWS for storage? TYIA EDIT When I click on the images that are not rending to open in a new tab i get the following error. I removed some of the data just incase its private. Error Code AccessDenied Code Message Access Denied Message RequestId RequestId HostId HostId Error -
How can i convert this function to class in django
def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): if request.user.type in allowed_roles: return view_func(request, *args, **kwargs) else: return render(request, '403.html') return wrapper_func return decorator -
Changes in html template are not reflecting
I have made changes in html file and saved it but the changes won't reflect on the browser. I have refreshed the page but still nothing changed. I changed the colour of the text actually. -
How to prevent specific user from accessing django admin url?
I am working on django blog project. I noticed any one can see login panel if they visit www.example.com/admin/ Is it possible to restrict specific users from accessing the admin url path -
How can I get rid of the ModuleNotFoundError: No module named <modulename> error?
I'm getting ModuleNotFoundError: No module named 'bookList' when trying to run the bot I wrote. In the bkmBooks.py file, I imported my model " from bookList.models import BookList " in this way. However, after the migrate, the functions inside my bkmBooks.py file did not work. What might be causing this error? The order of file structure is as follows: bookList>bookfiles>bkmBooks.py Contents of my bkmBooks.py file: from ast import Str from base64 import decode import requests from bs4 import BeautifulSoup import pandas as pd import csv from time import sleep from random import randint import numpy as np from bookList.models import BookList # import bookfiles.bkmBooks as bkmBooks headers = dict() headers[ "User-Agent" ] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" def sendBooksToMysql(): bkmArt() def bkmArt(): pages = range(1, 3, 1) for page in pages: url = "https://www.bkmkitap.com/sanat" results = requests.get(url, headers=headers) soup = BeautifulSoup(results.content, "html.parser") book_div = soup.find_all("div", class_="col col-12 drop-down hover lightBg") sleep(randint(2, 10)) for bookSection in book_div: img_url = bookSection.find("img", class_="lazy stImage").get('data-src') name = bookSection.find("a",class_="fl col-12 text-description detailLink").get('title') author = bookSection.find("a", class_="fl col-12 text-title").get('title').replace('Model:', '') publisher = bookSection.find("a", class_="col col-12 text-title mt").get('title').replace(name, '') price = bookSection.find("div", class_="col col-12 currentPrice").text.replace('\n', '').replace('TL', ' TL') b_link … -
Image not updating django
In my edit.html I have a form where the user can edit information on a trainee. The user can add many trainees, edit them, delete them etc. Everything works fine there except the image. The imagefield of form appears in a very messy state. Also it does not update when I select a new image. Here is my code. I have cut down my code to make it more readable models.py class Trainee(models.Model): TraineePic = models.ImageField(null=True, blank= True, upload_to="traineeImg/") Name = models.CharField(max_length=50) class Meta(): db_table = "Trainee" forms.py class TraineeForm(forms.ModelForm): TraineePic = forms.ImageField(label="Image :", required=False) Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') class Meta(): model = Trainee fields = ("Name","TraineePic",) views.py class UpdateTrainee(UpdateView): model = Trainee template_name = 'MyTestApp/edit.html' form_class = TraineeForm success_url = reverse_lazy('show') edit.html {% extends "MyTestApp/base.html" %} {% block body_block %} {% load static %} <link rel="stylesheet" href="{% static '/css/bootstrap.min.css'%}" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <style> ul#id_Gender li{ display: inline-block; } </style> <body> <div class="jumbotron"> <h2> Edit Trainee </h2> <form method="post" class="form-group" type="multipart/form-data" data-ajax="false"> {%csrf_token%} {{form.errors}} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.TraineePic.label }}</label> {{form.TraineePic}} </div> <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Name.label }}</label> {{ form.Name }} </div> <input type="submit" value="Update" class="btn btn-dark"> </form> </div> </body> {% endblock %} Here … -
Can Elasticsearch be used as a database in a Django Project?
Can we directly use Elasticsearch as a primary database in Django? I have tried finding the solution or a way out but could not find any relevant information. Everywhere it is said that we can use Elasticsearch as a search engine over any other primary database. But as per my understanding Elasticsearch is a NoSQL Database, so there should be a way to use it as a Primary Database in a Django Project. Please help, if someone has any idea about it. -
'builtin_function_or_method' object has no attribute 'model'
I'm sorting by category and I get this error when starting the server. How to solve it? Error Image: https://i.stack.imgur.com/W4ROr.png filter/views.py from django.shortcuts import render from .filters import * from .forms import * # Create your views here. def filter(request): index_filter = IndexFilter(request.GET, queryset=all) context = { 'index_filters': index_filter, } return render(request, 'filter.html', context) filter/filters.py import django_filters from search.models import * class IndexFilter(django_filters.FilterSet): class Meta: model = Post fields = {'brand'} search/models.py from django.db import models class Post(models.Model): BRAND = [ ('apple', 'apple'), ('samsung', 'samsung'), ('huawei', 'huawei'), ('nokia', 'nokia'), ] img = models.URLField(default='https://omsk.imperiya-pola.ru/img/nophoto.jpg') title = models.CharField(max_length=80) brand = models.CharField(max_length=20, choices=BRAND) content = models.TextField() price = models.FloatField(default=1.0) def __str__(self): return self.title filter/urls.py from django.urls import path from .views import * urlpatterns = [ path('filter/', filter, name='filter') ] templates/filter.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="get" action="{% url 'index' %}"> {{ index_filters.form }} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </body> </html> -
When I pass a url parameter to modelform, None is passed instead of the url parameter
I am trying to build up a posting webpage. This is how it works: you click a button, the posting form will appear, you fill in the form, you click the submit button, and the process is complete. And when the form is submitted, a url parameter will be passed as the value of a hidden input in the modelform in the views.py. However, when I browse the model in manage.py shell, None is saved instead of the url parameter. Here are the codes: models.py from django.db import models from django.db.models import CharField, TextField, DateField class Post(models.Model): username = CharField(max_length=30, blank=True, null=True) content = TextField() dt_created = DateField(auto_now_add=True) dt_modified = DateField(auto_now=True) def __str__(self): return self.username forms.py from django import forms from django.forms import Textarea, HiddenInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'username'] widgets = { 'content': Textarea(attrs={ 'class': 'write_input', 'placeholder': 'write your story here...' }), 'username': HiddenInput(attrs={ 'value': ' ' }) } labels = { 'content': '' } urls.py from django.urls import path, include from . import views urlpatterns = [ path('<str:username>/main/', views.account_main, name='account_main') ] views.py from django.shortcuts import render, redirect from .forms import PostForm from .models import Post def account_main(request, username): … -
How to reduce ram usage when you load a model
when I try to load the model in my views.py the RAM usage get higger after that it gets normal, So how to make it always on normal usage ? I am using model Wave2Vec2Inference("facebook/hubert-xlarge-ls960-ft",cuda_flag = True) can anyone help me out -
How to implement reject/approve functionality with Django
For example, a model called Request, this model has a status field, status is by default "Awaiting", I want to make it possible for someone to change that through a form to "Approved" or "Rejected" I tried using some methods but they all didn't work. -
How to simplify phone_number field update Process in django including verification
Problem Description: We have a User model where Phone number is been set as username and its unique=True, We also have a field where to represent verified/unverified users. And we verify users by OTP verification to phone number. So now we need to add a new feature where user can replace his phone_number and then he will go to verification process and then we will change his number. And also We need to preserve his previous number (which he already verified) until this new number is verified. If for some reason user decides to go back without verification we delete newly added number and keeps his old number as username. So what would be the best way to approach this problem What I'm considering to have another Model linked with ForeignKey to User class AlternativeNumber(models.Model): user = User() # forignkey number = Charfield is_verfied = BooleanField So we will be verifying users number and replacing his original number from his alternativenumber_set Do you think we can simply it more. Do you think it might have some flaws or we go with a better appraoch ? thanks. -
Print several separate tables from one HTML document
I did the work and was able to render the data into tables. Now I have the following structure on the page: <div class="report-table-container mt-5" id="**current_pko_table**"> *some data* </div> <div class="report-table-container mt-5" id="**current_report_table**"> *some data* </div> <div class="report-table-container mt-5" id="**current_refund_to_customers_table**"> *some data* </div> Can anyone suggest a solution to make the "print all" button so that it only prints: current_pko_table, current_refund_to_customers_table, current_refund_to_customers_table? And also offer to separate the pages for printing, so that each of these documents is on a separate page when printed. I will be glad for any help. My whole project is built on django, but my experience with JS small. I will be glad for any help! -
thon310\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'CELERY_BROKER_URL'
we are facing key error while executing File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\os.py", line 679, in getitem raise KeyError(key) from None KeyError: 'CELERY_BROKER_URL' -
How to use remote user authentication using simple-jwt in Django Rest Framework?
I have two django projects/microservices which uses two separate databases: Todo auth - built for authentication - todo auth database Todo project - built to view todo information specific to a user - todo database What I basically require is, Once a user login using the todo auth project and get a token, When using the token in the todo project, the user should be authenticated and created (if the use does not exist) in the todo database with the help of Remote user authentication. I followed the below document in order to get what i achieve https://auth0.com/docs/quickstart/backend/django/01-authorization The problem is the document uses drf-jwt, i want to use simple jwt to achieve this. Please let me know how I can achieve this using simple jwt. Many thanks. Ps: Im running the two projects/microservices separately in the same develpopment server on two different ports -
Failed to Fetch when the request didn't fail and code seemingly executes fine
I am using elasticsearch-dsl to construct 2 complex queries and execute them over multiple indices at the same time with MultiSearch. It is working fine in 99% of cases but rarely fails for some input parameters with such an error printed on backend (Django): 2022-09-29 03:37:23,592 ERROR: https://aws_instance_name.us-east-1.es.amazonaws.com:443 For such input params it never is executed successfully, so its definitely dependent upon the inputs. The backend Django python code executes fine until the response is actually returned which I observe with logger.info statements, but the error is there. When I set the response to an empty one to exclude issues further down the line with the specificity of the response, it still fails, so it's as if it's not the issue of the response. I executed both queries separately (on backend they are executed together in one with MultiSearch, so it could potentially be some issue inside the MultiSearch itself) over the very same indices in AWS Kibana and both are returning results fine in a matter of a couple of seconds. I wonder if there is a way to print out detailed info about the issue and not just ERROR:aws_instance message that is useless. What else could go wrong … -
Table sort by the sum of aother related table
I have two tables name table name number memberA 1002 memberB 1003 memberC 1004 score table number score 1002 20 1002 30 1003 60 1003 60 1004 80 What I want to get is The member lists orderby total score For example memberA total score is 50 memberB total score is 120 memberC total score is 80 SO what I want to get is sorted name table memberB memberC memberA How can I do this? by django queryset? NameTable.objects.orderby('sum???') -
How To Convert Free Heroku Django To Paid App
Some time ago I created my first training Python Django Web application on Heroku because I could do it for free. It is a typical CRUD application with a persistent database. I have enjoyed showing it to others since then. I just received notice from Heroku that I need to convert it to a paid application. I having indeed spent hours pouring over the documentation cited about the conversion, but I am still confused about what exactly I need to do. I believe that the best path is to change the dyno status from "free" to "eco". That would cost only $5 a month. I am not sure about the database. Is that included, or would that need also to be converted to a paid "mini" postgres for an additional $5 a month? And would I have to do all the data conversion work manually, or does that happen automatically behind the scenes? Answers to these questions are key to understand if Heroku will still be a home for my application, or will I need to move it to another platform. Thank you. -
When I include a hidden field in my modelform, the modelform is not submitted
I am trying to build up a posting webpage. This is how it works: you click a button, the posting form will appear, you fill in the form, you click the submit button, and the process is complete. And when the form is submitted, a url parameter will be passed as the value of a hidden input in the modelform in the views.py. Everything had been working fine until I added in my modelform the 'username' field which has the HiddenInput as a widget. It seems like modelform is not submitted at all. Here are my codes: models.py from django.db import models from django.db.models import CharField, TextField, DateField class Post(models.Model): username = CharField(max_length=30) content = TextField() dt_created = DateField(auto_now_add=True) dt_modified = DateField(auto_now=True) def __str__(self): return self.content forms.py from django import forms from django.forms import Textarea, HiddenInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'username'] widgets = { 'content': Textarea(attrs={ 'class': 'write_input', 'placeholder': 'write your story here...' }), 'username': HiddenInput(attrs={ 'value': ' ' }) } labels = { 'content': '' } views.py from django.shortcuts import render, redirect from .forms import PostForm from .models import Post def account_main(request, username): context = dict() if request.method == … -
Get seperate task id in celery chain in Django
I am running a scraper in background using celery chain. I have 2 task that should run in a synchronous manner. result = chain(taskOne.si(data= data), taskTwo(data = data)).delay() This code works,as i can see the return data in the terminal. However, i could not get the task id for each individual task. I tried assigning a variable into them but it will not trigger the celery chain. result = chain(taskOneData = taskOne.si(data= data), taskTwoData = taskTwo(data = data)).delay() if i print 'result' it will only show me the task id of the last task. -
Programming Error creating automatic instance
I am using django and I encountered an error. I want to create to IncidentGeneral automatically when a UserReport was created. How can I achieve it? Error: ProgrammingError at /admin/incidentreport/userreport/add/ column incidentreport_incidentgeneral.user_report_id does not exist LINE 1: SELECT "incidentreport_incidentgeneral"."user_report_id", "i.. class UserReport(models.Model): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default='Anonymous') description = models.TextField(max_length=250, blank=True) location = models.CharField(max_length=250) upload_photovideo = models.ImageField(default='user.jpeg', upload_to='incident_report/image') date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) status = models.PositiveSmallIntegerField(choices=STATUS, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_status(self): if self.status == 1: incident_status = 'Pending' elif self.status == 2: incident_status = 'Approved' elif self.status == 3: incident_status = 'Rejected' return incident_status def __str__(self): return self.user.username class IncidentGeneral(models.Model): WEATHER = ( (1, 'Clear Night'), (2, 'Cloudy'), (3, 'Day'), (4, 'Fog'), (5, 'Hail'), (6, 'Partially cloudy day'), (7, 'Partially cloudy night'), (8, 'Rain'), (9, 'Rain'), (10, 'Wind'), ) LIGHT = ( (1, 'Dawn'), (2, 'Day'), (3, 'Dusk'), (4, 'Night'), ) SEVERITY = ( (1, 'Damage to Property'), (2, 'Fatal'), (3, 'Non-Fatal'), ) user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE, primary_key=True) accident_factor = models.OneToOneField(AccidentCausation, on_delete=models.CASCADE) collision_type = models.OneToOneField(CollisionType, on_delete=models.CASCADE) crash_type = models.OneToOneField(CrashType, on_delete=models.CASCADE) weather = models.PositiveSmallIntegerField(choices=WEATHER, blank=True, null=True) … -
How to set a form as submitted while being inside a form loop in a Django Project?
I have a Log model with a LogForm form as following: class Log(models.Model): submitted = models.BooleanField(default=False) log_order = models.IntegerField(.......) log_weight = models.FloatField(........) log_repetitions = models.IntegerField(.....) class LogForm(forms.Form): log_order = forms.IntegerField() log_weight = forms.IntegerField() log_repetitions = forms.IntegerField() I have a for loop in my template which because I have a table with different information I have a loop of forms generating in this case for simplicity I have 3 forms to insert different log infomration it is as following: {% for e in exercises %} {% for b in e.breakdowns.all %} <form action="{% url 'my_gym:addlog' workout.id %}" method="post"> {% csrf_token %} <input hidden type="number" name="log_order" value="{{ b.order}}" required id="id_log_order"> <div> <input type="number" name="log_weight" required id="id_log_weight"> <input type="number" name="log_repetitions" required id="id_log_repetitions"> </div> <div> {% if Log.submitted %} <button> Already Submitted </button> {% else %} <button type="submit" id="submitlog"> Click to Submit </button> {% endif %} </div> </form> {% endfor %} {% endfor %} Here is the view: class workout_details(DetailView): model = Workout template_name = 'template.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) p = Log.objects context = super().get_context_data(**kwargs) context['exercises'] = exercises context['form'] = LogForm() context['p'] = p return context def addlog(request, id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': form = … -
How do you get the DJango form data that were appended?
How do you get all row data of the forms that were appended? I have a form with 5 numbers per row, and some 'N' number of rows that are selected by the user is appended. Form: class locker(forms.Form): num0 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num1 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num2 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num3 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) num4 = forms.IntegerField(label='', min_value=1, max_value=25, required=True) View: # Render form ... count = 3 newForm = locker() context.update({ 'locker': newForm, 'lockerCount': range(count) }) ... Template: # Display form ... <div class="lockers"> <form name="longForm" action="" method="post"> {% csrf_token %} {% for i in lockerCount %} {{ locker }}<br /> {% endfor %} <br /> <input type="submit" value="submit" class="small-button"> </form> </div> ... I've tried various methods searched from google, and the closest I got was: ... data = form.cleaned_data.items() for q in data: ... but it's getting only the last row of numbers. Looking at the console, I do see all the data (below). I'm trying to get all rows of the form, each row containing 5 sets of integers. Please help. [29/Sep/2022 23:19:42] "POST /main/ HTTP/1.1" 200 10113 [29/Sep/2022 23:20:43] "GET /main/?csrfmiddlewaretoken=w3YIsEf1Af2hX4IRfPIVShZCdUjh9EEnbu2o8UGbI8XFbcTif6f1FlviC3KoHDM8&num0=7&num1=6&num2=21&num3=5&num4=11&num0=22&num1=4&num2=6&num3=19&num4=10&num0=9&num1=14&num2=20&num3=3&num4=25 HTTP/1.1" 200 7687 -
How to return calculations to a template for all objects in a class model in Django
I am trying to build a simple form which calculates which machine would run a film width the quickest, the parameters and capabilities of each machine are held in a django model. The width of the film and how much of it will be entered in the form and the quantity needed. The function should work out which machine(s) can run it, what the max speed is and the average speed over the machines that are capable. I want to return the values of the calculation and maybe run a for loop and display the values for each machine in a results.html template in a table. I also want to display average times across machines capable of running the widths of film. I had some success with lists but would like to use a class that I can use in the template and do away with the lists. Any help with this would be much appreciated as I am getting pretty lost in it! I have only started on the 'Layflat Tubing' function in the hope that I can get it right and just copy down to the other functions. from django.views.generic.base import TemplateView from django.shortcuts import render import math, … -
How do I invert in Django the pretty "yes", "no" icons of a BooleanField in the Admin site?
When your model has a BooleanField, the Django Admin site displays circular icons: a green checkmark for "True" a red X for "False" The Django docs call those icons "pretty": If the field is a BooleanField, Django will display a pretty “yes”, “no”, or “unknown” icon instead of True, False, or None. it looks great! but my BooleanField is called "pending" so if pending = True , I want Django Admin site to display a red X instead of a green checkmark. Because green means "good" and red means "bad". Most of my entries are not pending, so the list is full of red X icons, it looks bad, I want them to be mostly green checkmarks instead. I know I could add a def in the model with a return not self.pending but that displays the words "True" and "False" instead, I want the icons.