Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load editorJs scripts integrated with django after an ajax call?
I am using editorJs for my description field as follows: epic_description = EditorJsField( editorjs_config={ "tools": { "Image": { "config": { "endpoints": { "byFile": "/imageUlaod/", "byUrl": "/imageUlaod/", }, "additionalRequestHeader": [ {"content-Type": "multipart/form-data"} ], } }, "Attaches": { "config": { "endpoint": "/fileUPload/", } }, } }, blank=True, null=True, ) But I also call this form of this field via ajax to load it. And it turns out that the script for the editorJs is not loaded at all. When I looked to my console it uses the cdn url https://cdn.jsdelivr.net/sm/jsdelivr-separator.js. Now I have no idea how to solve this issue since I do not know what script to load in the first place I check at the url to see if I can download the js file. Eiih nothing. Any help would be appreciated highly. -
'WSGIRequest' object has no attribute 'get'... API link from google
I am trying to use the Books APIs from google to import books to the website and save them in the database. Unfortunately, I have a problem with the get method and I don't know where the problem is. I get an error like in the subject. search_url = "https://www.googleapis.com/books/v1/volumes?q=search+terms" params = { 'q': 'Hobbit', 'key': settings.BOOK_DATA_API_KEY } r = request.get(search_url, params=params) print(r.text) return render(request, "BookApp/book_import.html")``` -
Trouble starting Django project w/o errors
This is the original code in urls.py. Similarly, errors in view.py, and the app url.py files automatically appear whenever I start a project in django (3.2.8). I've just begun coding, no one I've asked can answer why. HELP! from django.contrib import admin from django.urls import path -
conexion django con base de datos 4Dimension
quiero conectarme con la base de datos 4Dimension desde django. alguien tiene alguna idea de como hacerlo en solo lectura? -
stale token even for first time user Djoser and DRF
the newly registered user get email for activation . He clicks on the links and move to an activation page .then he clicks on verify button which take uid and token from the link and post it to auth/users/activation/ and then gets the response stale token for the given user no matter how fast he click on the link on verify link . result is same. I am using djoser for activation and all user related stuff.and redux in the frontend for api calls and also the React as frontend here is my settings.py: DJOSER = { 'LOGIN_FIELD': 'email', 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': ['https://negoziohub.herokuapp.com/google', 'http://127.0.0.1:8000/facebook'], 'SERIALIZERS': { 'user_create': 'base.serializers.UserSerializer', 'user': 'base.serializers.UserSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } here is userAction.js: export const activate = (uid, token) => async (dispatch) => { try { dispatch({ type: USER_ACTIVATE_REQUEST }) const config = { headers: { 'Content-type': 'application/json', } } const body = JSON.stringify({ uid, token }); const { data } = await axios.post(`/auth/users/activation/`, body, config ) dispatch({ type: USER_ACTIVATE_SUCCESS, payload: data }) // dispatch(login()) localStorage.setItem('userInfo', JSON.stringify(data)) } catch (error) { dispatch({ type: USER_ACTIVATE_FAIL, payload: error.response && error.response.data.detail ? … -
Upgrade Django with incompatible migrations
I'm tasked with upgrading the Django version for a project that currently uses Django 2.2.24. It contains a model (with existing migrations) that looks roughly like this: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) type = models.ForeignKey(MembershipType, on_delete=None) Starting with Django 3.0, on_delete=None causes an error since on_delete is supposed to be a callable. In order to avoid the error, both the model and the existing migrations have to be changed. By itself, it's not an issue to change the model like this: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) type = models.ForeignKey(MembershipType, on_delete=models.SET_NULL, null=True) But existing databases are not yet aware that the corresponding field can be nullable, so a new migration is required for that. The best way I currently see to do this is the following: change the model create&apply a migration using Django 2.2.24 change the old migrations manually Is there a more elegant way to solve this issue? -
How can I test delete view in Django app?
I want to test my View but I have problem with my delete function. class AnimalView(APIView): def delete(self, request, format = None): id = int(request.GET.get('id')) try: animal = Animal.objects.get(id=id) except: return Response(status=status.HTTP_404_NOT_FOUND) animal.delete() return Response(status=status.HTTP_204_NO_CONTENT) This is my model: class Animal(models.Model): name = models.CharField(unique=True, max_length=30, blank=False, null=False) class Meta: managed = True db_table = 'animal' ordering = ['name'] def __str__(self): return str(self.name) and this is the test that I'm trying to make: class TestURL(TestCase): def setUp(self): self.client = Client() def test_animal_delete(self): animal = Animal.objects.create(name = 'TestAnimal') response = self.client.delete(reverse("category_animal"), json.dumps({'id' : animal.id})) self.assertEqual(status.HTTP_204_NO_CONTENT,response.status_code ) But I'm getting a TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Can you please help me with my test? -
Use template date filters in custom template tag?
I want to use Django template date filters inside a custom template tag. Is that possible? My end goal is to be able to use it like this: {{parcel.pickup_dates|delivery_dates_formating}} Problem is, that "pickup_dates" can be array of 1 or 2 or 3 elements. My desired output is: "Sunday, 21 September" if one element, "Satardau - Sunday, 21-22 September" if 2 elements, "Friday - Sunday, 20-22 September" if 3 elements, Currenly my temlpate tag looks like this: def delivery_dates_formating(value): if len(value) == 1: return [value[0]] if len(value) == 2: return [value[0], value[1]] if len(value) == 3: return [value[0], value[2]] And in template I used to use something like: {{parcel.delivery_date|date:'E j, l'|capfirst}} I woul like to use django tempaltes date filtes, as it handels localisation. Is that possible? -
Where do Django's Field's "default" and test's "client" parameters come from?
If you search for the parameters of a Field (e.g. IntergField) in Django through from django.db import models dir(models.IntegerField) you get 'default_error_messages', 'default_validators', 'unique', 'validate', 'validators', etc, but not "default" itself, although it's commonly used, as in class Choice(models.Model): ... votes = models.IntegerField(default=0) Same thing with "client". The docs say TestCase "comes with its own client". In this snippet from Django's docs, this client is explored class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) but you can't find it through from django.test import TestCase dir(django.test.TestCase) or even dir(django.test.TestCase.client_class) I'm asking where they come from, but also how to search for these "hidden" parameters, methods, etc. -
Django call SOAP API
I made a CRM and now the company wants to set up their API, but it's a SOAP API who uses XML and after a little research here in Stack, some people said to use zeep, and didn't work. I'm trying first from a separate file to put in the CRM later (maybe not the best idea) but I think I'm doing wrong/more than I need to. Is it right to do this way or is there a better way ? from zeep import Client client = Client('httsp://company.com/?wsdl') element1 = client.get_element('ns0:E1') element2 = client.get_element('ns1:E2') element3 = client.get_element('ns2:E3') element4 = client.get_element('ns3:E4') element5 = client.get_element('ns4:E5') element6 = client.get_element('ns5:E6') element7 = client.get_element('ns6:E7') element8 = client.get_element('ns7:E8') element9 = client.get_element('ns8:E9') obj1 = element1(E1 = 'A') obj2 = element2(E2 = 'B') ... obj9 = element9(E9 = 'I') header_value = header(username='user', password='pass') client.service.Companymethod(_soapheader={heaeder_value, obj1, obj2, ... obj9}) XML: <definitions targetNamespace="http://X/soap/X"> <types> <xsd:schema targetNamespace="http://X/soap/X"> <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/> <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/"/> <xsd:complexType name="Companymethod"> <xsd:all> <xsd:element name="YRequest" type="tns:YRequest" minOccurs="1"/> </xsd:all> </xsd:complexType> <xsd:complexType name="YRequest"> <xsd:all> <xsd:element name="E1" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E2" type="xsd:nonNegativeInteger" minOccurs="1" maxOccurs="1"/> <xsd:element name="E3" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E4" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E5" type="xsd:nonNegativeInteger" minOccurs="1" maxOccurs="1"/> <xsd:element name="E6" type="xsd:boolean" minOccurs="0" maxOccurs="1"/> <xsd:element name="E7" type="xsd:nonNegativeInteger" minOccurs="0" maxOccurs="1"/> <xsd:element name="E8" type="xsd:nonNegativeInteger" … -
Custom User Model Django Error , No such table
Models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser phone = models.IntegerField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin objects = UserManager() Settings.py AUTH_USER_MODEL = 'Accounts.User' Error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: Accounts_user I have created a Model User, but when I tried to create a superuser, i got an error, that table does not exist, I have tried makemigrations and migrate command multiple times, but nothing seems to solve the issue i can't even open the table even in the admin pannel, can someone help me solve this issue -
Django implicit field naming for class with query expression - how does it work?
Simplified example of what I wrote today: class Grandparent(models.Model): text = models.CharField(max_length=5, choices=too_many) class Parent(models.Model): grandparent = models.ForeignKey(Grandparent, on_delete=models.CASCADE) info = models.CharField(max_length=30) class ChildSomething(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) data = models.CharField(max_length=5, choices=chromosome_identities) Given a specific Grandparent object, I wanted to order Parent objects underneath it by most ChildSomething's each Parent has, which I did successfully below. grandparent = Grandparent.objects.get(id=32923) # arbitrary id # This query produces the desired result parents = ( Parent.objects.filter(grandparent=grandparent). annotate(num_child_somethings = Count('childsomething')). order_by('num_child_somethings') ) My question: Why is it Count('childsomething') instead of Count('child_something')? The latter was my intuition, which was corrected by a helpful Django error message: Exception Type: FieldError Exception Value: Cannot resolve keyword 'user_translation' into field. Choices are: id, translate_text, translate_text_id, translation, usertranslation The answer to this is likely simple, I just couldn't find anything in the docs related to this. How does the naming convention work? If anyone knows of the appropriate Django docs link that would be ideal. Thank you. -
Django Webpack static not finding file
I created a Django application and tried to serve files via webpack. Now the application can't find those files despite setting the required constants in settings.py. The output folder is right in the root directory and should be picked up by STATICFILES_DIRS, but if I start the application I get a 404 not found error. I'm outputting my files via webpack inside the root folder in /dist/js/*.js webpack.config.js const webpack = require('webpack'); const glob = require('glob'); let globOptions = { ignore: ['node_modules/**', 'venv/**'] } let entryFiles = glob.sync("**/javascript/*.js", globOptions) let entryObj = {}; entryFiles.forEach(function(file){ if (file.includes('.')) { let parts = file.split('/') let path = parts.pop() let fileName = path.split('.')[0]; entryObj[fileName] = `./${file}`; } }); const config = { mode: process.env.NODE_ENV, entry: entryObj, output: { path: __dirname + '/dist/js', filename: '[name].js' }, optimization: { minimize: false } } module.exports = config settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = "/static/" STATICFILES_DIRS = [ ("js", f"{BASE_DIR}/dist/js"), ] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") main.html: {% load static %} <!DOCTYPE html> <html lang="de"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> {% block content %} {% endblock %} </body> <!-- Load bundled webpack script --> <script src="{% static 'main.js' %}" … -
Fixing ValueError: source code string cannot contain null bytes for django server
I am new to Django and I am trying to run my server, but I get this error message. Any help on how to fix it? File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\ma nagement\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\comman ds\runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp. py", line 14, in <module> from wsgiref import simple_server ValueError: source code string cannot contain null bytes I am using IntelliJ terminal to run it with python manage.py runserver Tried re-saving and re-writing it so to be sure it is in UTF-8, and it is. -
Field data disappears in Django REST framework
I have a field "plugins" (see below) in my serializer and this is a serializer which also contains a file upload which is why the MultiPartParser is used. My view is pretty much standard, and the plugins field data also shows up in the request.data, however it doesn't show up in the validated_data of the serializer. To bring a minimalistic example, this would be my serializer: class CreationSerializer(serializers.ModelSerializer, FileUploadSerializer): plugins = serializers.ListSerializer( child=serializers.CharField(), required=False, write_only=True) class Meta: fields = ['plugins'] + FileUploadSerializer.Meta.fields model = Company def create(self, validated_data): print(validated_data) While this would be my views.py: @swagger_auto_schema(request_body=CreationSerializer(), responses={201: CreationSerializer()}, operation_id='the_post') def create(self, request, *args, **kwargs): print(request.data) return super().create(request, *args, **kwargs) # which uses mixins.CreateModelMixin -
Cleaner django filters in graphql query
I have a project in angular where we use graphql to gather data from api that is created in django. I am using filters that are available in django-filter and here is my question. My example query looks like this: query foo( ... $something_Icontains: String, $something_Iexact: String, $something_IstartWith: String, $something_IendsWith: String, $something_IsNull: String, ... ) { foo( ... something_Icontains: $something_Icontains, something_Iexact: $something_Iexact, something_IstartWith: $something_IstartWith, something_IendsWith: $something_IendsWith, something_IsNull: $something_IsNull, ... ) { result { ...fooFields } } } It is quite lengthy and grows exponentially when more fields is added. Is there any way to shorten it? -
Passing ID Mitch mech with Django Pattern in Axios, Vue JS
I am want to update and delete by clicking in Datatable button. But, unfortunately I could not passing the PK=ID in Django Pattern through Axios. `from django.urls import path from . import views from django.views.generic import TemplateView app_name = 'todospaapp' urlpatterns = [ path('', views.index, name='index'), path('todos/', views.todos, name='todos'), path('save_todo/', views.save_todo, name='save_todo'), # path('<pk>/update', views.save_todo_update, name='save_todo_update' ), path('save_todo_update/<int:pk>', views.save_todo_update, name='save_todo_update'), ]` In my view.py `def save_todo_update(request, pk): try: todoitem = TodoItem.objects.get(pk=pk) except TodoItem.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = TodoItemSerializer(todoitem) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = TodoItemSerializer(todoitem, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors)` In my HTML: <tbody> <tr v-for="todo in todos"> <th scope="row" >[[todo.id]]</th> <td>[[todo.text]]</td> <td>[[todo.date_created | formatDate]]</td> <td>[[todo.date_completed | formatDate]]</td> <td><a class="btn btn-primary" v-on:click="updateTodo(todo.id)" >Update</a></td> </tr> </tbody> In Axios: updateTodo: function(id) { axios({ url: "{% url 'todospaapp:save_todo_update/'+id %}", method: 'put', data: { todo_text: this.input_todo }, headers: { 'X-CSRFToken': '{{ csrf_token }}' } }).then(response => { // console.log(response.data) this.getTodos() }) } }, -
Should i use Vue or django for URL routing?
I have been learning web development for two months, in tutorials there is a video about path and components with vue. const routes= [{ path:"/", component: () => import(./views/home) }] As far as i know you can do the same thing with django as well. urlpatterns = [path('', views.special_case_2003),] Which one should i use for URL routing? If they are doing same thing then why should i use a backend framework? -
Django Calculated fields Save()
This is very basic, but I'm having trouble finding the correct way to do this. I would like to have fields that are calculated and saved into the database. In the example, cHpd,cMpd and cBph are all fields that are calculated in the calc_rates function. I am piecing together how to do this. ''' class Route(models.Model): rtNumber = models.CharField(max_length = 5) rtState = models.CharField(max_length = 2) rtOffice = models.CharField(max_length = 255) #stDate = models.DateField(blank=True) #edDate = models.DateField(blank=True) llcName = models.CharField(max_length =255) boxes = models.IntegerField(null=True) miles = models.IntegerField(null=True) hours = models.IntegerField(null=True) wrkDays = models.IntegerField(null=True) activeCont= models.BooleanField(default=None) contRate = models.IntegerField(null=True) cHpd = models.IntegerField(null=True) cMpd = models.IntegerField(null=True) cBph = models.IntegerField(null=True) @property def calc_rates(self): hpd = self.hours / self.wrkDays mpd = self.miles / self.wrkDays bph = self.boxes / hpd self.cHpd = hpd self.cMpd = mpd self.cBph = bhp super(Route, self).save() -
Custom Permissions Verification Django Rest Framework
I am trying to figure out the best way to write a custom permission in Django Rest Framework for the following use case. I have a User model and a Organization model. A User can have multiple Organizations and an Organization can have multiple Users. I have this model to connect the relationships: class UserOrganization(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) role = models.CharField(max_length=255, default="Owner") primary_org = models.BooleanField(default=False) Users are able to create integrations to third party services, but these are tied to both the User and the Organization. I currently have the following custom permission that checks the User but how do I check if they are a member of the Organization? class UserPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Deny actions on objects if the user is not authenticated if not request.user.is_authenticated(): return False if view.action == 'retrieve': return obj.user == request.user or request.user.is_admin elif view.action in ['update', 'partial_update']: return obj.user == request.user or request.user.is_admin elif view.action == 'destroy': return request.user.is_admin else: return False The Organization id will be passed with every API call. Here's the Viewset for adding a new integration class IntegrationViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): def get_queryset(self): user = self.request.user return Integration.objects.filter(user=user) serializer_class … -
Django error : NoReverseMatch at /Post/8 Reverse for 'comments' with arguments '('',)' not found
I am working on my project I faced a problem with "COMMENT": I add a comment as a section when the user clicks "view" button to see the post from the home page. Django error : NoReverseMatch at /Post/8 Reverse for 'comments' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9]+)$'] views.py file def viewList(request, id): item = Post.objects.get(id=id) context = { 'item': item, 'comment_form': comment(), 'comments': item.get_comments.all(), } return render(request, 'auctions/item.html', context) @login_required def comments(request, id): listing = Post.objects.get(id=id) form = comment(request.PSOT) newComment = form.save(commit=False) newComment.user = request.user newComment.listing = listing newComment.save() return HttpResponseRedirect(reverse("listing", {'id': id})) models.py file class Post(models.Model): # data fields title = models.CharField(max_length=64) textarea = models.TextField() # bid price = models.FloatField(default=0) currentBid = models.FloatField(blank=True, null=True) imageurl = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.PROTECT) watchers = models.ManyToManyField( User, blank=True, related_name='watched_list') date = models.DateTimeField(auto_now_add=True) # for activated the Category activate = models.BooleanField(default=True) def __str__(self): return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}" class Comment(models.Model): body = models.CharField(max_length=100) createdDate = models.DateTimeField(default=timezone.now) # link to the post model auction = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="get_comments") user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=True) def __str__(self): return self.createdDate.strftime('%B %d %Y') HTML file … -
Django Update Middleware to replace decorator
I have the following Decorator which works fine when applied to different views with: @otp_required(login_url='login') on my site: Decorator from django.contrib.auth.decorators import user_passes_test from django_otp import user_has_device from django_otp.conf import settings def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False): """ Similar to :func:`~django.contrib.auth.decorators.login_required`, but requires the user to be :term:`verified`. By default, this redirects users to :setting:`OTP_LOGIN_URL`. :param if_configured: If ``True``, an authenticated user with no confirmed OTP devices will be allowed. Default is ``False``. :type if_configured: bool """ if login_url is None: login_url = settings.OTP_LOGIN_URL def test(user): return user.is_verified() or (if_configured and user.is_authenticated and not user_has_device(user)) decorator = user_passes_test(test, login_url=login_url, redirect_field_name=redirect_field_name) return decorator if (view is None) else decorator(view) However, I’d like to convert this into a Middleware as I want to avoid having to apply a decorator to every view on my site, but not managed to get working. I tried to amend the following Middleware which I currently have in place which is just for authorised users and has been working but as per above decorator I want this Middleware extended to also have OTP required as well: Middleware from django.utils.deprecation import MiddlewareMixin from django.urls import resolve, reverse from django.http import HttpResponseRedirect from wfi_workflow import settings class LoginRequiredMiddleware(MiddlewareMixin): """ Middleware … -
Django-rules replacement of guardian.mixins.PermissionListMixin
In my django based application I want to enable users to keep track of their locations. Each location has an owner, and the list view should only show the locations the current user owns. With django-guardian I was able to achieve the same with specifying the following in my views.py: from django.views import generic from guardian.mixins import PermissionRequiredMixin, PermissionListMixin # Create your views here. from .models import Location class LocationListView(PermissionListMixin, generic.ListView): model = Location permission_required = 'view_location' paginate_by = 20 ordering = ['name'] How would I create something similar with django-rules? -
OpenCV issues on Azure with Django
So, weird one for you all... I am working on building an emotion detection app using OpenCV/Mediapipe in Django. I am hosting it on Azure right now (it is very basic). When I start the app using func host start It works 100% as expected if I start it using python3 manage.py runserver I see the rest of my app, but my video isn't available. And the weird thing is, I DON'T SEE ANY ERRORS on my console. camera.py import cv2 import mediapipe as mp from mediapipe.python.solutions import drawing_utils, face_mesh mp_draw = drawing_utils mp_face_mesh = face_mesh faceMesh = mp_face_mesh.FaceMesh(max_num_faces=2) draw_specs = mp_draw.DrawingSpec((255, 0, 0), 1, 1) class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() if success: rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = faceMesh.process(rgb) if results.multi_face_landmarks: faces = [] for face_landmarks in results.multi_face_landmarks: mp_draw.draw_landmarks( image, face_landmarks, mp_face_mesh.FACEMESH_CONTOURS, draw_specs, draw_specs) face = [] for id, lm in enumerate(face_landmarks.landmark): ih, iw, ic = image.shape x, y = int(lm.x * iw), int(lm.y*ih) # cv2.putText(image, str(id), (x, y), # cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 1) face.append([x, y]) faces.append(face) frame_flip = cv2.flip(image, 1) ret, jpeg = cv2.imencode('.jpg', frame_flip) return jpeg.tobytes() views.py class HomeView(TemplateView): template_name = 'welcome.html' def gen(camera): … -
¿why the discount is not seen in the template with javascript?
I have problem showing discount result in input (created with django) The result of the multiplication does appear and using the same logic I implemented it for the descent point, however, although the code is very similar, it is not displayed I do not put all the django code because it seems that it is ok because it does read the result of the multiplication, it seems that it is more my logic error in javascript clicking on the button should give both results, which it does not do, it only shows one I add the image of the result function multiplicar(){ var quantity=parseInt(document.getElementById('id_quantity').value); var unit_price=parseInt(document.getElementById('id_unit_price').value); var percent=parseInt(document.getElementById('id_descuento').value); var total_price=document.getElementById('id_total_price'); var total=document.getElementById('id_total'); total_price.value=quantity*unit_price; console.log(total_price); total.value=(percent*total_price)/100; console.log(total); } <!-- Parts --> <h3>Partes</h3> <section> <div> <form> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Partes</h4> <p class="card-title-desc">Agrega las partes que se incluirán</p> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div class="form-check"> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn …