Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Django and GRPC same application
I'm working on the Django rest framework project and I need to work with gRPC as well. But I don't know how to manage to run both HTTP server and gRPC server same time. Like in .NET it has option to listen both HTTP1 and HTTP2. When I use command python manage.py runserver then gRPC doesn't work and when I used python manage.py grpcserver then Rest API doesn't work Is there any solution to this problem? Thanks. I used packages: djangorestframework and django-grpc -
Traces inside a celery task are logged in console but not reported to Jaeger backend
So in our company we are using Django as the backend web framework and have heavily used celery for backgroun processing and now we want to start implementing distributed tracing now that things are getting complex. We decided to go with Jaeger as the tracer, and have used django_opentracing to auto instrument our existing codebase. Things work perfectly for a normal request and we can see traces in jaeger ui but when a api request triggers a celery task in background, in the console logs we can see that jaeger is sending traces but they are not visible in the ui. Following django_opentracing doc below is our code setup. # settings.py file # ... # OpenTracing settings OPENTRACING_TRACE_ALL = True OPENTRACING_TRACED_ATTRIBUTES = ['META', 'body', 'path', 'path_info', 'method', 'FILES', 'headers'] def get_tracer(): from jaeger_client import Config config = Config( config={ # usually read from some yaml config 'sampler': { 'type': 'const', 'param': 1, }, 'local_agent': { 'reporting_host': '127.0.0.1', 'reporting_port': '5775' }, 'logging': True, }, service_name='optimus-store', validate=True, ) return config.initialize_tracer() tracer = get_tracer() OPENTRACING_TRACING = django_opentracing.DjangoTracing(tracer) from opentracing_instrumentation.client_hooks import install_all_patches install_all_patches() # Opentracing settings end ... other settings stuff My celery file for django project, import os from celery import Celery from … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use product_variation.set() instead
I am new to Django and didn't find any reference regarding this issue. I am getting this error when i use many to many field in Django model. Im trying to add ProductVariationCategory to ProductVariation and then to products. and i get following error : Direct assignment to the forward side of a many-to-many set is prohibited. Use product_variation.set() instead. here is my models.py class Product(models.Model): headline = models.CharField(max_length=150) product_variation = models.ManyToManyField(ProductVariation, blank=True) class ProductVariationCategory(models.Model): headline = models.CharField(max_length=255, default="") class ProductVariation(models.Model): category = models.ForeignKey(ProductVariationCategory, on_delete=models.SET_NULL, null=True) headline = models.CharField(max_length=255, default='') and here is my views.py* product_variation_categories, _ = ProductVariationCategory.objects.get_or_create(headline=product_variation_category) product_variations, _ = ProductVariation.objects.get_or_create(headline=product_variation, category=product_variation_categories) products, _ = Product.objects.get_or_create(product_variation=product_variations) im trying to assign productvariation with its relations to products. any idea? -
Not able to establish connection with Heroku Redis using Django channels_redis
I'm using Django Channels in my app to make a person to person chat function. For this I'm using Django Channels channel layers that uses 'Redis' as a backing store. I have following configuration in the settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', ("localhost", 6379))], }, }, } The CHANNEL_LAYERS is working fine for development when 'hosts' points to localhost. However for production, when I'm trying to make sure that the channel layer can communicate with Redis on Heroku it does not work. Using code as giving in Channels Docs as shown below, gives the following error import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.7/site-packages/asgiref/sync.py", line 223, in __call__ return call_result.result() File "/app/.heroku/python/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/app/.heroku/python/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/app/.heroku/python/lib/python3.7/site-packages/asgiref/sync.py", line 292, in main_wrap result = await self.awaitable(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 299, in send async with self.connection(index) as connection: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 835, in __aenter__ self.conn = await self.pool.pop() File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 73, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "/app/.heroku/python/lib/python3.7/site-packages/aioredis/commands/__init__.py", line 175, in create_redis loop=loop) … -
what is the meaning of request.POST['first'] and this is predefined dictionary and what will be value of 'first' key?
request.POST['first'] has POST[] dictionary made in request object and what will be the value of 'first' key? -
Get the value of a list to upload an Image on a djanog models
I need some help with a question, I'm currently working on a django project and I have a models like this : CATEGORY = ( ('raw', 'raw'), ('jpg', 'jpg'), ('psd', 'psd') ) Row = ( ('Homepage1', 'Homepage1'), ('Homepage2', 'Homepage2'), ('Homepage3', 'Homepage3') ) name = models.CharField(null=True, max_length=200) album = models.ForeignKey(Album, on_delete=models.CASCADE) file = models.ImageField(upload_to=Row.__getattribute__, null=True, blank=True) file_type = models.CharField(max_length=200, null=True, choices=CATEGORY) is_favorite = models.BooleanField(default=False) date_uploaded = models.DateTimeField(default=now) def __str__(self): return str(self.album) + "ID.{:0>3}".format(self.id) How can I use the Row list to say where I would upload the Images, do I get it right ? by saying this : models.ImageField(upload_to=**Row.__getattribute__,** null=True, blank=True) ???? Thanks y'all in advance -
Please suggest some of file uploading JS library for VueJS
I want to have a loading based file file upload feature in Vuejs while uploading the file to Django backend. -
Django-fcm how to set senderId
I'm working with django-fcm and I'm getting a mismatch senderId error, here's how I'm sending messages devices = DeviceNotification.objects.filter(user__id__in=get_user_model().objects.filter_by_targeting(instance.targeting)) res = devices.send_message(title=instance.title_fr, body=instance.content_fr, data={"title": instance.title_fr, "body": instance.content_fr}) Is there a way to add senderId to send_message function? thanks. -
Is there a way to combine a list of querysets into a sql union?
Given a list of querysets, is it possible to combine them into a union? Ideally the Django API would allow something like this - union(*querysets) But as far as I can see a union is only possible like this - q1.union(*rest_of_querysets) So given this is the only way how can I get the first item of the list of querysets without evaluating it? At the moment I have this which doesn't work - q1 = querysets[0] # it is evaluated at this point so doesn't work q1.union(*querysets[1:], all=True) -
Django is not matching same query
Hi I am trying to match 2 same query print('{prd} match from {category} {tf}'.format(prd=p.category.subtitle, category=c.subtitle, tf=p.category==c.title)) Output: bullet-network-camera match from bullet-network-camera False -
How do I convert an API UTC time to local time (+13:00) and ensure it is correct?
I am trying to convert a datetime from an API that stores datetime values as UTC. I need to convert the datetime to my local time 'Pacific/Auckland' The API I am using is Sunrise-Sunset https://sunrise-sunset.org/api The specific location I am requesting is Christchurch, New Zealand https://sunrise-sunset.org/search?location=christchurch The below code outputs 2021-09-26T22:47:45+00:00 however I'm certain this is incorrect. (see below) import requests api_url = 'https://api.sunrise-sunset.org/json?lat=40.712784&lng=-74.005943&formatted=0' response = requests.get(api_url) if response.status_code == 200: sunset_today = response.json()['results']['sunset'] print(sunset_today) # outputs '2021-09-26T22:47:45+00:00' The reason I believe the printed value is incorrect is because when I subtract 13 hours from todays sunset time of Sunday 26 Sep 7:31:42 pm NZ time (+13:00) to get the UTC time I should get Sunday 26 Sep 06:31:42 UTC (+00:00) which is significantly different from the UTC value I am receiving. I have searched StackOverflow and Google extensively, but cannot seem to find a solution that fits my needs. There are two questions I'm asking Why am I getting an odd UTC value for the sunset time? How can I convert the correct result ('2021-09-26T06:31:41+00:00') to my local datetime ('Pacific/Auckland')? FYI, I don't want to add bloat to the application, but from previous (unsuccessful) attempts at solving this problem … -
Django Rest + Gunicorn, static files for admin are missing
I am running Django REST using gunicorn and serving it using NGINX. PROBLEM: Static files for admin are not served correctly while static files for API routes are. CONFIGURATION: docker-compose.yml drf: ...* volumes: - .:/code - static_files:/static_files depends_on: - postgres nginx: ...* volumes: - static_files:/static_files ports: - 8081:8081 nginx.conf server { listen 8081; server_name localhost; access_log /var/log/nginx/example.log; server_tokens off; include /etc/nginx/mime.types; location /static { autoindex off; alias /static_files/; } location ~ (api|admin) { proxy_pass http://drf:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } } Settings.py STATIC_URL = "/static/" STATIC_ROOT = "/static_files/" On deployment I also run the following command: python manage.py collectstatic I can see that API routes have static files served while /admin do not. However, files can be found inside the docker volume. And there is one log from nginx container where we can see that nginx is trying to access the right static file...: ADMIN SITE GET /static/admin/css/responsive.css HTTP/1.1" 404 API SITE GET /static/rest_framework/js/default.js HTTP/1.1" 200 -
CSS is not loading in Django Admin Panel App?
I have created my first Django project, but in the admin panel, when I run http://127.0.0.1:8000/admin/ the CSS files is not loaded and I also created a new Django app but still got the same error, I have also visited the question but my problem is not solved: Django admin site not showing CSS style It looks like this: I can log in: It should look like this: settings.py import os STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Note: I have used STATIC_ROOT = os.path.join(BASE_DIR, 'static') in settings.py and also run the command python manage.py collectstatic, but still, I got the same error. -
Django NoReverseMatch at /topic/ pk=
Hi i want to add the url for if user click and will go to delete page but i don't want i want to put in pk= i already try pk=topic.id but fail view.py class DeleteTopic(DeleteView): model = Topic success_url = reverse_lazy('index') html.py <a class="btn btn-danger" href="{% url 'delete_topic' pk= %}">Delete</a> urls.py path('topic/<int:pk>/delete', DeleteTopic.as_view(), name='delete_topic'), -
DoesNotExist: matching query does not exist
I'm writing models tests in django and here is my test: class StockTest(TransactionTestCase): def setUp(self): Stock.objects.create( product_id=Products.objects.get(product_id=1), date='2021-10-10', count=1) def test_stocks(self): stocks_milk = Stock.objects.get(count=1) stocks_cookies = Stock.objects.get(count=2) self.assertEqual( stocks_milk.__str__(), 1) self.assertEqual( stocks_cookies.__str__(), 2) and my model where product_id is a foreign key to Products: class Stock(models.Model): stock_id = models.AutoField(primary_key=True) date = models.DateField() count = models.IntegerField() product_id = models.ForeignKey(Products, models.DO_NOTHING, db_column='product_id') user = models.CharField(max_length=255) def __str__(self): return str(self.count) When I run a test I get the error: grocery_check.models.Products.DoesNotExist: Products matching query does not exist. How to get the id from Products table properly? -
having trouble updating some ManyToManyField using signals
When i create a new student, I would like for the studentlist field in Tutors and the taught_by field in Students to reflect the same values. ie add new student student list updated with name of student new lesson created with name as student i am really lost with the signals and what to put inside, especially with created or editign manytomanyfields the signals.py: @receiver(post_save, sender=Students) def createdStudentToLesson(sender, instance, created, **kwargs): if created: student = instance lesson = Lessons.objects.create( student = student ) print("lesson saved") the models.py: class Lessons(models.Model): student = models.ForeignKey(Students, on_delete=models.SET_NULL, null=True) headed_by = models.ForeignKey(Tutors, on_delete=models.SET_NULL, null=True) day = models.CharField(max_length=4, choices=DAY_CHOICES, null=True) start_time = models.TimeField(null=True, blank=True) type = models.CharField(max_length=7, choices=TYPE_CHOICES, null=True) price_band = models.CharField(max_length=7, choices=PAYMENT_TYPE_CHOICES, blank=True, null=True) created = models.DateTimeField(auto_now_add=True ) def __str__(self): return str(self.student) + " at " + str(self.start_time) class Meta: ordering=['student','start_time'] class Students(models.Model): name = models.CharField(max_length=200, null=True, blank=True) taught_by = models.ManyToManyField("Tutors", blank=True) school_year = models.CharField(max_length=2, choices=YEAR_CHOICES, null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) def __str__(self): return str(self.name) class Meta: ordering = [ "name" ] class Tutors(models.Model): name = models.CharField(max_length=200, null=True, blank=True) studentlist = models.ManyToManyField('Students', blank=True) lessonlist = models.ManyToManyField('Lessons', blank=True) short_bio = models.CharField(max_length=100,null=True, blank=True) rate = … -
How to return incomplete body errors in django?
class OrderViewSet(viewsets.ViewSet): def list(self, request): orders = Order.objects.all() return Response({ "code": "success", "orders": orders, }) def create(self, request): comment = request.data["comment"] product_id = request.data["product_id"] order = Order(comment=comment, product_id=product_id) order.save() return Response({ "code": "success", }) I would like to return error if product_id is not supplied by the user in request body: "code": "invalid-request", "details": { "product_id": { "type": "required", "message": "Product id is required", } } Also, there's KeyError if comment isn't supplied, but I don't want to make comment mandatory in request body. How do I set it to '' if its not supplied & still return success? Thanks -
Use view/form in Django to upload a multiple files
Class below is used to create a form in Django and get neccesary information. Problem is, it offers only one file to upload. I need to upload multiple files. I use Crispy forms. My simplified view.py looks like: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) HTML code: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Fill form</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} When I inspect page, object looks like: <input type="file" name="file_1" class="clearablefileinput form-control-file" id="id_file_1"> I want it to contain multiple atribute. How can I achive that? I can't get it to work using documentation (https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/). I have tried: widgets = {'file_1': form.ClearableFileInput(attrs={'multiple': True})} form.instance.file_1 = form.FileField(widget=form.ClearableFileInput(attrs={'multiple':True})) form.instance.file_1 = form.FileField(widget=form.FileInput(attrs={'multiple': True})) My models.py file_1 = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="File 1", validators=[validate_file_size], help_text="Allowed size is 50MB") I can't find an example how to implement multiple files upload which could be implemented in my class. -
How do I reactivate a django server?
I'm very new to django web development in python and I'm currently following a course on building a simple django website. The problem is, I went to sleep and decided to shut down my computer. And now I think I need to reactivate the website or something because the website just says 'This site can't be reached'. I opened up the code and I'm not sure if I'm suppose to write a certain command in the terminal or something. The terminal is empty when before it was running the website and had stuff there. I do understand that it is going to stopping running the website when I shut down my computer because it's my computer hosting it, but I just need to know how to start running it again. So how do I 're-activate' a django website? -
Django queryset custom order
I would like to make a queryset, which will first order by title then by size, but the size should be custom ordered, like the order in the list. For example order_size_ist = ['S', 'M', 'L', 'XL', 'XXL' ] queryset = RawMaterial.objects.order_by('title', 'size') The size should be ordered first S, then M then L and so on. Any ideas ? Thank you in advance :) -
Add intermediate model fields to reverse relationship
I have two related models (Product and Recipe). There is a many-to-many relationship defined between them (with a through model). I am able to query the 'through' model fields using the below serializer, but I am unable to make this work the other way around (from Product to Recipe) models.py: class Product(models.Model): version = models.CharField(max_length=4) displayname = models.CharField(max_length=50,validators=[alphanumeric]) ... class Recipe(models.Model): ... ingredients = models.ManyToManyField(Product, through='RecipeInput', related_name='recipe_input') products = models.ManyToManyField(Product, through='RecipeOutput',related_name='recipe_output') class RecipeInput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) amount_min = models.FloatField(blank=True, null=True) class RecipeOutput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) amount_min = models.FloatField(blank=True, null=True) mj = models.FloatField(blank=True, null=True) serializers.py: class RecipeInputSerializer(serializers.HyperlinkedModelSerializer): product_id = serializers.ReadOnlyField(source='product.id') product_name = serializers.ReadOnlyField(source='product.displayname') class Meta: model = RecipeInput fields = ('product_id',"product_name", 'amount', 'amount_min', ) class RecipeOutputSerializer(serializers.HyperlinkedModelSerializer): product_id = serializers.ReadOnlyField(source='product.id') product_name = serializers.ReadOnlyField(source='product.displayname') class Meta: model = RecipeOutput fields = ('product_id',"product_name", 'amount', 'amount_min', 'mj', ) class ProductInputSerializer(serializers.HyperlinkedModelSerializer): recipe_id = serializers.ReadOnlyField(source='recipe.id') recipe_name = serializers.ReadOnlyField(source='recipe.displayname') class Meta: model = RecipeInput fields = ('recipe_id','recipe_name', 'amount_min', 'amount', ) class RecipeSerializer(serializers.ModelSerializer): ingredients = RecipeInputSerializer(source='recipeinput_set', many=True) products = RecipeOutputSerializer(source='recipeoutput_set', many=True) class Meta: model = Recipe fields = "__all__" depth = 1 class ProductSerializer(serializers.ModelSerializer): products_in = ProductInputSerializer(source='recipe_input', many=True) class Meta: model = Product … -
Pip hangs on installing packages
I'm using django in a virtual environment. I'm using powershell and trying to install pyopenssl. I try pip install pyopenssl: (bookmarks) bookmarks> pip install pyopenssl Collecting pyopenssl Using cached https://files.pythonhosted.org/packages/b2/5e/06351ede29fd4899782ad335c2e02f1f862a887c20a3541f17c3fa1a3525/pyOpenSSL-20.0.1-py2.py3-none-any.whl Collecting six>=1.5.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/d9/5a/e7c31adbe875f2abbb91bd84cf2dc52d792b5a01506781dbcf25c91daf11/six-1.16.0-py2.py3-none-any.whl Collecting cryptography>=3.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz Installing build dependencies ... it hangs on Installing build dependencies .... I've waited 30mins but nothing happened. I've also tried python -m pip install pyopenssl (bookmarks) bookmarks> python -m pip install pyopenssl Collecting pyopenssl Using cached https://files.pythonhosted.org/packages/b2/5e/06351ede29fd4899782ad335c2e02f1f862a887c20a3541f17c3fa1a3525/pyOpenSSL-20.0.1-py2.py3-none-any.whl Collecting cryptography>=3.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz Installing build dependencies ... \ And when I try pip -v install pyopenssl: (Since the ouput is large, i'm only showing the last part.) Added semantic-version>=2.6.0 from https://files.pythonhosted.org/packages/a5/15/00ef3b7888a10363b7c402350eda3acf395ff05bebae312d1296e528516a/semantic_version-2.8.5-py2.py3-none-any.whl#sha256=45e4b32ee9d6d70ba5f440ec8cc5221074c7f4b0e8918bdab748cc37912440a9 (from setuptools-rust>=0.11.4) to build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' Removed semantic-version>=2.6.0 from https://files.pythonhosted.org/packages/a5/15/00ef3b7888a10363b7c402350eda3acf395ff05bebae312d1296e528516a/semantic_version-2.8.5-py2.py3-none-any.whl#sha256=45e4b32ee9d6d70ba5f440ec8cc5221074c7f4b0e8918bdab748cc37912440a9 (from setuptools-rust>=0.11.4) from build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' Installing collected packages: setuptools, wheel, pycparser, cffi, toml, semantic-version, setuptools-rust Creating C:\Users\Suhail\AppData\Local\Temp\pip-build-env-fwbrqqmx\overlay\Scripts Successfully installed cffi-1.14.6 pycparser-2.20 semantic-version-2.8.5 setuptools-58.1.0 setuptools-rust-0.12.1 toml-0.10.2 wheel-0.37.0 Cleaning up... Cleaned build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' 1 location(s) to search for versions of pip: * https://pypi.org/simple/pip/ Getting page https://pypi.org/simple/pip/ Found index url https://pypi.org/simple Looking up "https://pypi.org/simple/pip/" in the cache Request header has "max_age" as 0, cache bypassed Starting new HTTPS connection (1): pypi.org:443 https://pypi.org:443 "GET /simple/pip/ HTTP/1.1" … -
Django: How to add DeleteView and UpdateView
Hi I'm Student in django, i want to add UpdateView and DeleteView, can someone expert guys can help me to figure out (Forum website) :D i provide some of my views.py code class TopicView(View): def get(self, request, *args, **kwargs): tid = request.GET.get('id') print(tid) topic = Topic.objects.filter(id=tid).first() print(topic) # topic.clicks += 1 topic.save() username = check_result(request, topic) print(username) comments = topic.comments() content = create_content_paginator(request, queryset=comments, page_size=5) content.topic = topic return render( request, 'topic.html', context={'username': username, 'content': content, 'form': Form} ) @check_login def post(self, request, *args, **kwargs): topic_id = request.POST.get('topic', '') content = request.POST.get('content') topic = Topic.objects.filter(id=topic_id).first() username = check_result(request, topic) if content: user = UserInfo.objects.filter(username=username).first() comment = Comment(user=user, topic_id=topic_id, content=content) comment.save() comments = topic.comments() content = create_content_paginator(request, queryset=comments, page_size=5) content.topic = topic print(Form.errors) return render( request, 'topic.html', context={'username': username, 'content': content, 'form': Form} ) tid = Topic_id of post_id .. content = the content inside the topic class PublicView(View): @check_login def get(self, request, pid, *args, **kwargs): subject = Subject.objects.filter(id=pid).first() # semester = subject.semester username = request.session.get('name') return render( request, 'public.html', context={'username': username, 'form': Form, 'content': {'subject': subject}} ) @check_login def post(self, request, pid, *args, **kwargs): subject = Subject.objects.filter(id=pid).first() username = request.session.get('name') print(username,'asdasd') user = UserInfo.objects.filter(username=username).first() name = request.POST.get('title') content = request.POST.get('content') … -
Django: unable to make a calculation inside a template
I've created a e-commerce Django application and in the back office of this application, I have a page that is supposed to show some statisctics. I'm trying to display benefits or losses. For the costs, I've created a @property in the model as following: class Statistics(models.Model): """ The Statistics model represents the statistics that can be calculated """ costs_infra = models.FloatField(verbose_name="Costs Infrastructure") costs_salary = models.FloatField(verbose_name="Costs Salary") class Meta: verbose_name_plural = "Statistics" def __str__(self): """Unicode representation of Statistics""" return " Infra costs: {}, Salary costs: {}".format( self.costs_infra, self.costs_salary ) @property def calculate_costs(self): return self.costs_infra + self.costs_salary For the total income, I've calculated it inside a view as following: @group_required('Administrator', 'Manager') def stats_home(request): total_users = User.objects.all().count() costs = Statistics.objects.all() subscriptions_1month = Subscription.objects.get(plan_name='1 Month') subscriptions_1year = Subscription.objects.get(plan_name='1 Year') subscriptions_3year = Subscription.objects.get(plan_name='3 Years') user_subscriptions_1month = UserSubscription.objects.filter(subscription=subscriptions_1month).annotate(Count('user', distinct=True)).count() user_subscriptions_1year = UserSubscription.objects.filter(subscription=subscriptions_1year).annotate(Count('user', distinct=True)).count() user_subscriptions_3years = UserSubscription.objects.filter(subscription=subscriptions_3year).annotate(Count('user', distinct=True)).count() income_per_subscription_1month = Subscription.objects.get(plan_name='1 Month').price * UserSubscription.objects.filter(subscription=subscriptions_1month).count() income_per_subscription_1year = Subscription.objects.get(plan_name='1 Year').price * UserSubscription.objects.filter(subscription=subscriptions_1year).count() income_per_subscription_3years = Subscription.objects.get(plan_name='3 Years').price * UserSubscription.objects.filter(subscription=subscriptions_3year).count() total_income = income_per_subscription_1month + income_per_subscription_1year + income_per_subscription_3years return render (request, "stats_home.html", locals()) An finally, I'm trying to make a simple calculation (total income - total costs) but I'm unable to do this inside the template, as far as I could see … -
how to use external webcam as an image scanner to save into the database?
I'm trying to use an external webcam as an image scanner, is'nt there a way to achieve that please , im using django as backend **3.2 version ** this is my models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) i have to instead of scan documents , just capture a picture of them from my web browser and upload them ? i know i have to use js to access webcam , but i dont know how to save it into the database thank you in advance ..