Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OpenCV camera issue with Django and Azure
I am new to using azure and django. During my project I'm having issues with the camera on my laptop. When running the code on my local system, it works completely fine (the camera opens, detects everything and does what it needs to). So after that I uploaded my code on azure using a virtual machine to get it up and running. The code is uploaded fine and everything works fine but the camera doesn't switch on (a broken image box appears) when I go to the page where the camera is supposed to run. What can I do to fix this? I uploaded the code using azure web app to look at the error logs, errors like this appear too- [ERROR] import gi [ERROR] ModuleNotFoundError: No module named 'gi' [ERROR] [ WARN:0] global /tmp/pip-req-build-khv2fx3p/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video0): can't open camera by index [ERROR] INFO: Created TensorFlow Lite XNNPACK delegate for CPU. [ERROR] cv2.error: OpenCV(4.5.4) /tmp/pip-req-build-khv2fx3p/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' (I do not get these errors on my local system, only when I upload it) (Also the audio clip that is supposed to play doesn't work either, does that have something to do with server configuration?) I … -
How to get model-objects using other models in django
I need if user requests to get the following page the response of the request would be the page containing specific posts made by the users who is followed by the user who requests. I thought to do some actions to do this: Get the requester Get the users who are followed by the requester Get the posts created by the users the who are being followed In my models.py: class User(AbstractUser): image_url = models.CharField(max_length=5000, null=True) class Follow(models.Model): follower = models.ForeignKey( User, on_delete=models.PROTECT, related_name="follower") following = models.ForeignKey( User, on_delete=models.PROTECT, related_name='following') class Post(models.Model): content = models.CharField(max_length=140) date_created = models.DateTimeField(auto_now_add=True) poster = models.ForeignKey(User, on_delete=models.CASCADE) In my views.py: def following_page(request, username): user = User.objects.get(username=username) f = user.following.all() posts = Post.objects.filter(poster=f.following) posts = posts.order_by("-date_created").all() return render(request, 'network/index.html', { "posts": posts }) It says AttributeError 'QuerySet' object has no attribute 'following' Should I have to change the model? How to solve the problem? -
Djongo ArrayReferenceField in Django Admin Issue
I have used the below models class ProductVariation(Trackable): """Product Variation""" variation_name = models.TextField() storage = models.CharField(max_length=127) color = models.CharField(max_length=255) ram = models.CharField(max_length=255) price = models.CharField(max_length=31) variation_images = models.ArrayReferenceField(to=GenericImages, null=True, on_delete=models.CASCADE) objects = models.DjongoManager() class Product(Trackable): """Product master""" product_model = models.CharField(max_length=255) processor = models.CharField(max_length=127) screen_size = models.CharField(max_length=127) variation = models.ArrayReferenceField(to=ProductVariation, on_delete=models.CASCADE, related_name='variants') product_metadata = models.JSONField(blank=True) ##Foreignkey category = models.ManyToManyField('Category') # sub_category = models.ManyToManyField('SubCategory') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.long_name and this is my admin.py for product model class ProductAdmin(admin.ModelAdmin): list_display = ('product_model', 'created_at',) I'm not able to add the variations in the django admin for Product form(i.e there is no add symbol like for categories in front of variations field)Refer the Image Versions: Python: 3.7 Django: 3.2.6 djongo: 1.3.6 Please help me with this. Thanks! -
How to convert UIImage to data that Django understands
It may seem like a stupid question, but I have a problem with UIImage. My app communicates with my Django server, and for that, I'm using Alamofire. I need to pass an image, but I don't know how to convert UIImage to appropriate data so that the server can understand. My code currently looks like this: let param = ["image": image] // <- 'image' is a UIImage AF.request(method: .post, parameters: param) // and so on The server says the form is invalid. For my server, I'm using a form looks like this: class UploadImageForScanForm(forms.Form): image = forms.ImageField() How can I convert a UIImage to an appropriate data format so that my Django server can understand it and do its work with it? -
How to filter users first name from related model in Django filter form
I want to filter users first name from my profile model using Django filter this is my profile model in models.py. from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_members = models.CharField(max_length=500, blank=True) ...other fields and this is my filters.py import django_filters from .models import Profile class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = '__all__' in this when I add my form to template it gives me select tag with all users username and I don't want that because if user want to filter user by it's name than they can search by their name instead of looking in drop down.Please help me (: -
django changing a value of databe field using variable in view
Is there any way to update the by-hand value of a particular field in the model instance using variables? For example. models.py class ExampleModel(models.Model): name=models.CharField(max_length=10) a=models.CharField(max_length=10) b=models.CharField(max_length=10) c=models.CharField(max_length=10) views.py list=[a,b,c] fruits=[orange,apple,banana] values def ExampleView(request): model_instsnce=ExampleModel.objects.last() for i in list: instance_model.i=fruits[i] model_instance.save() In my project, I tried to use something like the above but it doesn't work. 'i' from loop doesn't behave like a variable. 'i' is treated as a new field in the model. Any idea how to use variables to designate fields from model to change? -
How to avoid data being stored in database using django rest framework
I have create a django rest framework api. For that i have created model, then create a serialize. It is working fine. I want to know is there a way that my input would not store in database. Currently, my inputs are stored in sqlite3 database. The reason why i want to do that the user input value via php form. I have to take 1 value from that form and do some modifications on it and return the value. Thats why i dont think i need a db for my django project, Here is code models.py class MyModel(models.Model): value=models.IntegerField() serializers.py class MySerializer(serializers.ModelSerializer): class Meta: model=MyModel fields='__all__' views.py class MyViews(APIView): def post(self, request): serializer = MySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('api', VideoUploadViews.as_view()) ] -
Sorl-thumbnail only working with DEBUG=True
I'm using Python 3.6.9, Django 3.2.8, sorl-thumbnail 12.7.0 with memcached my thumbnails completely disappear and give a 404 when settings.py variable DEBUG is set to False. I also have to say, that I don't get any errors displayed at all from setting THUMBNAIL_DEBUG = True as I understand it depends on the aforementioned variable which I have to set to False for pictures to disappear, if it does not depend on it I'm not getting any error displayed either. I'm just loading them inside templates like this: {% load thumbnail %} {% thumbnail ann.obj.fotografia_professionista "460x310" as thumb %}<img src="{{ thumb.url }}" data-src="{{ thumb.url }}" class="img-fluid lazy">{% endthumbnail %} and it works fine as long as DEBUG = True. I restarted apache2 and memcached, I also used python manage.py thumbnail clear or cleanup but it just doesn't work at all. I'm delivering the thumbnails at SETTINGS.MEDIA_URL, which is just set to "/media" and that I'm enabling in urls.py like this: urlpatterns = [ # my paths ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I did read this thread and I set up my urlpatterns the same exact way as it was suggested, but it doesn't solve my problem -
I have a problem with making random backgorund image usign js inside my django project?
the images don't appear even though I add the correct directory but djaong post give this massage in console: GET http://127.0.0.1:8000/%7B%%20static%20bc-3.jpg%20%%7D 404 (Not Found) script.js:24 my problem is I wanna add a random background image in my project I set this in CSS property "background-image" and it's work the URL but js code doesn't work my code: index.html {% extends "kidedu/layout.html" %} {% load static %} {% block body %} <div class="random_images_container"> <div class="main_head"> <h1>Join Our Big Community, To Educate Kids.</h1> <h5>Get Start, By sing-in for a new account or log in.</h5> <a class="head_btn btn" href="{% url 'sign_up' %}">Join Us</a> </div> <div class="arrows"> <i class="fas fa-chevron-left le"></i> <i class="fas fa-chevron-right ri"></i> </div> <ul class="bullets"> <li></li> <li class="active"></li> <li></li> </ul> </div> {% endblock %} js file // Image slider const imageSlider = document.querySelector(".random_images_container") const imagesArr = ['bc-1.jpg', 'bc-2.jpg', 'bc-3.jpg'] setInterval(() => { let randomNumber = Math.floor(Math.random() * imagesArr.length) console.log(randomNumber); imageSlider.style.backgroundImage = 'url("{% static '+imagesArr[randomNumber]+' %}")' }, 1000) url.py from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path("", views.index, name="index"), # User path("log_in/", views.log_in, name="log_in"), path("sign_up/", views.register, name="sign_up"), path("log_out/", views.log_out, name="log_out"), ] style.css .random_images_container { height: 515px; background-size: cover; background-image: url("{% static 'images/bc-1.jpg' %}"); width: … -
How to send Django GraphQL Auth mails with Celery?
I am using Django GraphQL Auth for authentication purposes. It has this feature to automatically send emails after creating an account or during a password reset etc. I want to use this feature with Celery and thankfully it provides that too here. It's just that I am not sure how to use that feature. Can you tell me how? -
Django - Pass PK as initial value in Form(CreateForm)
-Objective- I want to set an object PK as initial value in the Create Form. Version Python 3.9.2 - Django 3.2 - (Crispy-Forms) Context: I created a list from where I create objects(each with pk). Once I select one I can add several lines from a Detail page(Detailview)that redirects to create/update forms (like add/edit informations related to that specific object). I need to have it related (1 to many). -Issue and Error- I'm unable to get the object PK -as initial value- in the 1st field of the Creation form(based on Createview+ Forms.py + Class in Models.py). Errors such as: "object can't be null" - value does not appear in the form, but the space/widget does - many, many others. I tried plenty of variations of code(get pk from url, from cache, dict., def in forms.py)...but haven't found one way to make it work. Please, any help on the matter would be kindly appreciated. Thanks in advance, Below my code: Forms.py ----------------------------CREATION FORM IN THE ENDPAGE-------------------------- from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.db.models.fields import BooleanField, CharField, DateField from django.forms import ModelForm, widgets from django.forms.fields import ChoiceField from django.forms.models import ModelChoiceField from django.http.response import … -
Example of usage Subquery in django orm
What is the difference between two queries? Because I see identical queries through queryset.query. categories = Category.objects.filter(is_active=True).values_list("pk", flat=True) Post.objects.filter(category_id__in=Subquery(categories)) vs Post.objects.filter(category_id__in=Category.objects.filter(is_active=True).values_list("pk", flat=True)) And how to use Subquery properly? In what cases? Can anyone explain with examples Subquery, Outref etc? -
I am creating a blog site. I want to create a list field in the user model , or the profile model to store all the posts created by the user
** Help me to create a list field in the models or extend the user model to have the lists of posts created by the user. ** from django.db import models from django.contrib.auth.models import User from PIL import Image from blog.models import Post # This is my Profile Model class Profile(models.Model) : user = models.OneToOneField(User , on_delete = models.CASCADE) image = models.ImageField(default= 'default.png' , upload_to = "profile_pics") """ i want to create list field to store the posts user create . This is the Profile model . whenever a post is created by the user. the list in here saves the post created by the user. """ def __str__(self): return "{} Profile".format(self.user.username) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 125 or img.width >125 : output_size = (150 , 150) img.thumbnail(output_size) img.save(self.image.path) This is my Post model . How and where should i create the list so that i can have the track of the posts created by the user. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model) : title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete … -
Django Sessions not Working on remote server
I am trying to use a session variable in my django app view.py def get(self, request): room_name = request.session.get('room_name', str(uuid.uuid4().hex)) context = app.get_context(room_name) context['room_name_create'] = room_name context['room_name_check'] = request.session.get('room_name') return render(request, self.template, context) js console.log('a', context.room_name_create) console.log('b', context.room_name_check) This works perfectly on my local server. On the remote server context.room_name_create shows a value, but context.room_name_check shows as null in the browser. This is only a small app and I have copied all of the source files to the remote server and so all of the source is identical. I have tested this on different browsers Can anyone suggest what I can check to resolve this? -
What is the entry point of a Django app similar to main.py? Where do I set up parameters?
I want to set up some parameters and initialize the Injector object, because I want to use a dependency injection and singletons in my Django app. Usually I do that in the main.py of my app but with Django I don't see where the first entry point of the application is when it runs. Where shoud I initialize the injector and pass it my views and services? I have a view like this: from uuid import UUID from django.shortcuts import render from django.http.response import JsonResponse from django.http.request import HttpRequest from rest_framework import viewsets, status from rest_framework.parsers import JSONParser from rest_framework.response import Response from Instruments.services import InstrumentsService from rest_framework.decorators import api_view from Instruments.services import InstrumentsService from injector import singleton, inject # Application views live here @singleton class InstrumentViewSet(viewsets.ModelViewSet): @inject def __init__(self, instrument_service: InstrumentsService, **kwargs): self.instrument_service = instrument_service super().__init__(**kwargs) def list(self, request: HttpRequest): data = {} try: data = self.instrument_service.get_instruments() return JsonResponse(data, status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse( {"Status": f"Error: {exc}"}, status=status.HTTP_400_BAD_REQUEST, safe=False, ) def create(self, request): instrument_data = JSONParser().parse(request) data = {} try: data = self.instrument_service.add_instrument(instrument_data) return JsonResponse(data, status=status.HTTP_201_CREATED, safe=False) except Exception as exc: return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST, safe=False) def retrieve(self, request, pk: UUID = None): data = {} try: … -
Why isn't assertContains working properly in django tests?
I wrote a test that is supposed to create a flight, then pass appropriate arguments to the client.get function and receive a response that will contain results of 'search' - in this case it should be only the flight created before as a direct flight from Airport to AirportSeceond(names or airport and airport2). However, it seems that there are no results in the response (the first assertion works properly). My test (TestCase): def test_no_errors_html_direct_flights(self): country, city, airport, city2, airport2, airport3 = create_set() flight = SingleFlight.objects.create(departure_airport=airport, arrival_airport=airport2, departure_time_utc=(tz.now()+datetime.timedelta(days=5)), duration_in_hours=2, duration_in_minutes=10, price=200) print("\n\n\n") print(flight) date = (tz.now() + datetime.timedelta(days=5)).date().strftime("%Y-%m-%d") print(date) kwargs = {'dep': 'Airport', 'arr': 'AirportSecond', 'date': date} response = self.client.get(reverse('app1:flight-search-result'), kwargs) self.assertContains(response, 'No options for your search') self.assertContains(response, 'Direct connection') My template: {% block content2 %} {% if not direct_flights %} {% if not indirect_flights %} <p><strong>No options for your search</strong></p> {% endif %} {% endif %} {% for flight in direct_flights %} <p>{{ flight.departure_airport }}</p> <p>{{ flight.departure_time_local }}</p> <p> </p> <p>{{ flight.arrival_airport }}</p> <p>{{ flight.arrival_time_local }}</p> <p>Direct connection</p> <---- this should be in the response <a href="{% url 'app1:flight-search-detail-passenger-form' flight.id_flight %}">Here! ;)</a> {% endfor %} {% for connection in indirect_flights %} {{ connection.price }} {% for flight in connection.all_info %} … -
Access to ForeingKey's model data in Django
I need to access to a ForeignKey's model data, but I don't know how. I wrote this as a simple example of what I want to do: class Model1(models.Model): name = models.CharField(max_length=100) phone_number = models.BigIntegerField() class Model2(models.Model): model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) name = model1.name phone_number = model1.phone_number It gives me the following error message: AttributeError: 'ForeignKey' object has no attribute 'name' -
How to customize a look of crispy forms?
I have to edit an upload form created with crispy forms. I have provided a code that I have been used, and how it looks right now and how I would like to look. I tried to do it with helper attributes, but I failed, can you help me to get wanted outcome? This is how it looks now! I'm looking for something like this! This is upload_document.html {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <h1>Upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Upload</button> </form> {% endblock content %} models.py from django.db import models class UploadFile(models.Model): excel = models.FileField(upload_to="excel/", max_length=250) def __str__(self): return self.title forms.py from .models import UploadFile class GlForm(forms.ModelForm): class Meta: model = UploadFile fields = ('excel',) settings.py CRISPY_TEMPLATE_PACK = 'bootstrap4' INSTALLED_APPS = [ 'bootstrap4', 'crispy_forms', '...', ] Thanks in advance! -
Django Swagger won't allow me to use POST method (no parameters shown)
I'm using djangorestframework together with drf-spectacular modules for a Django project, and I'm trying to build some basic API methods for my Project model. Its structure looks like this: from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length = 128) description = models.TextField() image = models.URLField() date = models.DateTimeField(auto_now_add=True) I also have a serializer for the model, looking like this: from rest_framework import serializers from api.models.Project import Project class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ['title', 'description', 'image', 'date'] Then, in views.py, I created two functions: project_list_view, which either lets you to GET all the Project objects from the database, or lets you POST a new object. And finally, project_detail_view, which lets you GET a Project object by typing in its pk (integer id). These are my two functions: @api_view(['GET', 'POST']) def project_list_view(request): if request.method == 'GET': projects = Project.objects.all() serializer = ProjectSerializer(projects, many=True) return Response(serializer.data) elif request.method == "POST": serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def project_detail_view(request, pk): if request.method == "GET": try: project = Project.objects.get(pk = pk) serializer = ProjectSerializer(project, many = False) return Response(serializer.data, status = status.HTTP_200_OK) except: return Response(status=status.HTTP_404_NOT_FOUND) The GET from … -
Relation doesn't exist in django restframework
I am creating one crud operation in django restframework and I have created project name "portfolio" and app "stock" and store in postgres database Here is my code. stock.models.py from django.db import models class Stocks(models.Model): Name = models.CharField(max_length=50) Number_of_Share = models.IntegerField() Unit_Price = models.IntegerField() ShareValue=models.IntegerField() Total_Share_Value= models.IntegerField() stock.serializers.py from rest_framework import serializers from .models import Stocks class StocksSerializer(serializers.ModelSerializer): class Meta: model =Stocks fields = '__all__' stock.viewset.py from rest_framework import viewsets from .models import Stocks from . import serializers class StockViewset(viewsets.ModelViewSet): queryset = Stocks.objects.all() serializer_class = serializers.StocksSerializer portfolio.router.py from stock.viewsets import StockViewset from rest_framework import routers router = routers.DefaultRouter() router.register('Stocks',StockViewset) portfolio.urls.py from django.urls import path, include from .router import router urlpatterns = [ # path('admin/', admin.site.urls), path('portfolio/',include(router.urls)) ] But I am facing this error. Exception Type: ProgrammingError Exception Value: relation "stock_stocks" does not exist LINE 1: ...reValue", "stock_stocks"."Total_Share_Value" FROM "stock_sto... Please help me solve this error. -
How to connect to ElastiCache instance (Redis) from Django App running on local machine
I'm struggling to find a solution to properly set connexion between my Django app running on my local machine and my ElastiCache instance Let me resume the situation. CONFIG: I have a Django App deployed on an AWS EC2 instance and running using a docker-compose-yml file. I'm using ElastiCache & Redis for my cache. MY ISSUE: I can successfully connect to my ElastiCache Instance from my EC2 instance. I can use Redis and create key etc.. Everything working perfectly. I am able to connect to ElastiCache from my Django App when I run it with my docker-compose.yml file within my EC2 Instance. I can also use Redis on my ElastiCache from my local machine by creating a sort of bridge with my EC2 instance using this command: ssh -f -N -L 6379:{my_elasticache_amazon_url}:6379 ec2-user@{my_ec2_instance_url} Then I run the following command and have access to redis: redis-cli -h 127.0.0.1 -p 6379 127.0.0.1:6379> But I can't access to ElastiCache from my Django App running on my local machine! I need to set this connexion for dev and test purpose, before deploying it on the EC2 instance. WHERE I AM: I tried to directly connect to ElastiCache using the URL in the Django App … -
How can i add Viusal studio build tools in dependencies in heroku requirements?
i'm tryng to build a web app for my master thesis. I'm using django. I used the package cvxpy (cvxpy) of python that need the visual studio build tools for python 3 to be installed. I have two problem: 1) how can i install this tools on a python venv? 2) how can i declare in requirements.txt for heroku the need of visual studio build tools ? Thanks PS i had not problem to install and use visul studio build tools in my local machine without venv. -
heroku run python manage.py makemigrations -a myapp takes forever
I have added this to my setting.py DATABASE_URL = os.environ.get('DATABASE_URL') db_from_env = dj_database_url.config(default=DATABASE_URL) DATABASES['default'].update(db_from_env) and yet when I run heroku run python manage.py makemigrations -a myapp it stucks in connecting process. Does anyone know how to solve this? -
401 "Unauthorized" error in Django File Upload
I have created a Django and Angular application to upload files. It was working without errors until I integrated a login page. I have not been able to upload files since integration. I get 401 - "Unauthorized" error. What could have possibly gone wrong? Thank you -
Django Raw SQL query outputting me objects instead of actual data
I'm trying to run raw SQL because i'm fed up with Django's QuerySet. So i thought it would be easy to run raw sql, but apparently not. Here is what i'm trying to run: test_raw = CsmSecurityPrice.objects.raw("SELECT SEC_ID, PRICE, PRICE_DATE FROM dbo.CSM_SECURITY_PRICE WHERE SEC_ID = 1093772 ORDER BY PRICE_DATE DESC")[:] for p in test_raw: print(p) Here is the horrendous output i get: CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772)..... The query works wonder in SQL SERVER MANAGEMENT STUDIO.