Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model class computedfields.models.ComputedFieldsAdminModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm trying to add a calculated field to my model (i want the field to be stored in the model/ the admin panel/ and in the database) PS : I'm not sure if it's the right method to add calculated columns to my model. i'm trying to use computedfields and i have this error RuntimeError: Model class computedfields.models.ComputedFieldsAdminModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. models.py : from asyncio.windows_events import NULL from email.policy import default from msilib import type_valid from pyexpat import model from unittest.util import _MAX_LENGTH from django.db import models import computed_property from computedfields.models import ComputedFieldsModel, computed, compute class MyProject(models.Model): Compte_Analytique = models.CharField(max_length=30) Libelles = models.CharField(max_length=500) Realisation= models.CharField(max_length=50) Prévision = models.CharField(max_length=50,blank=True,default=0) @computed(models.CharField(max_length=500), depends=[('self', ['Realisation_cum_total', 'Prévison_de_cloture','Prévision_2020','Reste_a_realiser'])]) def CGI(self): cloture=self.Realisation +self.Prévision return cloture def __str__(self): return self.Libelles``` settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'home.apps.HomeConfig', ] apps.py: from django.apps import AppConfig class HomeConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'home' -
Django-stubs doesn't ignore import
I've tried to configurate pre-commit + mypy + django-stubs, so I have error when i try to commit. ModuleNotFoundError: No module named 'environ' My configs: .pre-commit-config.yaml - repo: https://github.com/pre-commit/mirrors-mypy rev: '' hooks: - id: mypy exclude: "[a-zA-Z]*/(migrations)/(.)*" args: [--config=setup.cfg, --no-strict-optional, --ignore-missing-imports] additional_dependencies: [django-stubs] setup.cfg [mypy] allow_redefinition = True check_untyped_defs = True ignore_missing_imports = True incremental = True strict_optional = True show_traceback = True warn_no_return = False warn_unused_ignores = True warn_redundant_casts = True warn_unused_configs = True plugins = mypy_django_plugin.main show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.local [mypy_django_plugin] ignore_missing_model_attributes = True [mypy-*.migrations.*] # Django migrations should not produce any errors: ignore_errors = True Does anyone have any ideas? -
ValueError: dictionary update sequence element #0 has length 1; 2 is required on cacheops
I get an error with this line of code in my settings.py for cacheops CACHEOPS = {'letes.*':('all'),} This is the error. ValueError: dictionary update sequence element #0 has length 1; 2 is required -
DRF: Optimization in use_pk_only_optimization?
What is the optimization in use_pk_only_optimization? I am setting it to return False but I am afraid to badly affecting the performance. Best Regards -
How Do I Access Data From a Multi-Table Inheritance Definition?
Straight from the Django Docs.... from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) I've been playing with this all afternoon. The good news is that I can get it to work as long as you don't call your app Abstract... I can see the data in my database so I know it's working...but I can't figure out how to access the data. In the past I have used Class Based Views...this is my first go at using a multi-table inheritance structure beyond class based views. I have tried to do... def get_absolute_url(self): return reverse("App:create_restaurant_detail",kwargs={'pk':self.object.place_ptr_id}) But the url lookup keeps saying not found. I'm trying to figure out how to access the data in the table. Thanks for any thoughts and help in advance. -
ModuleNotFoundError: No module named 'rest_framework'. I have installed djangorestframework and I have 'rest_framework' in INSTALLED_APPS
I am having trouble importing rest_framework from django. I have already installed djangorestframework using 'pip install djangorestframework' and I have 'rest_framework' in the INSTALLED_APPS section in settings.py. I am working in vsCode and I have tried restarting it to see if that would but I'm having no luck. Any ideas on how to fix this? -
Django, accessing the top parent objects from second level parents from child with many to many realtaionship
I have a setup where I have these models. Devices Slideshows Slides The device can have only one slideshow Slideshow can be assigned to many devices The slide can be assigned to many slideshows Now, I am trying to work my way up the tree to get all of the devices that have all the slideshows that the slide belongs to. Lets say I have a hold of the 'slide 1' object. Is there a query that could get me all the devices at the top of the tree? Currently, this is how I am traversing to the top as I need to send a post_save signal, it is working as is but I feel like it is a bad way to do it. and it's hard for even me to follow. I am using related names to go up the tree. related_name=devices related_name=slideshows I was hoping to do something simple like instance.slideshows.devices.all() but that yields related manager errors or even instance.slideshows.all().devices.all() slideshows = instance.slideshows.all() related_devices = [] for slideshow in slideshows: devices = slideshow.devices.all() related_devices = list(chain(related_devices, devices)) for device in related_devices: post_save.send(Device, instance=device) -
django howto use select_related not using local id key
i have made two models where i would like to get them joined on the two name keys. models.py class MODELa (models.Model): ...... nameXX = models.CharField(_("name"), max_length=255, primary_key=True) class MODELb (models.Model): ...... nameYY = models.CharField(_("nameYY"), max_length=255) FKxx = models.ForeignKey(to=MODELa, on_delete=models.CASCADE, null=True) views.py rows = MODELb.objects.all().select_related('FKxx') using debug toolbar, i can see the join is using the id field LEFT OUTER JOIN "MODELa" ON ("MODELb"."FKxx_id" = "MODELa"."nameXX") How do i set it use the local key nameYY? -
DRF set_cookie does not work when frontend is on localhost and backend is on a remote server
I've created a DRF app which the backend is using jwt authentication with httpolnly cookies for authentication and it also uses a enforce_csrf for perventing csrf attacks. from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings from rest_framework.authentication import CSRFCheck from rest_framework import exceptions def enforce_csrf(request): check = CSRFCheck() check.process_request(request) reason = check.process_view(request, None, (), {}) print(reason) if reason: raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) class CookieBasedJWTAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token to pervent csrf attacks django set a cookie and also a 'csrftokenmiddleware' and compares them. here is the sample code for setting csrf cookie and token: class SetCSRFToken(APIView): permission_classes = [AllowAny] def get(self, request): response = Response() csrf.get_token(request) response.status_code = status.HTTP_200_OK csrf_secret = csrf.get_token(request) response.set_cookie( key = 'csrftoken', value = request.META["CSRF_COOKIE"], expires = settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'], path= settings.SIMPLE_JWT['AUTH_COOKIE_PATH'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = False, samesite = 'Lax' ) response.data = {"status": "CSRF cookie set", 'csrfmiddlewaretoken':request.META["CSRF_COOKIE"]} return response i also set : CORS_ALLOW_ALL_ORIGINS= True CORS_ALLOW_CREDENTIALS = True the code works perfect when both frontend and backend are on the localhost, but when i run the … -
Django: Thread causing InMemoryUploadedFile to prematurely close?
Good day, I have a problem where a CSV file, sent to a View and later passed into a new thread for processing, sometimes closes prematurely and I can't figure out why. The behaviour is intermittent and only started happening after I switched to using a new thread to process the file. This is the original way I was processing the file and it worked, but for large files it caused time-out issues on the client: class LoadCSVFile(APIView): permission_class = (IsAuthenticated,) parser_classes = [FormParser, MultiPartParser] def post(self, request): file = request.FILES['file'] data_set = file.read().decode('utf-8') io_string = io.StringIO(data_set) for row_data in csv.reader(io_string, delimiter=',', quotechar='"'): print('row_data:', row_data) return Response({ 'message': 'File received and is currently processing.', 'status_code': status.HTTP_200_OK }, status.HTTP_200_OK) So I now process the file in a new thread like so: class LoadCSVFile(APIView): permission_class = (IsAuthenticated,) parser_classes = [FormParser, MultiPartParser] def post(self, request): request_handler = RequestHandler(request) csv_handler = CSVHandler(request.FILES['file']) # Fire and forget the file processing. t = threading.Thread(target=request_handler.resolve, kwargs={ 'csv_handler': csv_handler }) t.start() return Response({ 'message': 'File received and is currently processing.', 'status_code': status.HTTP_200_OK }, status.HTTP_200_OK) class RequestHandler(object): def __init__(self, request : Request): self.request = request def resolve(self, **kwargs): csv_handler = kwargs['csv_handler'] try: print('Processing file...') csv_handler.process_file() except Exception as e: … -
Django get parameter from url in Template to set CSS
I have a dynamic category menu list in my template that I would like to highlight (set active) when the url parameter matches the menu item. Therefore when the page equals the menu item the category will be highlighted. URL examples: https://[domainname]/training/?category=1 https://[domainname]/training/?category=2 https://[domainname]/training/?category=3 {% for categories in category_list %} <a href="{% url 'training' %}?category={{categories.Category_id}}" class="list-group-item list-group-item-action {% if request.GET.category == 'categories.Category_id' %}active{% endif %}"> {% endfor%} -
Null value of foreign key column in Django Serializer
I'm using ModelSerializer and setting all fields from my Item model, but I have null value in category field when retrieving everything. Item description Item and Category Model As you can see value of category is null -
values() with ManyToMany field only returns the last object in the M2M field - django
I'm trying to return my data into json using values()but when i try to use M2M field in the Values() it returns only the last object of the M2M field, is there a way to return all of the objects in the M2M field within the Values() please class CustomerInvoice(models.Model): customer = models.CharField(max_length=50) items_model = models.ManyToManyField(Item,through='InvoiceItem') class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() and here is my query invoices = CustomerInvoice.objects.values('id','customer','items_model__name').order_by('-id') but it returns only the one objects in the M2M fields, i know i need to do something like this but i have to keep Values() format a = [] for data in invoices: for i in data.items_model.all(): a.append(i.name) thank you in advance .. -
In-page JS search not working in some pages
I'm using a simple JS in-page search on my Django web application. The problem is that it isn't working in some of the views for some reason. It works on the template created by GameListView but it doesn't work on the template created by GameListViewByDist. I'm not sure if it's relevant but both views are rendered on game_list.html which extends from base.html where the navbar search field is. Since both view codes are much alike i'm having a hard time finding the error. I appreciate any help. **HTML** **BASE.HTML** <nav> <input id="searchbox" type="search" placeholder="Search"> </nav> **JS** let type_timer; let type_interval = 300; let search_input = document.getElementById('searchbox'); search_input.addEventListener('keyup', () =>{ clearTimeout(type_timer); type_timer = setTimeout(liveSearch, type_interval); }); function liveSearch(){ let cards = document.querySelectorAll('.game_card'); let search_query = document.getElementById("searchbox").value; // SHOW MATCHES AND HIDE THE REST for (var i = 0; i < cards.length; i++){ if(cards[i].innerText.toLowerCase().includes(search_query.toLowerCase())){ cards[i].classList.remove("is_hidden"); } else{ cards[i].classList.add("is_hidden"); } } } **VIEWS.PY** class GameListView(SortableListMixin, ListView): sort_fields = [('name'), ('purchase_date')] model = models.Game ordering = ['-purchase_date'] def get_context_data(self, **kwargs): context = super(GameListView, self).get_context_data(**kwargs) context.update({ 'tag_list': models.Tag.objects.all(), }) return context class GameListViewByDist(ListView): def get_queryset(self): self.distributor = get_object_or_404(models.Distributor, pk=self.kwargs['distributor']) return models.Game.objects.filter(gamestatus__distributor=self.distributor) def get_context_data(self, **kwargs): context = super(GameListViewByDist, self).get_context_data(**kwargs) context.update({ 'tag_list': models.Tag.objects.all(), }) return context -
Retrieve only the courses that the user has created
I am trying to get only the courses that the user has created to be listed out when the user wanted to create a quiz. So that the user could create a quiz for a particular course that the user has created. However, now I all the courses that are is my database are being listed out. I am not sure how to get only the courses that the user has created to be listed. Please help me out. models.py class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.CharField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.CharField(max_length=2500, null = False) timeline_budget = models.CharField(max_length=250, null = False) req_prerequisite = models.CharField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) def __str__(self): return self.title @property def sliceLearn(self): subtitle = self.roles_responsibilities return subtitle.split('.')[:-1] class Quiz(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) title = models.CharField(max_length=300, null = False) … -
Changing the default class for Bootstrap Crispy Form
I am using Crispy Forms with Bootstrap4. Currently, all the input fields are rendered with form-control class. I want to add form-control-lg to the input fields. I have tried the following but it is not working forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'first_name', 'last_name'] help_texts = { 'username': None, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password1'].help_text = None self.fields['password2'].help_text = None self.fields['password2'].label = "Confirm Password" self.helper = FormHelper() self.helper.layout = Layout( Field( 'username', css_class="form-control form-control-lg my-custom-class" ) ) Template <div class="content-section"> <form method="POST" action=""> <h3>Sign Up</h3> <hr> {% csrf_token %} {{ form | crispy }} </br> <button type="submit" class="btn btn-primary">Sign Up</button> </form> </div> Also, can I modify the class globally for all input fields? -
Django REST Framework Token Auth request.user returns empty
I'm trying to create a REST API which inserts an ID inside a favorites many to many model. But when I try to get the request.user it returns empty. Im using the TokenAuth method and I send the key inside the Authentication header. Here you see my Viewset. The ["favorites"] is send inside the body of the POST request. class FavoriteViewSet(view sets.ModelViewSet): queryset = Profile.objects.all() serializer_class = FavoriteSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] def post(self): data = request.data profile = Profile.objects.get(user=self.request.user) profile.favorites.add(data["favorites"] return Response(status=status.HTTP_201_CREATED) My serializer: class FavoriteSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' depth = 1 My Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Receipt) def __str__(self): return self.id My Error: IntegrityError at /v1/favorites/ (1048, "Column 'user_id' cannot be null") -
Best approach at multiple node types in MPTT model
just looking to get some feedback as I attempt to increase the efficiency of my models. I am using MPTT to build a hieratical content that can support multiple content types within the tree. The initial approach that I took was to create a node model with a Generic relationship and separate models of node types with a Generic relation to the node model. I've seen mixed feelings regarding GenericForeignKey and I am experiencing the added work of these relationships not being natively supported by Django. Such as needing to manually associate the nodes, needing to manually check the content of the node, etc. This manner also results in additional queries to the database. Is there a different approach to this? I been trying to model out creating a Node model, and inherit different Node types however, if each model had a TreeForeignKey, they'd also be able to only reference their own model without a GenericForeignKey My models are currently built as so. class StoryNode(MPTTModel): story = models.ForeignKey(Story, on_delete=models.RESTRICT, null=True, related_name='storynodes') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') ending_node = models.BooleanField(default=False) limit = models.Q(app_label='core', model='storytext') | models.Q(app_label='core', model='storyaction') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', … -
How to put Pytesseract OCR on the web
I am using Pytesseract OCR for text detection and I am using a jupyter notebook to run it right now so the output is just popping up as another window. My output for the program is an image and I was wondering if there is a way to use flask or django or something to put my program on a website. I am trying to allow the user to input their own image and then the program will output another image on the website. This is the main code: def pytess(img): hImg,wImg,_ = img.shape boxes = pytesseract.image_to_boxes(img) for b in boxes.splitlines(): print(b[0]) b = b.split(' ') x,y,w,h= int(b[1]),int(b[2]),int(b[3]),int(b[4]) cv2.rectangle(img,(x,hImg-y),(w,hImg-h),(0,0,255), 2) cv2.putText(img,b[0],(x,hImg-y+25), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2) ##Detecting Words hImg,wImg,_ = img.shape boxes = pytesseract.image_to_data(img) for x,b in enumerate(boxes.splitlines()): if x!=0: b = b.split() if len(b)==12: x,y,w,h= int(b[6]),int(b[7]),int(b[8]),int(b[9]) cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255), 2) cv2.putText(img,b[11],(x,y), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2) cv2.imshow("Result",img) cv2.waitKey(0) pytess(img) -
(Django) Primary key is not applied
I set the restaurant_id column as pk as below, but when I try to insert data on the admin page the restaurant_id column in the menu table shows name data in the restaurant table. Why does this happen? class Restaurant(models.Model): restaurant_id = models.AutoField(primary_key=True) photo = models.ImageField(upload_to="images/") name = models.CharField(max_length=50) phone = models.CharField(max_length=15) hours = models.CharField(max_length=100) website = models.URLField(max_length=200) country = models.CharField(max_length=20, default='country') def __str__(self): return self.name class Menu(models.Model): restaurant_id = models.ForeignKey(Restaurant, on_delete=models.CASCADE) item = models.CharField(max_length=100) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.item -
Does Django have an equivlant to ruby on rails "rails db:create"?
I've been searching on google about this but everyone is saying Django lacks this feature. I should not have to manually create the initial database in PGAdmin or something similar just to start development. What is the django equivalent of rails db:create? -
Page not found at/admin
I'm a very beginner. When I tried to go visit this (http://127.0.0.1:8000/admin), I couldn't. Here have shown page not found. What can be the solution? -
how to edit views.py in django when installed in ubuntu server
I installed Django in ubuntu server ,when I connect t my public server:8080 I got Django installed, now how to edit urls.py file or tests.py in server, should I use WinSCP or is there any graphical option to edit files in server to modify Django website -
please help i dont understand
hi please help me i created a createview class in my app and then i put a post method and then it gives me this error: 'Register' object has no attribute 'object' class Register(CreateView): form_class = RegForm model = Users template_name = 'registro.html' success_url = '/home/' def get_form(self, form_class=RegForm): if form_class is RegForm: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): name = form.cleaned_data['name'] Flastname = form.cleaned_data['Fatherslname'] Mlastname = form.cleaned_data['Motherslname'] age = form.cleaned_data['age'] return self.form_valid(form) else: return self.form_invalid(form) and this is my forms i dont know why: class RegForm(ModelForm): class Meta: model = Users fields = ['name', 'lname1'] Name = forms.CharField(label="Nombre", max_length=100, required=False) Fatherslname = forms.CharField(max_length=100, required=False) Motherslname = forms.CharField(max_length=100, required=True) age = forms.IntegerField() UserName = forms.CharField(required=True, max_length=80) userType = forms.ChoiceField(label="Eres?", choices=users) birthplace = forms.ChoiceField(label="Pais", choices=Paises) dateOfBirth = forms.DateField(label="Fecha de Nacimiento", initial=datetime.date.today) imagen = forms.ImageField(label="foto") Email = forms.EmailField(required=True) passwd = forms.CharField(label="contraseña", max_length=32, widget=forms.PasswordInput) ConfPasswd = forms.CharField(label="confirmar contraseña", max_length=100, widget=forms.PasswordInput) -
WebSocket not connecting |. Django Channels | WebSocket
I am using the WebsocketConsumer consumer and when I disconnect the websocket connection it gives the below error. Also when I have already one open connection and when I try to create a connection with the same route it gets Disconnected and gives the same Application instance <Task pending name='Task-5' coro=<StaticFilesWrapper.__call__() running at /Volumes/Data/Projects/LocoNav-LM/vt-lm-server/venv/lib/python3.8/site-packages/channels/staticfiles.py:44> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/futures.py:360, <TaskWakeupMethWrapper object at 0x1076a2580>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 54789] path=b'/ws/users/'> took too long to shut down and was killed. My code:- class TestMultipleUsers(WebsocketConsumer): def connect(self): logging.info('connecting....') self.accept() redis_client = RedisClient(host='localhost', port=6379, db=0) redis_client.subscribe_and_listen() redis_client.subscribe_channel('test') for message in redis_client.sub.listen(): if message is not None and isinstance(message, dict): print(message) self.send(text_data="1") def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) def disconnect(self, close_code): logging.info('disconnecting....') logging.info(close_code) However, whenever I disconnect the web socket from Postman the disconnect method never gets called. requirements.txt channels==3.0.4 Django==4.0 celery==5.2.3