Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to throttle redis/celery tasks for a django web site?
I have a django v3.0.2 site (python v3.6.9) where I upload an image, process the image, and then display it on a web site. By process the image, I create different sizes of the the one image, find and identify faces, ocr any text and translate it if needed, use several different algorithms to calculate how similar each image to the others, and other image processing algorithms. I use celery v4.3.0 and redis v4.0.9 to do all the calculations in the background in different celery tasks. The issue I am having is that when I try to upload and process more than ~4 images in a loop, I run out of memory and the calculations start to throw exceptions. By run out of memory, my 5 GB of swap and 16 GB of ram are all used up and chrome even crashes. In my database, I keep a log of the progress of each task and whether it completes successfully or not. I can see many errors and many tasks not started. If I put a time.sleep(10) in the loop that uploads the images and right after the celery workers are launched for each image, I can upload 60+ images … -
how to save bootstrap modal form upon submit in django?
I'm new to ajax and I need help. I was able to open the modal when I clicked the Add grade, now my problem is how to save the form to the database using modal? that error page will show if I hit the save changes in modal form. views.py class GradeUpdateView(LoginRequiredMixin, UpdateView): model = Subject template_name = 'teacher/modal.html' # fields = ['grade'] # success_url = '/' form_class = UpdateGradeForm def get_success_url(self): subject = self.object.subject_name year = self.object.year_taken return reverse_lazy('student-list', kwargs={"subject_name_id": subject.id, "year_taken": year}) modal.html <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" id="grade-form"> <div class="modal-body"> {% csrf_token %} {{ form.as_p }} {% comment %} <input type="submit" class="btn btn-sm btn-block btn-primary" value="Save"> {% endcomment %} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" data-form-url="" class="btn btn-primary" id="save-form">Save changes</button> </div> </div> </form> </div> </div> </div> main.js var modalDiv = $("#modal-div"); $(".open-modal").on("click", function () { $.ajax({ type: 'GET', url: $(this).attr("data-url"), success: function (data) { modalDiv.html(data); $("#exampleModalCenter").modal(); } }); }); -
Automatically taking picture when face detected using Django?
I successfully used StreamingHttpResponse to open the webcam on a template and detect face. But I don't know how to automatically take picture of the detected face and display it on the template. -
Implementing Pagination with Django-Filter
I am looking to implement Pagination with Django-Filter's function based view. I currently have the search function working, but have not been able to find documentation online on how to implement pagination with Django-filter; haven't been able to get it working with references i've found online. What I have so far: views.py from django.shortcuts import render from .models import Stock from .filters import StockFilter def home(request): return render(request, 'stockwatcher/home.html', {'title': 'Home'}) def stock_search(request): f = StockFilter(request.GET, queryset=Stock.objects.all()) return render(request, 'stockwatcher/search_results.html', {'filter': f}) filters.py import django_filters from .models import * class StockFilter(django_filters.FilterSet): senator = django_filters.CharFilter(field_name='senator' ,lookup_expr='icontains') ticker = django_filters.CharFilter(field_name='ticker', lookup_expr='iexact') class Meta: model = Stock fields = [ 'senator', 'ticker' ] exclude = [ 'asset_description', 'asset_type', 'amount', 'type', 'transaction_date', ] urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.home, name="stockwatcher-home"), path('stocks/', views.stock_search, name="stockwatcher-stocks"), path('about/', views.about, name="stockwatcher-about")] search_results.html {% extends "stockwatcher/base.html" %} {% block content %} {% load widget_tweaks %} <div class="container"> <div class="row" style="padding: 50px;"> <form method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> </div> <div class="row"> {% for stock in filter.qs %} <div class="col-4"> <div class="card text-white bg-info mb-3" style="max-width: 18rem;"> <div class="card-header">{{stock.transaction_date}}</div> <div class="card-body"> <h5 class="card-title" style="color: white"> {{stock.ticker}} </h5> <p class="card-text">{{stock.senator}} - … -
Does anyone know why base appears instead of virtualvenv? Pycharm
Does anyone know why base appears instead of virtualvenv? How can I reactivate it? I am with Pycharm on Windows I was working well with venv and suddenly at night he changed it for base -
Django: Show many objecets values without writing them all
In my model I'have many questions for my user, so when I try to show the results using a for loop my code became kinda big and I'm also afraid of errors. I was wondering if there is a smarter way to display only the "a,b,c" user inputted answers (without the user and the date fields) with way less code. Here what I'm doing since now: model class Question(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) start_date = models.DateField(default=datetime.now) finish_date = models.DateField(default=datetime.now) a = models.CharField(null=True) b = models.CharField(null=True) c = models.CharField(null=True) ... html {% for answer in answers %} {{ answer.a }}, {{ answer.b }}, {{ answer.c }} ... {% endfor %} views def show_answers(request): answers = Question.objects.filter(user=request.user.profile) return render(request, 'show_answers.html', {'answers': answers}) -
How can I have a form redirect to same page after submitting in Django?
How can I set my function in views.py so that a form redirects to the same page after submitting? For example, I want to add time slots: In my views.py: @login_required def post_available_timeslots(request): print("Check") if not check_existing_timeslot(request): print("Time slot does not exist") instance = TimeSlot() data = request.POST.copy() data["time_slot_owner"] = request.user # data["food_avail_id"] = FoodAvail.objects.get(author=request.user).pk form = TimeSlotForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return redirect("food_avail:view_food_avail_res") else: print("Time slot does not exist") messages.info(request, "Time Slot Already Exists") return render(request, "food_avail/view_food.html", {"time_slot": form}) in models.py class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) # food_avail_id = models.ForeignKey(FoodAvail, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.start_time) + "-" + str(self.end_time) In forms.py: class TimeSlotForm(ModelForm): class Meta: model = TimeSlot fields = ["start_time", "end_time"] In urls.py: from django.urls import path from food_avail import views app_name = "food_avail" urlpatterns = [ path("post_food_avail/", views.post_available_food, name="post_food_avail"), # path("post_food_avail/", views.FoodAvailCreateView.as_view(), name="post_food_avail"), # path("update_food_avail/", views.post_available_food, name="update_food_avail"), path("food_avail_all/", views.check_food_availibility, name="view_food_avail"), path("food_avail_res/", views.view_available_food, name="view_food_avail_res"), # path("food_avail_res/", views.post_available_timeslots, name="create_timeslots"), ] in my html template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> {{ field.label }} <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for … -
AWS s3bucket "can only concatenate str (not "NoneType") to str"
Im having trouble finding out whats the problem. I don't know what's causing the error if its boto3 or s3bucket , DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' seems to be the problem. At least when I remove DEFAULT_FILE_STORAGE the templates render. I either get 'NoneType' object has no attribute 'encode' for every template or "can only concatenate str (not "NoneType") to str" attempting to upload image. settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ["localdeals1.herokuapp.com", 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Products.apps.ProductsConfig', 'Users.apps.UsersConfig', 'django_filters', 'crispy_forms', 'widget_tweaks', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', 'Products.context_processors.Products_and_Users', ], }, }, ] WSGI_APPLICATION = 'Ecommerce.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Los_Angeles' USE_I18N = True USE_L10N = True USE_TZ = True GEOIP = os.path.join(BASE_DIR, "Products") STATIC_URL = '/static/' … -
Create a from builder using Django
I am fairly new to programming and start my career with Python Django. I already build some basic application and recently came across to use google forms and decided to create application like this. Where any user can come to certain page and can able to create his own form as per his requirement. I though of some new features like drag and drop. I wanted to ask if that's somehow possible to drag drop input fields or something like that using Django template system where I can use some simple JS library or if its possible using React as fronted. So my requirements are quite simple, but I am confused with Django models that what will be the structure of models. UI should be drag n drop thing. User can select the list of fields available in the inventory. And create his own form. And on post submission. From django you need to capture and store the data. Here in this case the data will be the form fields as well as its values. Ex form fields which are available in the inventory. Test field Email Field Multi select field and Drop Down Field= I hope someone can help … -
Registration form not submitting user info in django app
I'm somewhat new to Django and I'm working on user auth for my first larger scale app right now. Here are images of my app views.py file, my app urls.py, and my register.html template (which extends my base of just a navbar currently). Right now, the form will render when I use /register/ path in the browser, but the register button does nothing. {% extends "base.html" %} {% block title %}Create an Account{% endblock %} {% block content %} <form method="POST" action="register/" class="form-group"></form> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-success" value="Submit">Register</button> </form> {% endblock %} from django.urls import include, path from . import views urlpatterns = [ path('', views.summary, name='summary'), path('form/', views.form, name='form'), path('results/', views.results, name='results'), path('goals/', views.goals, name='goals'), path('news/', views.news, name='news'), path('login/', views.login, name='login'), path('register/', views.register, name='register') #add sign in url ]` from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.auth import login, authenticate from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from datetime import date, timedelta from .models import Question, Answer from . import forms def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) … -
Django django-db-logger dos not add log to db
I try to add in to my Django project -> https://github.com/CiCiUi/django-db-logger. But for some reason, logger did not add records to db. setting.py INSTALLED_APPS = [ ..., 'django_db_logger', ] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['special'] } }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'myproject.custom': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', 'filters': ['special']}}} I can see new db table, and I can add new record in admin panel But here logger did not add new row. import logging db_logger = logging.getLogger('db') @csrf_exempt def read_sms_from_customer(request): if request.method == 'POST': db_logger.warning('info POST') -
How to use Syslog in Django REST framework?
I’m developing a Python Django REST API. Currently, I need to incorporate a logger to Syslog. Do I need to just define the logger and Syslog handler in the Settings.py? I’m relatively new to Django and using the Syslog protocol, so I appreciate any help and what Python modules to use. -
Plotly - Adjustbale bar plot
I'm creating a graph in Plotly as part of a Django project and the problem I have is that when I have only one value the size of the bar is incredibly big, obviously, as soon as I have more than one item, the bar starts to look nice, but when is only one value is really ugly, does anyone know how to fix this? def get_leads_data(request): c = Profile.objects.get(user=request.user) qs = Leads.objects.filter( agent_id=c,status='Open') df = read_frame(qs) graphs = [] graphs.append(go.Bar( x=df['company'], y=df['expected_revenue'], name='Estimated Revenue' )) layout={ 'title': 'Estimated Revenue by Company', 'xaxis_title':'Company', 'yaxis_title':'Revenue', 'height':500, 'width':640, } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') return render(request,'account/plot.html',{'plot_div':plot_div}) -
Filter a user data using contains in Django
I have this model that records data in slug. The user has a relation with the award model. What am trying to do is list all login user's awards slug field data in the contain filter so i can use it to filter user's data. NOTE : All the data in save in the SuccessfulTransactionHistory model field award is in slug format and SuccessfulTransactionHistory model has no foreign key relation to award and user models.py class Award(models.Model): admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) image = models.ImageField(upload_to='award_images') slug = models.SlugField(max_length=150, blank=True, null=True) about_the_award = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') price = models.DecimalField(max_digits=3, default='0.5', decimal_places=1, blank=True, null=True, validators = [MinValueValidator(0.1)]) bulk_voting = models.CharField(max_length=20, choices=BULK_VOTING, default='Closed') amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2, blank=True,) results_status = models.CharField(max_length=20, choices=RESULTS_PUBLISHED, default='private') starting_date = models.DateTimeField() ending_date = models.DateTimeField() date = models.DateTimeField(auto_now_add=True) class SuccessfulTransactionHistory(models.Model): nominee_name = models.CharField(max_length=120) transaction_id = models.CharField(max_length=120) award = models.CharField(max_length=120) amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) status = models.CharField(max_length=120, null=True, blank=True) phone = models.CharField(max_length=120, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) In my view.py success_list = SuccessfulTransactionHistory.objects.filter(award__contains=request.user.award.slug).order_by('-date') This is my error 'User' object has no attribute 'award' `` -
I need to do a delete and update based on status
I need to do a delete and update based on status. Here are models: class Purchases(TimeStampedModel): APROVADO = "AP" EM_VALIDACAO = "VA" STATUS_CHOICHES = ( (APROVADO, "Aprovado"), (EM_VALIDACAO, "Em validação"), ) values = models.DecimalField(decimal_places=2, max_digits=10, default=0) cpf = BRCPFField("CPF") status = models.CharField(max_length=20, choices=STATUS_CHOICHES, default=EM_VALIDACAO) I'm trying to do like this in my viewset: def get_queryset(self): qs = super().get_queryset() if self.action in ("update", "parcial_update", "delete"): qs.filter(Purchases.status=="VA") return qs However he is still letting edit the orders with the approved status. Can only be deleted or edited purchase with status "In validation" Can someone help me? -
Filter sub-groups in django querysets
Consider the following table: Column_A Column_B Column_C First UserA NULL Second UserB NULL Third UserC 1 Fourth UserA 1 Fifth UserB NULL Sixth UserB 2 Seventh UserC 2 I'd like to return all rows (Column_A, Column_B, Column_C) such that either: Column_C is NULL, or for every unique value in Column_C, return the first row with Column_B == UserA. If no such row exists, return the first row sorted by Column_B.time_created. For e.g. table.objects.magic_queryset(matching_user(UserA)) returns Column_A Column_B (FK) Column_C First UserA NULL Second UserB NULL Fourth UserA 1 Fifth UserB NULL Sixth UserB 2 I'm unable to write a queryset that will do the filtering efficiently in a single query. Appreciate any pointers. -
Django-limit_choices_to With ForeignKey based on different links
I am making a building manager website in Django. I have a page that is a DetailView for each building. On the DetailView page is a link to add a work task for repairs. On creating a work task I would like it to filter only for the building page that I came from. For example, from "building/1" page clicking the work task link would only allow you to see and select rooms in the building with pk = 1. views.py from django.shortcuts import render from .models import Building, Room, Task, Task_Note from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView # Create your views here. class BuildingList(ListView): model = Building template_name = "dorm/buildings.html" class BuildingDetail(DetailView): model = Building template_name = "dorm/building.html" class TaskAdd(CreateView): model = Task fields = ["time", "room", "work_request_id", "description"] template_name = "dorm/add_task.html" models.py from django.db import models from django.db.models.fields import DateTimeField, IntegerField, CharField, TextField from django.db.models.fields.related import ForeignKey import datetime from django.urls.base import reverse error = "Error" # Create your models here. class Building(models.Model): number = IntegerField(null = True, blank = True) @property def number_of_rooms(self): try: return Room.objects.filter(building = self).count() except: return error @property def number_of_active_tasks(self): x = 0 q = Task.objects.all() for … -
Prevent Delete on Default Image Django
I'm trying to set default image on nullable and blankable image field. I set the default image inside media/category like this: I've successfully set default image and working good by setting default on models.py like these: class Category(models.Model): ... image = models.ImageField(upload_to=upload_location, default='category/category.png', null=True, blank=True) ... def delete(self): if self.image != 'category/category.png': self.image.delete() super().delete() When adding data with blank image, the default image fill the default image field on the table: and it's shown as well like this: The problem comes when I delete the data it self, the image also being deleted. I have tried these code to prevent default image deletion, the data still remain, the default image still being deleted and the image field being blanked, like these: And I realize that these code (on models.py) only prevent data deletion, not the file/image deletion: ... def delete(self): if self.image != 'category/category.png': self.image.delete() super().delete() ... I want the default image still remain event the data being deleted, because it will be used when other someone add another data with blank image. How to prevent this default image deletion? Please help? -
Django Authentication to use both email and username
I've been nearly done with my django-react app with all the models, serializers, and APIs. But now I need to change the authentication method to also use email. class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(unique=True) # Notice there is no username field, because it is included in AbstractUser I've looked through some possible solutions but they involve using AbstractBaseUser while some other write a custom authentication backend that omits the username completely. This might break other views and frontend since we have been mainly using username. I still want to keep the username and use both username and email to authenticate. Is there any simple idea (preferably kept using AbstractUser) that I wouldn't have to make major change? -
How can I require that every checked box in ModelMultipleChoiceField has an integer associated in django?
Im working with a ModelMultipleChoiceField field in a form, and I would like to require that for every box that is checked, an integer is specified somewhere on the form. I other words, that the length of the checked boxes and itegers declared is the same. Is there any way to do this in Django? -
How to access python variables from ajax
In a Django web application, there is a for loop to feed a dropdown menu like below in index.html: <div class="form-control-lg"> <select class="form-control " id="booklist"> <option value="">Please select a book</option> {% for book in booklist %} <option value="{{ book }}"> book['name']</option> {% endfor %} </select> </div> This code simply adds all the books in booklist to a dropdown menu. I need to load the books from booklist but by ajax this time. I tried the below code but it does nothing, and the dropdown is empty. $(document).ready(function() { for(var book in booklist) { $('#booklist').append('<option value=book>'+ book['name'] +'</option>'); } } What is the way to get the result? -
Custom Export URL for export headers function
I have this in my resources: def export(self, queryset=None, *args, **kwargs): data = super().export(queryset, args, kwargs) return tablib.Dataset(headers=data.headers) It exports only the header fields for files. I want to bind it to a button only: but considering the custom export is inside my model resource, it is also applied to the export button. How do I add it only to the template button? Something like a new URL? -
Create model instance consisting of many-to-many field
I am trying to create a model instance using a post request, however one issue that I am having is that the model consists of a field which is of many-to-many. Now I am at a stage where I have got an array consisting of primary keys of the model instances (Modules) I wish to associate with the model I am trying to create (a Student). Please see my code below as I do not know where I am going wrong, after some basic research it seems I need to use a .set() method. The PUT['modules'] corresponds to array that consists of values [1,2,3,5]. def create_student(request): """API for creating a student""" if request.method == "POST": PUT = json.loads(request.body) student = Student(name=PUT['name'], join_date=PUT['join_date'], academic_year=PUT['academic_year'], modules=PUT['modules'] # THIS IS WHERE I NEED HELP ) student.save() return JsonResponse(student.to_dict()) return HttpResponseBadRequest("Invalid method") Thank you for your time. -
Create a list using values_list() in django
I'm trying to get the values of the objects saved in my database in a list and as integer, but the code I'm using is not working: if I try number[1:] I'm just gettin a blank variable in the html page and I keep getting errors telling me I'm still working with queryset and not list. number = list(Week.objects.filter(user=request.user).values_list()) How Can I get a simple list using .values_list()? -
Powershell file .ps1
I am stuck on a problem. I have a python application with a Django server and fronted in React. I run the Django and React server via a .ps1 file On the other hand, when I relaunch my application I open a new CMD window for Django and React I can't find a solution to kill the windows that are already open. code python3 to run file .ps1 {p = subprocess.run('powershell.exe -ExecutionPolicy RemoteSigned -file"entrypoint.ps1"', stdout=subprocess.PIPE, shell=True, timeout=30) } code powershell (.ps1) {Start-Process -FilePath 'venv/Scripts/python.exe' -ArgumentList "./manage.py runserver" Start-Process -FilePath 'venv/Scripts/python.exe' -ArgumentList "main.py" Start-Process 'npm' -ArgumentList "start" -WorkingDirectory "../prg_Frontend"}