Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saved task_id in database does not match Info from celery worker
I'm currently working on an application, that allows queueing of several tasks which should be allowed to be cancelled. For that to be possible, my task-model has a field for saving the task_id of the worker, and in Django, the user is presented with a list of the tasks and an option to stop individual tasks. The issue I am having is that the task_ids stored away in the database and the task_ids mentioned in the info line from the worker do not match until the worker has finished his task. i.e. the worker returns [2021-07-22 16:35:25,652: INFO/MainProcess] Received task: dop.tasks.execute_report[7490537f-90dd-4966-bff7-63d5461a92ff] but in the database, there's a different task_id saved until the worker returns a successful completion of the task. This prevents me from revoking any of the displayed tasks in the queue, because they have the wrong task_id associated with them. my code is below: def create_report(request, slug): ... # create report report = Report.objects.create( reportDefinition=reportDefinition, user=request.user ) ... transaction.on_commit( lambda: execute_report.delay( user_id=request.user.id, report_id=report.id, command_string=reportDefinition.get_command(), db_name=request.user.basex_prefix, resource_names=report.get_active_user_resource_names(), ) ) ... execute_report looks like this: @celery_app.task(bind=True) def execute_report( self, user_id, report_id, command_string, db_name, resource_names: list ): start_time = datetime.now() # get objects user = get_user_model().objects.get(id=user_id) report = Report.objects.get(id=report_id) report.task_id = … -
Django in_bulk() raising error with distinct()
I have the following QuerySet: MyModel.objects .order_by("foreign_key_id") .distinct("foreign_key_id") .in_bulk(field_name="foreign_key_id") foreign_key_id is not unique on MyModel but given the use of distinct should be unique within the QuerySet. However when this runs the following error is raised: "ValueError: in_bulk()'s field_name must be a unique field but 'foreign_key_id' isn't." According to the Django docs on in_bulk here it should be possible to use in_bulk with distinct in this way. The ability was added to Django in response to this issue ticket here. What do I need to change here to make this work? I'm using Django3.1 with Postgres11. -
DATETIME_FORMAT setting for my customized datetime field
I wrote a customized datetime field Now i want to add DATETIME_FORMAT setting for this customized field? -
How to set is_staff to True in Django when a user is created with a specific group selected
How would I automatically set is_staff to True when creating a new user in the Django admin when they have a specific group selected? -
Uploading image to Django database raises TypeError
I am having trouble uploading image paths into my Django database. When I try to add data without the eventImage field, it works fine. But when I upload anything to the eventImage field, it says: TypeError at /admin/events/event/add/ expected str, bytes or os.PathLike object, not tuple Request Method: POST Request URL: http://127.0.0.1:8000/admin/events/event/add/ Django Version: 3.2.5 Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not tuple Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/posixpath.py, line 374, in abspath I've put relevant code snippets below. Please let me know what I'm doing wrong! In my settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'events', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] In my events.py file: from django.db import models class Event(models.Model): venueName = models.TextField() artistName = models.TextField() eventName = models.TextField() time = models.TextField() date = models.TextField() length = models.TextField() description = models.TextField() eventImage = models.ImageField( upload_to='media/', blank=True, null=True) def __str__(self): return self.eventName Any help would be hugely appreciated! -
how to solve Django url patterns not working
I added path('int:pk/',...) in urls.py and access 'http://127.0.0.1:8000/blog/1' the result was 'page not found(404)' Using the URLconf defined in doit.urls, Django tried these URL patterns, in this order: blog <int:pk>/ blog admin/ The current path, blog/1, didn’t match any of these. also, I made 3 pk contents please help me I suffered for a long time. urls.py from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.PostDetail.as_view()), path('', views.PostList.as_view()), ] models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() created_at = models.DateTimeField() def __str__(self): return f'[{self.pk}]{self.title}' views.py from django.views.generic import ListView, DetailView from .models import Post class PostList(ListView): model = Post ordering = '-pk' class PostDetail(DetailView): model = Post post_list.html <!DOCTYPE html> <html lang = "ko"> <head> <meta charset="UTF-8"> <title>Blog</title> </head> <body> <h1>Blog</h1> {% for p in post_list %} <hr/> <h2> {{ p.title }} </h2> <p> {{ p.content }}</p> <h4> {{ p.created_at }} </h4> {% endfor %} </body> </html> post_detail.html <!DOCTYPE html> <html lang="ko"> <head> <meta charset = "UTF-8"> <title> {{ post.title }} - Blog </title> </head> <body> <nav> <a href="/blog/">Blog</a> </nav> <h1> {{ post.title }} </h1> <h4> {{ post.created_at }} </h4> <p> {{ post.content }} </p> <hr/> <h3> ... </h3> </body> </html> -
Python: Object is missing attributes
Im working with the following object (from PyGuacamole: https://pypi.org/project/pyguacamole/0.7/): class GuacamoleClient(object): """Guacamole Client class.""" def __init__(self, host, port, timeout=20, debug=False, logger=None): """ Guacamole Client class. This class can handle communication with guacd server. :param host: guacd server host. :param port: guacd server port. :param timeout: socket connection timeout. :param debug: if True, default logger will switch to Debug level. """ self.host = host self.port = port self.timeout = timeout self._client = None # handshake established? self.connected = False # Receiving buffer self._buffer = bytearray() # Client ID self._id = None self.logger = guac_logger if logger: self.logger = logger if debug: self.logger.setLevel(logging.DEBUG) @property def client(self): """ Socket connection. """ if not self._client: self._client = socket.create_connection( (self.host, self.port), self.timeout) self.logger.info('Client connected with guacd server (%s, %s, %s)' % (self.host, self.port, self.timeout)) return self._client @property def id(self): """Return client id""" return self._id def close(self): """ Terminate connection with Guacamole guacd server. """ self.client.close() self._client = None self.connected = False self.logger.info('Connection closed.') def receive(self): """ Receive instructions from Guacamole guacd server. """ start = 0 while True: idx = self._buffer.find(INST_TERM.encode(), start) if idx != -1: # instruction was fully received! line = self._buffer[:idx + 1].decode() self._buffer = self._buffer[idx + 1:] self.logger.debug('Received instruction: %s' % … -
Django is loading static files but not image that are stored from backend in production
As the title says, after I changed DEBUG to False, the image that is uploaded from the admin panel are not loading. However, other static files like css files and images that are loaded only from HTML side are rendered properly. -
Django - Sum annotation adding group by id to clause
The following queryset subquery = aggregate_table.objects.filter( item__parent__name=OuterRef(dimension) ).annotate( aggregate_value=Sum(aggregation_field) ).order_by( 'item__parent__name' ).values('aggregate_value') queryset = queryset.annotate(aggregate_value=Subquery(subquery)) produces SQL that groups by both the name (supplied by the order_by) and by the id. SELECT SUM(U0."data") AS "aggregate_value" FROM "aggregate_table" U0 INNER JOIN "item" U1 ON (U0."item_id" = U1."id") INNER JOIN "parent" U2 ON (U1."parent_id" = U2."id") WHERE U2."name" = (T12."name") GROUP BY U0."id", U2."name" ORDER BY U2."name" ASC the ID produces incorrect results and instead of summing and returning 1 row with say 100 as the sum'd value, it returns 100 rows with 1 as the sum'd value. any ideas on how to remove the u0.id from the group by clause? -
display a spinner during data processing
I have written a django application for some data processing. In some cases, there could several minutes to wait until the processing is done. So I'd like to display a spinner on the page as soon as the user clicked on "excute" and all along the processing until the page is refreshed to display the results... I followed a tutorial (here) where I could set things up on the application and show the spinner when the page is loading. But this is not exactly what I'm looking for. The follwing JS code is coming from the video and shows the spinner until the page is loaded: const spinnerbox = document.getElementById('spinner-box') //console.log(spinnerbox) $.ajax({ type: 'GET', url: '/', success : function(response){ spinnerbox.classList.add('not-visible') console.log('response', response) }, error : function(error){ console.log(error) } }) I guess I need to modify this code, type should be 'POST' but I don't know what to add next to the script. Thanks for any help! Sébastien -
Django testing image
How to create image for test? I tried simpleUploadFile in different ways and it didn't work. I need test my endpoint. but have problem in image field My test: def setUp(self): self.card = Card.objects.create( title='card titulo', image='', amount=0, description='descricao', id= 1 ) self.user = User.objects.create_user( username='test', email='', password='have_senha' ) self.referral = Referral.objects.create(refferal_user=self.user, reffered_user=self.user) self.redeem = Redeem.objects.create(card=self.card,user=self.user) self.factory = RequestFactory() self.image = SimpleUploadedFile('donwload.jpeg', b'') def test_new_card(self): data ={ "title": "teste", "image": self.image, "amount": 0, "description": "TESET", "id": 24 } client = APIClient() client.force_authenticate(user=self.user) response = client.post('/card', data, format='json') print(response.json()) -
AWS EC2 and OpenCV with UDP consumer
I have two EC2 A That grabs the video feed from Amazon Kinesis Video to send it into via UDP to B B the consumer which it will grab the UDP feed from the A While debugging my opencv not grabbing the UDP feed, I suspect something is wrong with ffpmeg, so I am going to make sure that ffplay can read packets sent from A. Now when I try to read udp packets with ffplay {adress-ip-with-port}I have the following error : Could not initialize SDL - No available video device (Did you set the DISPLAY variable?) How do I fix this one since there is no display on EC2. Also if it can help, this is my code for the consumer part Create your views here. from django.http import HttpResponse from django.template import loader from django.shortcuts import render # from .models import Vehicule import cv2 import threading from django.views.decorators import gzip from django.http import StreamingHttpResponse @gzip.gzip_page def webcam(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, 'vebcam.html') #capture video class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture('udp://172.31.57.243:55055', cv2.CAP_FFMPEG) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) … -
Django Views: Display and access data from csv file of users to create them
Currently I'm doing this via a management command that takes a csv, iterates through to create users. I'd like to do this via a view form where rows are populated by the data so eventually I can look and modify if typos in rows before importing. Here is an example of the csv. code: password = 'tempass12345' with open(file_path, mode='r', encoding='utf8') as csv_file: data = csv.reader(csv_file) for row in list(data)[1:]: first_name, last_name, email = row user = User.objects.create( username=email, first_name=first_name, last_name=last_name, email=email, password=password ) # csv file First Name,Last Name,Email Roy ,Cot, rcot@xyz.com What's the best django approach to doing this? The file will not be stored. -
How can assign foreign key of Abstrat User Model in django
When i submit the button it show the error "Vendor_Profile.auth_user" must be a "Auth_User" instance. Auth_User is an Abstract User Model.py class Auth_User(AbstractUser): is_vendor = models.BooleanField(default=False) class Vendor_Profile(models.Model): auth_user = models.ForeignKey(Auth_User, on_delete=models.CASCADE) name = models.CharField(max_length=50) View.py try: vendor = Vendor_Profile( auth_user=request.session['USER_ID'], name=self.request.POST.get('name') ) vendor.save() return render(request, 'home.html') except Exception as e: return HttpResponse('failed{}'.format(e)) -
TypeError: addProductPaymentResponse() missing 1 required positional argument: 'paymentForOrderID'
I want to restrict post request if similar str(number) in paymentForOrderID is already exists in ProductPayment model, #model.py class ProductPayment(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, editable=False,verbose_name="Payment Made By",) paymentForOrderID = models.CharField(max_length=200, null=True, blank=True, verbose_name="Payment For Order ID") paymentMethodUsed = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Method Used") aproxTimeAndDateOfPayment = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Approx Date/Time Of Payment") totalAmountPaid = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Amount Paid") paymentDetails = models.TextField(null=True, blank=True,editable=False,verbose_name="Details") createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False, verbose_name="Entry ID") def __str__(self): return str(self.createdAt) I'm trying this way.... #views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def addProductPaymentResponse(request, paymentForOrderID): user = request.user data = request.data response_list = ProductPayment.objects.all() alreadyExists = response_list.objects.filter(paymentForOrderID=paymentForOrderID).exists() if alreadyExists: content = {'detail': 'Sorry Response has already been recieved'} return Response(content, status=status.HTTP_400_BAD_REQUEST) else: product = ProductPayment.objects.create( user=user, paymentForOrderID=data['paymentForOrderID'], paymentMethodUsed=data['paymentMethodUsed'], aproxTimeAndDateOfPayment=data['aproxTimeAndDateOfPayment'], totalAmountPaid=data['totalAmountPaid'], paymentDetails=data['paymentDetails'], ) return Response('Payment Response added') On hitting post action from frontend I get this error TypeError: addProductPaymentResponse() missing 1 required positional argument: 'paymentForOrderID' [22/Jul/2021 18:13:01] "POST /api/payments/product-payment-add-response/ HTTP/1.1" 500 102170 So kindly highlight where is the mistake and how can I fix that -
How to use global variables in django
I use django_rest_framework. I need parse huge xml file then find some data. Parse xml on get call is bad idea because is too long time. I try once a 3 minute parse it and save parsed object to global variable. But I'm not sure about it work correctly. Example: class MyView(APIView): catalog = None parse_time = 0 @classmethod def get_respect_catalog(cls): if time.time() - cls.parse_time > 300: cls.catalog = parse_xml() cls.parse_time = time.time() return cls.catalog def get(self, request): vals = catalog.xpath('tag/text()') # here i find some tag ... return response I sent several requests but many time variable parse_time had value 0. As if class MyView recreate sometimes and class variables "catalog" and "parse_method" resets to init values. I think it because uwsgi have many workers and many interprets. May be exists way for using global variables in django. P.S. I know for my case I need use database. But I want use global vars. -
adding items from products to card (Django-views-codes)
I am fairly new and working on a project and just want to add products to the basket and I'm getting this Error: "AttributeError at /productapp/basket/add/Django Tutorial/ Manager isn't accessible via Basket instances" I think the problem is the view code but don't know how to fix it. Can anybody help me? Thank You. Models: class Products(models.Model): products_name = models.CharField(max_length=30) pub_date = models.DateTimeField(auto_now=True) price = models.CharField(max_length=10) note = models.CharField(max_length=200) inventory = models.IntegerField(default=1) product_pic = models.ImageField(upload_to ='images/', default='images/broken/broken.png') def __str__(self): if (self.inventory<=0): return self.products_name + ' (Out of Stock)' return self.products_name class Basket(models.Model): products = models.ForeignKey(Products, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) amount = models.IntegerField(default=1) def __str__(self): return str(self.products) urls: app_name = 'productapp' urlpatterns = [ path('products/', views.products, name='products'), path('basket/', views.basket, name ='basket'), path('', views.home, name='home'), path('basket/add/<str:name>/', views.addtobasket, name='addtobasket'), ] views: def products(request): products_list = Products.objects.order_by('-pub_date') context = {'products_list': products_list} return render(request, 'productapp/products.html', context) def basket(request): basket_list = Basket.objects.order_by('-pub_date') context = {'basket_list': basket_list} return render(request, 'productapp/basket.html', context) def addtobasket(request, name): basket = Basket.objects.all()[0] product = Products.objects.get(products_name=name) basket.objects.add(products=product) return HttpResponseRedirect(reverse("basket")) Html: <body> <section class="products_section"> <h1 class="products_section_h1" style="color: #ffffff;">Our Tutorials</h1> {% block content %} {% if products_list %} {% for product in products_list %} <div class="products"> <div class="product"> <img src="../{{product.product_pic}}" style="width:200px; border: 2px solid #051218;"> … -
Django object creation happens infinitely
I have a class connectTo defined in myclass.py which will connect to lets say a TCP socket and importing the same in views.py. I wrote an ajax to call the views function which creates object for my class as below views.py from myclasses import connectTo def connect(request): connectTo() return JsonResponse("Success") but the problem is as long as django server is running the connection to the TCP socket is happening. It should happen only once when connect in views.py is called instead it keeps on creating object and establishes TCP connection and stops if I close django server. -
Django admin inlines - how to remove empty records from create/update form
I'm using StackedInline to add related objects in my Django admin form (relation is one to many). The problem is that it renders three empty inline forms by default when creating new object like in this example: What I want is to render only "Add" button because the related objects are so rare that most of the records don't have these (or at least single empty record) and my related object is much larger than the one on the pictures. It should look something like this example: How can I do this? -
How to redirect from a view in one app to a view in another app?
I have two apps members and ctr member app handles the login, registration and logout and ctr will handle some admin stuff in page named foradmin.html. I want to redirect to from member/views.py to ctr/views.py after the login has been done. Please tell me how can I do it member/views.py def loginpage(request): if user is not None: login(request, user) if user.is_superuser: return redirect('foradmin') #this foradmin page is included in ctr urls @login_required(login_url='login') @allowed_user(allowed_roles=['admin']) def foradmin(request): return render(request, 'foradmin.html') #I want to redirect this ctr app this is also written in ctr/views.py member/urls.py urlpatterns=[ path('register',views.registerpage, name='register'), path('login', views.loginpage, name='login'), path('logout', views.logoutUser, name='logout'), path('ricktest', views.ricktest, name='ricktest'), path('forstaff', views.forstaff, name="forstaff"), path('foradmin', views.foradmin, name="foradmin"), ] ctr/views.py @login_required(login_url='login') @allowed_user(allowed_roles=['admin']) def foradmin(request): return render(request, 'foradmin.html') ctr/urls.py urlpatterns=[ path('foradmin', views.foradmin, name="foradmin"), ] Final Note: I want that after the conditions of login are met this should redirect to ctr app -
How to implement Biometric Authentication in a ReactJS Web Application
I currently have a web application set up using ReactJS for the front-end, Django and Apache Guacamole for the back-end and MariaDB for the database. I also have a Secugen Hamster Plus Fingerprint Scanner which when plugged in to the computer, will be used for user authentication on the login page of the web application (using ReactJS). Does anyone know how I can go about writing code to retrieve fingerprint images from the database to compare them with the user-inputted fingerprint when he attempts to login? I have been unsuccessful in finding any working examples or documentation for reference on the Internet. -
How to get type of object if value of ForeignKey is None?
I have got a basic foreign key table structure class Category(models.Model): id_pk = models.AutoField(primary_key=True) label = models.CharField(unique=True, max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'category' and class PartProperty(models.Model): id_pk = models.AutoField(primary_key=True) category = models.ForeignKey(Category, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'part_property' If a row inside PartProperty has a Category object I can access this object via e.g. part_property = PartProperty.objects.select_related().filter(id_pk=part_property_id) and part_property[0].catogory respectively dynamically via part_property .values(*(self.__COLUMN_NAMES))[0]['self.__COLUMN_NAMES[i]] and set a new value and save the table where the foreign key points to. But if part_property[0].catogory is None I have no object type for creating an object of the foreign key table. Is it possible to get the object type dynamically from the PartProperty / PartProperty model? -
Python Django refusing to create user and telling me to download Pillow (again)
I'm trying to create a new superuser within my admin files, and I receive this error. PS C:\Users\sefni\Desktop\AtlasStore> py manage.py createsuperuser SystemCheckError: System check identified some issues: ERRORS: store.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Thing is I have already installed pillow before making making migrations to my data, it worked successfully since I have my 0001_initial.py. This is the error given when I try to install pillow again. PS C:\Users\sefni\Desktop\AtlasStore> pip install pillow pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pip install pillow + ~~~ + CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Content of my admin files: from django.contrib import admin from .models import Category, Product @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'slug', 'price', 'in_stock', 'created', 'updated'] list_filter = ['in_stock', 'is_active'] list_editable = ['price', 'in_stock'] prepopulated_fields = {'slug': ('title',)} -
How can set the boolean value in django
I am trying to get set the boolean value True when the checkbox is selected but when i select it show the error failed["“>” value must be either True or False."] and also it show the error when i set the password object have no strip fucntion Model/py from django.db import models from django.contrib.auth.models import AbstractUser class Auth_User(AbstractUser): is_vendor = models.BooleanField(default=False) View.py class Sign_up(TemplateView): template_name = 'Sign-up.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: data = self.request.POST.get user = Auth_User( username=data, email=data, is_vendor=data ) user.set_password(data('password').strip()) user.save() return render(request, 'home.html') except Exception as e: return HttpResponse('failed{}'.format(e)) Html <label for="is_vendor">is_vendor <input type="checkbox" name="is_vendor"> </label><br> -
django: Handling two values in one field
Intro: I have time series data that need to be stored in with the date_created, the its value. Also, each list of values will have a column where I define some constants. Example, oxygen level can be today == 95, later its goes to 80 which is bad things and I need to monitor that. My Models: class Column(models.Model): max = models.PositiveIntegerField(max_length=500, null=True, blank=True) min = models.PositiveIntegerField(max_length=500, null=True, blank=True) limit = models.PositiveIntegerField(max_length=500, null=True, blank=True, help_text='if {absolute(latest measurement - the new measurement) == limit} then you may need to be alerted') name = models.CharField(max_length=500) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='statistics', null=True, on_delete=models.SET_NULL) class Value(models.Model): object_id = models.CharField(max_length=20) name = models.CharField(max_length=50, blank=True) column = models.ForeignKey(Column, related_name='values', on_delete=models.CASCADE) field_value = models.CharField(max_length=500) field_name = models.CharField(max_length=500) seen_by = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='seen_by_users', blank=True) date_created = models.DateTimeField(auto_now=True, blank=True, null=True) problem When I deal with blood pressure that should have a field_value like 120/80 which is why I am using CharField instead of IntigerField. Also, separating them cause many complications like # 1. I should create two value # Note I already planned to do it this way but I need more ideas please. Value.objects.create(field_name='Diastole', field_value=80) Value.objects.create(field_name='Systole', field_value=120) # 2. in the view I should do `anoniation` or `aggregation` on values …