Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A Python Image Capture (include Django if needed)
[ I'm trying to create a web image capture in python (Django if needed) that takes a photo and displays the record of the time capture with the picture taken, and arranges every picture taken in a chronological order. #here is the code of my camera capture # tried adding time capture with chronologically slideshow but I experienced major errors # I hope to hear some feedback (Thank you in advance) import cv2 as cv cam_port = 0 cam = cv.VideoCapture(cam_port) result, image = cam.read() if result: cv.imshow("freetry", image) cv.imwrite("freetry.png", image) cv.waitKey(0) cv.destroyWindow("freetry") else: print("No image") -
How to pass int from python flask back end to front end?
I have an int variable in my python backend id = 1 I want to pass this to my front end, so when the user clicks on a button like <button id = 'next'> <a href="view/<id>"> Where I have a pathway in my server.py @app.route('/view/<id>') def view(id): return render_template('view.html') How can I pass the id variable to my html file so I can link it via ahref? -
Django annotating fields with null values
I have list of Demand objects that have allocated field that would either be null or have a name (denoting this demand's allocation). I use annotations to count allocated/unallocated numbers per team: Demand.objects.filter(project=project).values('team').annotate( unallocated=Count('allocated', filter=Q(allocated__isnull=True)), allocated=Count('allocated', filter=Q(allocated__isnull=False)) ) What's weird is that the numbers for the allocated annotation come out right, but the numbers for the unallocated are always zero. For instance: list(Demand.objects.filter(project=project).values('allocated', 'team')) With the following outcome: [{'allocated': None, 'team': 'Design'}, {'allocated': None, 'team': 'Engineering'}, {'allocated': None, 'team': 'Engineering'}, {'allocated': None, 'team': 'Engineering'}, {'allocated': None, 'team': 'Delivery'}, {'allocated': None, 'team': 'Product'}] but the annotations with have just this: <QuerySet [{'team': 'Delivery', 'unallocated': 0, 'allocated': 0}, {'team': 'Design', 'unallocated': 0, 'allocated': 0}, {'team': 'Engineering', 'unallocated': 0, 'allocated': 0}, {'team': 'Product', 'unallocated': 0, 'allocated': 0}]> Am I doing it wrong or it may be a bug? -
How to use Pyunit test for my code than given below?
class CheckoutView (CreateView): template_name = "checkout.html" def checkout(request): if request.user.is_authenticated: customer = request.user cart, created = 'Cart'.objects.get_or_create(owner=customer, completed = False) cartitems = cart.cartitems_set.all() else: cart = [] cartitems = [] cart = {'cartquantity': 0} context = {'cart': cart, 'cartitems': cartitems} return render(request, 'cart/checkout.html', context) This is my code for checkout and I need unit test for this using pyunit test I tried but failed so I need help -
How to run function in background in Django view
I have Django project with one view. When i refresh page i want to call some function which is very complicated and take same time to execute. How and what is the best way to do it in backround? import time import psycopg2 from django.http import HttpResponse def long_time_function(sec): time.sleep(sec) print('DONE') def index(request): long_time_function(100) return HttpResponse('INDEX page') There is some built in solutions to do that or i need to run this function with thread or multiprocessing and set Deamon = True ? -
Django throws an integrity error while deleting an user
I have a project in which students can be added, when i try to delete the student who has been added django shows an error like this IntegrityError at /student/delete/1 FOREIGN KEY constraint failed Request Method: GET Request URL: http://127.0.0.1:8000/student/delete/1 Django Version: 3.1.1 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: C:\Users\name\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py, line 242, in _commit Python Executable: C:\Users\name\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.2 Python Path: ['C:\\Users\\name\\Desktop\\test-projects\\college-management-sytem_withstaffsentmailFinal', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages'] Server time: Mon, 18 Apr 2022 06:35:06 +0100 here is the django model class Student(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, null=True, blank=False) session = models.ForeignKey(Session, on_delete=models.DO_NOTHING, null=True) def __str__(self): return self.admin.last_name + ", " + self.admin.first_name class Staff(models.Model): course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, null=True, blank=False) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def __str__(self): return self.admin.last_name + " " + self.admin.first_name is there any way to fix this error ? -
Django Web-sockets
I have two pages in the web-application Tickets List and Ticket detail. On the ticket list page, I used datatable to show all data. I used Django channels and WebSockets for real-time updates. Now I want to implement functionality like this. Whenever someone added comments on the ticket detail page(I created a room using the unique ID of the ticket), I want to refresh my API-based data table on the ticket list page. Like -> User comment on detail page (comment consumer sends a response to detail page as well as broadcast an event to another channel to update the table). How can I implement this functionality? -
Need help Implementing a count, retrieve score from user, increment count, then find average implementation Django Python
Need help Implementing a count, retrieve score from user, increment count, then find average implementation Django Python CrystalPrototype_Django_WebsiteV1/prototype/HomeScreen/admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(Profile) admin.site.register(Element) admin.site.register(Edit) admin.site.register(TOS) """ This function allows for deletion of elementTexts and will update the auto ranking score after deletion. """ @admin.action(description = 'Delete elements for one TOS and reset weight') def deleteElementText(modeladmin, request, queryset): allElement = Element.objects.all() # allText = ElementText.objects.filter(tos = instance) # filter to get all elements in tos tosElements = allElement.filter(tos = queryset[0].tos) queryElements = queryset.values_list('element', flat = True) excluded = tosElements.exclude(id__in = queryElements) weights = excluded.values_list('weight', flat = True) # get absolute weight absTotal = sum(abs(w) for w in weights) regTotal = sum(weights) # get total total = absTotal + regTotal # set rating TOS.objects.filter(pk=queryset[0].tos.pk).update(weightRating = round((total / absTotal) * 100)) queryset.delete() class ElementTextAdmin(admin.ModelAdmin): actions = [deleteElementText] admin.site.register(ElementText, ElementTextAdmin) -
The word keyword “lazy”
Can anyone explain me the meaning of “lazy”. I can’t understand the meaning of the word “lazy” in Django. For example. In Lazy Translation Topic. These functions store a lazy reference to the string or lazy suffix I met that word many times in many programming languages but I can’t catch it. -
ModuleNotFoundError: No module named 'paystack.urls'
i'm trying to integrate payments subscription with Paystack using Django but it's throws me an error every time i do /manage.py runserver. the error ModuleNotFoundError: No module named 'paystack.urls' for the first time i try to install it with this github repo but it throws me an error pip install -e git+https://github.com/gbozee/pypaystack.git@master#egg=paystack the error ERROR: No matching distribution found for paystack (unavailable) I solved it using this: Future users should change egg=paystack to egg=pypaystack pip install -e git+https://github.com/gbozee/pypaystack.git@master#egg=pypaystack when i add this into my urls.py its throws me an error: urlpatterns = [ path('admin/', admin.site.urls), path('', include('myschool.urls')), path("paystack", include(('paystack.urls','paystack'),namespace='paystack')), ] the error ModuleNotFoundError: No module named 'paystack.urls' the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'myschool', #crispy Module 'crispy_forms', #Bootstrap Module 'crispy_bootstrap5', 'bootstrap5', 'storages', 'paystack' ] I'm I the first person having this error, because i do my research but i can't found it. -
Does not display image in button [duplicate]
I'm just learning how to use Django and HTML, and I've run into a problem that my image is not displayed on the button, instead I get an icon with a leaf that has a hill and a cloud, I don't understand what the error is, and I will be grateful if someone that will help me fix it. <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title></title> <style> </style> </head> <body> <button> <img src="images/i.jpg" alt="" style="position: relative; float: right; width: 320px; height: 320px"> </button> </body> </html> -
Best way to integrate Square Pay into a Django Web App?
So I've been working on a django e-commerce app, and to allow payment I planned on implementing some form of Square Payment API. When doing research for documentation on this, I couldn't find anything for django. Does anyone have an experience doing this or could anyone point me in the right direction? -
Site admin in django must have site name and password for login
I am making a site management program. 1. Site 2. Block and 3, Door No. the manager charges those sitting there every month. Administrator The site name and password will be entered to login and select the desired site. 1st site will be selected among the residents, the block will be selected according to the 2nd site According to the 3rd block, those who are seated after choosing the door number and password will enter. I couldn't find an example for this. It will always be entered via persons, this is via entity. thank you for your help -
How can i get select value in django html?
I have a modal form like this. I want to show a different form in front of the user according to the selected value here, but I can't get the selected value. How can I do that? <form> <div class="modal-body"> <div class="mb-3" id="modal-id" style="display: none;"> <label for="id-field" class="form-label">ID</label> <input type="text" id="id-field" class="form-control" placeholder="ID" readonly /> </div> <div class="mb-3"> <select class="form-select" aria-label="Disabled select example" name="typeselect"> <option value="1">Type 1</option> <option value="2">Type 2</option> <option value="3">Type 3 </option> <option value="4">Type 4 </option> </select> </div> {% if typeselect.val == "1" %} <div class="mb-3 typeforms typeone"> {{typeoneform}} </div> {% elif typeselect.val == "2" %} <div class="mb-3 typeforms typetwo"> {{typetwoform}} </div> {% elif typeselect.val == "3" %} <div class="mb-3 typeforms typethree"> {{typethreeform}} </div> {% elif typeselect.val == "4" %} <div class="mb-3 typeforms typefour"> {{typefourform}} </div> {% endif %} </div> <div class="modal-footer"> <div class="hstack gap-2 justify-content-end"> <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-success" id="add-btn">Add Customer</button> <button type="button" class="btn btn-success" id="edit-btn">Update</button> </div> </div> </form> I want to display according to option values from the forms I send to the html page. -
Importing CSV file with NULL values to Django Models
I'm importing csv files into Django models using a BaseCommand as such: load_data.py import csv from django.core.management import BaseCommand from api.models import Location, LocationData class Command(BaseCommand): help = "Load data from csv file into database" def add_arguments(self, parser): parser.add_argument('--path', type=str) def handle(self, *args, **kwargs): path = kwargs['path'] with open(path, 'rt') as f: reader = csv.reader(f, dialect="excel") next(reader, None) for row in reader: LocationData.objects.create( location = Location.objects.get(name=row[1]), date = row[2], hour = row[3], measurement = row[4] if row[4] else None ) The measurement column has empty/NULL values so I set up the models.py as such: class LocationData(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) date = models.DateField() hour = models.PositiveSmallIntegerField( validators=[ MinValueValidator(0), MaxValueValidator(24) ], ) measurement = models.FloatField(default=None, null=True, blank=True) def __str__(self): return self.name However, when I try to use the load_data.py which I have created, it resulted in an error: django.db.utils.IntegrityError: NOT NULL constraint failed: api_locationdata.measurement What I have tried: Deleting my migrations files and remigrating using python manage.py makemigrations but the error still occurs. What am I missing here? -
Django Error: Ensure this value has at most 10 characters (it has 321)
i have page file that i am update the details of the user. (Student User) and i create field for student: ID = models.CharField(max_length=10, null=True) and i also do clean_ID in StudentForm, but when i press the correct amount of characters i got the this error: Ensure this value has at most 10 characters (it has 321). you can see this in the photo down here. i don't understand how to fix the problem. VIEWS FILE class DetailsStudentView(View): def get(self,request, student_id): student = Student.objects.get(pk=student_id) userStudent = User.objects.get(pk=student_id) form_student = StudentForm(request.POST or None, instance=student) form_user = StudentUserUpdate(None,instance=userStudent) return render(request, "details.html",{'form_student':form_student, 'form_user':form_user}) def post(self,request,student_id): form_student = StudentForm(request.POST, request.FILES) if form_student.is_valid(): user = User.objects.get(pk=student_id) email = form_student.cleaned_data['email'] user.email = email user.save() student = Student.objects.get(pk=student_id) student.first_name = form_student.cleaned_data['first_name'] student.last_name = form_student.cleaned_data['last_name'] student.Phone = form_student.cleaned_data['Phone'] img = request.POST.get('imag_profile') if img != None: student.imag_profile = img student.ID = form_student.cleaned_data['ID'] student.save() return redirect('HomePage:home') userStudent = User.objects.get(pk=student_id) form_user = StudentUserUpdate(None,instance=userStudent) return render(request,'details.html',{'form_student':form_student, 'form_user':form_user}) Form FILE class StudentForm(forms.ModelForm): email = forms.EmailField(widget = forms.TextInput(attrs={ 'type':"text" ,'class': "bg-light form-control" })) class Meta(): model = Student fields = ('first_name','last_name','Phone','imag_profile','ID') widgets = { 'first_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }), 'last_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }), 'Phone': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }), 'ID': forms.TextInput(attrs={ … -
Django - how to access request body in a decorator?
I need to access the body of a request inside of a decorator, how can i do that? I'm calling the cache_page decorator from get in a class based view. In order to perform some logic, i need to access the URL of the request in the decorator. Here is my code: def custom_cache_page(timeout, *, cache=None, key_prefix=None): #print(request) return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=85, cache_alias=cache, key_prefix=key_prefix, ) class Sales_View(APIView): http_method_names = ['get'] @method_decorator(custom_cache_page(1.5)) def get(self, request, format=None): ... -
What the meaning of None . for test result [closed]
When testing in django For example self.assertEqual(response.status_code, 200) self.assertContains(response,"hello") self.assertContains(response,"my page") self.assertContains(response,"my list") self.assertContains(response,"article by") Mainly . is shown but sometimes None is shown. Either case, OK appears the last. such as Ran 8 tests in 3.413s OK -
Using the property Depth in Django Rest Framework serializers
When I use the Depth property in a serializer that brings the user model reference, it brings the user's password field, would there be any way to remove the password from the request response? my response: enter image description here -
I need to serialize & deserialize model class defination in django
I am quite new to django, I have class. from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) Now user is going to give me a JSON/XML file <item> <name>first_name</item_name> <type>char</type> </item> <item> <name>age</item_name> <type>char</type> </item> Based on the file, model class should change. How can I load model class from JSON/XML file? -
collect data from tables and display it on django-admin
I want to collect data from tables in Django and display them in the Django admin so, I tried to edit the admin.py where : @admin.register(models.Project) class ProjectAdmin(admin.ModelAdmin): but the ProjectAdmin can't take more than one argument so I can't get the data from the rest tables how can I do this? -
Custom user foreign key TypeError: Cannot create a consistent method resolution order (MRO)
How can I add foreign key with user type foreign key? Models have one to many relationship through foreign keys. Django docs show that I can add a model and reference through a foreign key. I want to add a user type: admin, staff, and guest. Then add permissions: up to delete, up to edit, and up to read respectively. python3 manage.py runserver TypeError: Cannot create a consistent method resolution order (MRO) for bases Model, HistoricalRecords, SoftDeletableModel, TimeStampedModel from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models import CharField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from model_utils.models import SoftDeletableModel, TimeStampedModel from simple_history.models import HistoricalRecords class User_Type(models.Model, HistoricalRecords, SoftDeletableModel, TimeStampedModel): name = models.CharField(max_length=100) class User(AbstractUser): """ Default custom user model for project. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore user_type = models.ForeignKey(User_Type, on_delete=models.CASCADE) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) -
How can I add a related field to serializer instance?
I have the following model + serializer where I send a post request to create a new model instance. The user sending the post request is related to a Company which I want to pass as related model instance to the serializer. But how to actually define this instance and attach it to the serializer instance within the post view? # views.py class OfferList(APIView): """ List all Offers or create a new Offer related to the authenticated user """ def get(self, request): offers = Offer.objects.filter(company__userprofile__user=request.user) serializer = OfferSerializer(offers, many=True) return Response(serializer.data) def post(self, request): serializer = OfferSerializer(data=request.data) # Add related company instance company = Company.objects.get(userprofile__user=request.user) serializer['company'] = company # this doesn't work if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # offer/models.py class Offer(models.Model): """ A table to store Offer instances """ # Relations company = models.ForeignKey(Company, on_delete=models.CASCADE) .. # serializers.py class OfferSerializer(serializers.ModelSerializer): class Meta: model = Offer fields = '__all__' user/models.py class UserProfile(models.Model): """ Extends Base User via 1-1 for profile information """ # Relations user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) -
django.urls.exceptions.NoReverseMatch - django-smart-selects
I am trying to implement django-smart-selects in my project but get errors when trying to add a record in my model from django admin. Here's my code: models.py class PricingConfiguration(CreateUpdateMixin): name = models.CharField(max_length=50) description = models.CharField(max_length=250) appointent_category = models.ForeignKey( AppointmentCategory, null=True, blank=True, related_name="pricing_appointment_category", on_delete=models.CASCADE, ) speciality = models.ForeignKey( Speciality, null=True, blank=True, related_name="pricing_speciality", on_delete=models.CASCADE, ) sub_speciality = ChainedForeignKey( SubSpeciality, chained_field="speciality", chained_model_field="speciality", show_all=False, auto_choose=True, sort=True, null=True, blank=True, ) urls.py from django.urls import include, path, re_path from django.contrib import admin from rest_framework.routers import DefaultRouter app_name = "configuration" urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^chaining/", include("smart_selects.urls")), ] Errors: django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'chained_filter' not found. 'chained_filter' is not a valid view function or pattern name. Traceback (most recent call last) File "/usr/local/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 149, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.9/site-packages/django_extensions/management/technical_response.py", line 40, in null_technical_500_response raise exc_value.with_traceback(tb) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/usr/local/lib/python3.9/site-packages/django/template/response.py", … -
pytest-django RuntimeError : Database access not allowed,
I'm testing my django application using pytest / pytest-django. my urls.py file contains from django.urls import include, path from . import views urlpatterns = [ path('', include('django.contrib.auth.urls')), path('users/', views.users, name='users'), path('add-user/', views.add_new_user, name='add_new_user'), ] in my tests.py file, I have import pytest from django import urls def test_users_url_resolves_to_users_view(client): url = urls.reverse('users') resp = client.get(url) assert resp.status_code == 200 I get RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. when i run this.