Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
In Django, how do I access and display the full name of a user in an Admin filter, when the full name is a foreign key value?
I am using the default Django admin and User model. I'm trying to add a field to list_filter where the field's value is username. But I would like to display the user first_name and last_name in the filter. I'm not sure how to access those user values from the admin. Here's a little code that doesn't work: list_filter = ('status', 'assignee_full_name') @property def assignee_full_name(self, obj): return obj.assignee.first_name + obj.assignee_last_name (assignee is the field I'm sorting on, that's the one with the value that equals the username.) This code as written doesn't work. The error message is <class 'intake.admin.ClientAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'assignee_first_name', which does not refer to a Field. What do I need to do differently to get assignee.first_name and assignee_last_name into a form that will be recognized or displayed by list_filter? There's a similar question at Django Display User as user Full Name in Admin Field, in fact this code was derived from that answer, but the accepted answer is unsatisfactory; as it says right in the answer, it "doesn't work". I appreciate that the questions are substantially similar, but the answer provided does not answer the question. -
How do I change an environment variable only during tests in Django?
I have a class that extends the root TestCase. I would like to set an environment variable in each of the tests that extend this class so that I don't cycles on unnecessary API queries. When I place the patch decorator outside of the class, it appears to have no effect. When I place the patch decorator just above the setUp, the patch appears to only last through the duration of the setUp. import mock, os from django.test import TestCase #patching here seems to have no effect class TCommerceTestCase(TestCase): @mock.patch.dict(os.environ, { "INSIDE_TEST": "True" }) def setUp(self): self.assertEqual(os.environ["INSIDE_TEST"], "True") # works! def test_inside_test(self): self.assertEqual(os.environ["INSIDE_TEST"], "True") # Fails! How do I patch an environment variable in a Django test (without manually patching to every function?) -
Bokeh & Django: RuntimeError("Models must be owned by only a single document")
I am making some bokeh plots using python bokeh and django. I'm trying to put these bokeh plots in a row, but this fails at the line: script, div = components(row(sample_plot, variant_plot, sizing_mode='scale_width')) in the code below. If i try to render a single plot generated with this method, it works. The error message i get is: I'm very confused why this is happening when i put my plots in a row. ERROR (exception.py:118; 04-11-2021 16:56:58): Internal Server Error: / Traceback (most recent call last): File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/path/2/ma/viewz/HTS/views.py", line 932, in get script, div = components(plot_row) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/embed/standalone.py", line 216, in components with OutputDocumentFor(models, apply_theme=theme): File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/embed/util.py", line 134, in OutputDocumentFor doc.add_root(model) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 321, in add_root self._pop_all_models_freeze() File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 1104, in _pop_all_models_freeze self._recompute_all_models() File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 1127, in _recompute_all_models a._attach_document(self) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/model.py", line 692, in _attach_document raise RuntimeError("Models must be … -
Django stops serving static css files; but static images keep working
Template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width = device-width, initial-scale = 1"> <link rel="stylesheet" href="{% static "css/custom/nav.css" %}"> <link rel="stylesheet" href="{% static "css/custom/fonts.css" %}"> </head> <body> <div> <figure> <img src="{% static 'icons/logo.png' %}" alt=""> </figure> </div> </body> settings: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "webapp/static", ] STATIC_ROOT = "django_static" Problem: Django doesn't load static files. The browser throws: [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav.css, line 0) Not found: http://127.0.0.1:8000/static/css/custom/nav.css But, the images in static files work quite well. The URL for the main logo gets rendered to: http://127.0.0.1:8000/static/icons/logo.png Pictures get served without a problem, css doesn't. This happened in my opinion random. I had this issue formerly on a different page where css for the admin page apparently just stopped working and I couldn't figure out why. Now it happened for all css files on a bigger project that I can't just scrap and restart. I have no idea why this happens or how to troubleshoot this. I changed all static paths around, did collectstatic several times, added static paths to urls.py... Nothing changed. Edit: as I don't … -
Django - Send notification to user after new like
I'm searching for a method to notify an user if another user liked his/her post. For example instagram is giving you an alert: "this_user liked your post". Is there a way to do with djangos integrated messages framework? So far I got the logic for like a post (simple post request). I want to send the notification to the author of the post so after post.save() method. Someone know how to do? -
How to get mysqlclient to work with pipenv?
After installing mysqlclient with 'pipenv install mysqlclient' and attempting to runserver I was getting this error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?