Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating Vite (VueJs) frontend with Django Login Form
I am looking to understand how once it is checked that a user is authenticated using a django login form, how they can then be taken to a vue frontend made using vite? Many examples I have seen make use of webpack loader however, I am using vite. I am developing locally, so is it a matter of just directing the user to a local server url only if authenticated? The idea is depending on the authenticated user, certain information will need to be gathered associated with them. -
How to send audio file from front end to django backend through websockets for processing at the backend
I have made a website in django that uses websockets to perform certain tasks as follows : From frontend I want to take audio using MediaRecorder as input api through javascript I want to send this audio back to the backend for processing and that processed data is again send back through the connection in realtime. I have tried various things for the purpose but haven't been successful yet. The bytes data that I've been receiving at the backend when I'm converting that into audio then I'm getting the length and size of the audio file but not getting the content of the file. Means the whole audio is silent but the same audio which I'm listening in the frontend is having some sound. but I don't know what's happening at the backend with the file. Consumer.py : import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["username"] self.room_group_name = "realtime_%s" % self.room_name self.channel_layer.group_add( self.room_group_name, self.channel_name) await self.accept() print("Connected") async def disconnect(self , close_code): await self.channel_layer.group_discard( self.roomGroupName , self.channel_layer ) print("Disconnected") async def receive(self, bytes_data): with open('myfile.wav', mode='bx') as f: f.write(bytes_data) audio.js : <script> navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { if (!MediaRecorder.isTypeSupported('audio/webm')) return alert('Browser not supported') … -
Isolation level doesn't change even if setting "SERIALIZABLE" to 'OPTIONS' in settings.py in Django
Following the documentation, I set SERIALIZABLE isolation level to 'OPTIONS' in settings.py for PostgreSQL as shown below. *I use Django 3.2.16 on Windows 11: # "settings.py" import psycopg2.extensions DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', }, 'OPTIONS': { # ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Here ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE, }, } Then, I created person table with id and name with models.py as shown below: person table: id name 1 John 2 David # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) Then, I created and ran the test code of non-repeatable read which runs two transactions with two threads concurrently as shown below: # "store/views.py" from django.db import transaction from time import sleep from .models import Person from threading import Thread from django.http import HttpResponse @transaction.atomic def transaction1(flow): while True: while True: if flow[0] == "Step 1": sleep(0.1) print("<T1", flow[0] + ">", "BEGIN") flow[0] = "Step 2" break while True: if flow[0] == "Step 2": sleep(0.1) print("<T1", flow[0] + ">", "SELECT") person = Person.objects.get(id=2) print(person.id, person.name) flow[0] = "Step 3" break while True: if flow[0] == "Step 6": sleep(0.1) print("<T1", flow[0] … -
Why can't I add a photo in the Django admin panel
I'm making a Django store site and I have a product class that includes an "image" field. I am using Models.ImageField and adding any! photos(I installed the Pillov library), pictures, the admin panel gives an error. I am attaching the class Product(models.penter image description herey), from django.db import models from django.urls import reverse # Create your models here. # class Shop_element(models.Model): name_element = models.CharField('Название товара', max_length=100, default='') description_element = models.TextField('Описание товара', max_length=250, default='') id_element = models.IntegerField('Уникальный id,не должен повторяться', max_length=10) #count_element = models. def __str__(self): return self.title class meta(): verbose_name = 'Товар' verbose_name_Plural = 'Товары' class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.PROTECT) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d') # description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_detail', args=[self.id, self.slug]) Tried to fix it myself but failed. -
django htmx change hx-get url after user input from radio buttons
This is forms.py: class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs = { "hx_get": reverse("planner:detail", kwargs={"slug": self.instance.venue}), "hx_target": "#services", } class Meta: model = Order fields = ["venue"] widgets = {"venue": forms.RadioSelect()} HTML: <div id="venue-options" class="p-3"> {% crispy form %} </div> This is the error when you click one of the radio buttons: The current path, planner/detail/None/, matched the last one. It says None/ because when you join the page none of the radio buttons are clicked so there is no slug to replace it. I need a way to replace None with the slug / id of the object chosen by the user. I need the url to be changed everytime the choise is changed. I am open to using apline.js but i would like a way of doing it in htmx/django. Thank you so much. -
What are these weird symbols in bash terminal in vs code. I am working with Django. How to fixed it?
$ python manage.py migrate ?[36;1mOperations to perform:?[0m ?[1m Apply all migrations: ?[0madmin, auth, contenttypes, my_app, sessions ?[36;1mRunning migrations:?[0m Applying my_app.0001_initial...?[32;1m OK?[0m Tried to make it look like this. -
Validate models in django admin with inlines (when I save several models at the time)
I'm maiking a quiz on django. On the picture below you can see 3 models (Quiz, QuizQuestionQuizAnswer) on 1 page. I used NestedStackedInline and NestedTabularInline for that. I need to need validate quiz before save. For example: I need to check if at least one answer is marked as correct. If answers more than one. etc models.py class Quiz(models.Model): title = models.CharField('Название теста', max_length=200) description = models.TextField('Описание', max_length=2000, blank=True) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) pass_score = models.PositiveIntegerField(help_text='Минимальный результат (в процентах) для прохождения теста', default=60, validators=[ MaxValueValidator(100), ]) created_at = models.DateTimeField('Дата создания', auto_now_add=True, ) updated_at = models.DateTimeField('Дата обновления', auto_now=True, ) def get_quiz_question(self): return self.quizquestion_set.all() def __str__(self): return self.title class QuizQuestion(models.Model): """ Вопросы для квиза""" quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.CharField('Вопрос', max_length=1000) created_at = models.DateTimeField('Дата создания', auto_now_add=True, ) updated_at = models.DateTimeField('Дата обновления', auto_now=True, ) def __str__(self): return self.question class Meta: verbose_name = 'Тест' verbose_name_plural = 'Тесты' class QuizAnswer(models.Model): """ Варианты ответов """ question = models.ForeignKey(QuizQuestion, on_delete=models.CASCADE) text = models.CharField('Варианты ответа', max_length=250) is_correct = models.BooleanField('Отметьте правильные', default=False) class Meta: verbose_name = 'Ответ' verbose_name_plural = 'Ответы' def __str__(self): return f'Вариант ответа' admins.py from quiz.models import * from django.contrib import admin from nested_inline.admin import NestedStackedInline, NestedModelAdmin, NestedTabularInline class AnswerInLine(NestedTabularInline): """ Делаем вложенную модель в админке""" … -
is it good to use flask api with django rest framework?
I and my friend was discussing a project idea and I wanted to do it using DRF with vue.js on the front end. then he told me that using flask API with DRF will make the performance better. I really don't remember how and why. do you agree with him and why? -
Hide specific field in drf_yasg django swagger documentation
I have a project with drf_yasg, there is a serializer with a to_internal_value method which is writing a field('mobile_operator_codes') for me. The field is overriden, so we don't need to input it in request. Though we need to output it in response. Documentation(drf_yasg) takes fields='all' and writes everything in request, though we don't need the 'mobile_operator_codes' in request blog. We don't expect it in the request. Serializer is as follows: class ClientSerializer(serializers.ModelSerializer): tags = ClientTagsField(required=False) mobile_operator_code = serializers.CharField(required=False) class Meta: model = Client fields = '__all__' def to_internal_value(self, data): data_overriden = data.copy() if 'phone' in data: data_overriden['mobile_operator_code'] = get_operator_code_from_phone(data['phone']) return super().to_internal_value(data_overriden) View is as follows: class CreateClientView(mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = ClientSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Model: class Client(models.Model): phone = models.CharField(max_length=11, verbose_name="номер телефона клиента") mobile_operator_code = models.CharField(max_length=3, verbose_name="код мобильного оператора") tags = models.JSONField(null=True, blank=True, verbose_name="теги") timezone = models.CharField(max_length=50, verbose_name="временная зона") # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones def __str__(self): return str(self.phone) + ' ' + str(self.tags) if self.tags else str(self.phone) Swagger documentation: swagger documentation What I tried: read_only in field makes this field not writeble by to_internal_value excluding the field from fields just puts empty value in it(given (required=False)) you cannot use different serializer, because you will still have to … -
Django forms: how to use optional arguments in form class
I'm building a Django web-app which has page create and edit functionality. I create the page and edit the pages using 2 arguments: page title and page contents. Since the edit and create code is very similar except that the edit code doesn't let you change the title of the page I want to make some code that can do both depending on the input. This is the current code I'm using right now. class createPageForm(forms.Form): page_name = forms.CharField() page_contents = forms.CharField(widget=forms.Textarea()) class editPageForm(forms.Form): page_name = forms.CharField(disabled=True) page_contents = forms.CharField(widget=forms.Textarea()) I know that if I wasn't using classes, but functions I could do something like this: def PageForm(forms.Form, disabled=False): page_name = forms.CharField(disabled=disabled) page_contents = forms.CharField(widget=forms.Textarea()) PageForm(disabled=True) PageForm(disabled=False) That is the kind of functionality I'm looking for^^ I tried the following: class PageForm(forms.Form): def __init__(self, disabled=False): self.page_name = forms.CharField(disabled=disabled) self.page_contents = forms.CharField(widget=forms.Textarea()) class PageForm(forms.Form, disabled=False): page_name = forms.CharField(disabled=disabled) page_contents = forms.CharField(widget=forms.Textarea()) Both didn't work and got different errors I couldn't get around. I was hoping someone could lead me in the right direction, since I'm not very familiar with classes. -
Can't set up stripe payment method
I'm trying to finish the payment feature on my app, first time trying to do this following a tutorial by Bryan Dunn. I added a SITE_URL like he did but I don't know if I need that since I added a proxy on my package.json and using axios to make api calls, I can use axios instead in this case? And when I click on "Proceed to checkout" button the url doesn't work, I tried changing it to a form.control, it gets redirected to the url but the stripe prebuilt form and product not showing up either. urls: urlpatterns = [ path('', views.getRoutes, name="get-routes"), path('users/register/', views.registerUser, name="register"), path('users/login/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('products/', views.getProducts, name="get-products"), path('products/<str:pk>', views.getProduct, name="get-product"), path('user/profile/', views.getUserProfile, name="get-user-profile"), path('users/', views.getUsers, name="get-users"), path('search/', ProductFilter.as_view(), name="search-product"), path('create-checkout-session/', StripeCheckoutView.as_view()), ] views: class StripeCheckoutView(APIView): def post(self, request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'currency': 'usd', 'price': 'price_1MAtSLJU3RVFqD4TnNYWOxPO', 'quantity': 1, }, ], payment_method_types=['card'], mode='payment', success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.SITE_URL + '/' + '?canceled=true', ) return redirect(checkout_session.url) except: return Response( {'error': 'Something went wrong when creating stripe checkout session'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) cartScreen.js: import React, { useEffect } from "react"; import { Link } from "react-router-dom"; import { Row, Col, Image, ListGroup, Button, Card, Form, } from … -
django How to pass the value returned by ajax to select option?
` <select id='user' class="form-control select2" data-toggle="select2" name="user" required > {% for u in users %} <option value="{{u.id}}" {% ifequal ??? u.id %}selected{% endifequal %}>{{u.username}}</option> {% endfor %} </select> ` $.ajax({ type: 'get', url: "{% url 'list:list_user' %}", dataType: 'json', data: {'u_id': u_id}, success: function(result){ $("#user").val(result.user); }, error: function(){ alert("false"); } }); How to pass the value returned by ajax to select option ??? I was having some trouble designing the edit form, I want select can use the value returned by ajax to select the corresponding text. -
Forgot to migrate free tier Postgres and now my app is empty
My project is again live no problems whatsoever, but the database is empty. I am either trying to restore an old backup to the new Postgres instance or upload a backup from my local disk. But I can’t find any way to do it and I feel a little bit lost. I tried to do pg:restore but I don’t know where to grab the backup (from the free heroKu tier). Hope my ask is clear fellas! Any guide it’s deeply appreciated! -
Comparing django database data with a custom python function not working (Django)
I'm trying to retrieve reserved appointments from database in Django and compare them with custom dates which I have created with a custom function. The problem is that it will work only for the first day and the other days it will copy the appointments from the first day. Please check the images and the code. I think the problem is when I compare using the for loop with jinja in template. {% for date in dates %} <div class="py-2 pr-4"> <button onclick="document.getElementById('id01').style.display='block'" class=""> {{date}}</button> <!-- The Modal --> <div id="id01" class="w3-modal"> <div class="w3-modal-content"> <div class="w3-container"> <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">&times;</span> <h1 class="font-medium leading-tight text-5xl mt-0 mb-2 text-black">Not Available</h1><br><br> <!--Displaying Timeslots--> <!--I think that the problem is here --> {% for a in app %} {% if a.date|date:"c" == date%} {{a.time}}<br> {% endif %} {% endfor %} <br><br> </div> </div> </div> </div> {% endfor %} Please also see the images . all dates generated this appointments are reserved only on the first date,but appears in each date -
How to run Python server in Kubernetes
I have the following Dockerfile which I need to create an image and run as a kubernetes deployment ARG PYTHON_VERSION=3.7 FROM python:${PYTHON_VERSION} ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ARG USERID ARG USERNAME WORKDIR /code COPY requirements.txt ./ COPY manage.py ./ RUN pip install -r requirements.txt RUN useradd -u "${USERID:-1001}" "${USERNAME:-jananath}" USER "${USERNAME:-jananath}" EXPOSE 8080 COPY . /code/ RUN pwd RUN ls ENV PATH="/code/bin:${PATH}" # CMD bash ENTRYPOINT ["/usr/local/bin/python"] # CMD ["manage.py", "runserver", "0.0.0.0:8080"] And I create the image, tag it and pushed to my private repository. And I have the kubernetes manifest file as below: apiVersion: apps/v1 kind: Deployment metadata: labels: tier: my-app name: my-app namespace: my-app spec: replicas: 1 selector: matchLabels: tier: my-app template: metadata: labels: tier: my-app spec: containers: - name: my-app image: "<RETRACTED>.dkr.ecr.eu-central-1.amazonaws.com/my-ecr:webv1.11" imagePullPolicy: Always args: - "manage.py" - "runserver" - "0.0.0.0:8080" env: - name: HOST_POSTGRES valueFrom: configMapKeyRef: key: HOST_POSTGRES name: my-app - name: POSTGRES_DB valueFrom: configMapKeyRef: key: POSTGRES_DB name: my-app - name: POSTGRES_USER valueFrom: configMapKeyRef: key: POSTGRES_USER name: my-app - name: USERID valueFrom: configMapKeyRef: key: USERID name: my-app - name: USERNAME valueFrom: configMapKeyRef: key: USERNAME name: my-app - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: key: POSTGRES_PASSWORD name: my-app ports: - containerPort: 8080 resources: limits: cpu: 1000m memory: 1000Mi requests: cpu: … -
Django Templates Not Updating with CSS Changes
I am currently working on a project using Django and Django Templates, and this also is my first time ever using Django. For this project, I had to overhaul a lot of the design and change a lot of the CSS in the static files. I had previously been running the server on the same Google profile for a while. However, after completing my changes, and running the server on that same Google profile, none of the changes I've made is displayed. However, when I run the server on a guest account, change my Google profile, or run the server on Safari, the changes show. I'm curious to know why this is happening. -
Django, Random migration errors when trying to sync to new Database (PostgreSQL)
I'm currently following a backend tutorial and now were installing postgreSQL into our Django project. But i cannot migrate because of some (for me) random errors. PS: I did install psycopg2 and Pillow. ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd The Errors: PS E:\pythondjango_course\Django\myproject> python manage.py migrate Traceback (most recent call last): File "E:\python\Lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "E:\python\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection connection = Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\pythondjango_course\Django\myproject\manage.py", line 22, in <module> main() File "E:\pythondjango_course\Django\myproject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\python\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "E:\python\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\python\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "E:\python\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) … -
Filtering on multiple fields in an Elasticsearch ObjectField()
I am having trouble figuring out the filtering syntax for ObjectFields() in django-elasticsearch-dsl. In particular, when I try to filter on multiple subfields of the same ObjectField(), I'm getting incorrect results. For example, consider the following document class ItemDocument(Document): product = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField() }) details = fields.ObjectField(properties={ 'category_id': fields.IntegerField(), 'id': fields.IntegerField(), 'value': fields.FloatField() }) description = fields.TextField() I want to find an Item with a detail object that has both category_id == 3 and value < 1.5, so I created the following query x = ItemDocument.search().filter(Q("match",details__category_id=3) & Q("range",details__value={'lt':1.5})).execute() Unfortunately, this returns all items which have a detail object with category_id==3 and a separate detail object with value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 20.0 }, { "category_id": 4, "id": 7, "value": 1.0 }, ... ] } instead of my desired result of all items that have a detail object with both category_id==3 AND value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 1.0 }, ... ] } How do I properly format this query using django-elasticsearch-dsl? -
Where the .env keys get stored after the nom build command in react?
Hello guys I build a react application using Django as the backend and having many keys at.env file. Now when I build the react app with the ‘npm run build’ command it builds the index file with CSS in the build folder. But where it stores all the keys of the .env file which were used in some components. Or its gets build with all the components -
django-simple-history: How to optimize history diffing?
I am using djangorestframework to display model history alongside which fields have been altered. To add history to my models, HistoricalRecords is being inherited through a modelmixin as shown in docs. Everything is working fine but i have a lot of similar queries (10) and duplicate queries (2). Is there a possible way to optimize this logic (i am out of options) ? // viewsets.py class BaseHistoryModelViewset(viewsets.ModelViewSet): """ Inherit this class to add path '.../history/' to your viewset """ @action(methods=["get"], detail=False, url_path="history") def results_history(self, request, *args, **kwargs): if "simple_history" in settings.INSTALLED_APPS: qs = self.queryset class HistoryModelSerializer(serializers.ModelSerializer): list_changes = serializers.SerializerMethodField() def get_list_changes(self, obj): # Optimize this logic here. if obj.prev_record: delta = obj.diff_against(obj.prev_record) for change in delta.changes: yield change.field, change.old, change.new return None class Meta: model = qs.model.history.model fields = ["history_id", "history_date", "history_user", "get_history_type_display", "list_changes"] serializer = HistoryModelSerializer( qs.model.history.all(), many=True) return Response(serializer.data) return Response(status=status.HTTP_404_NOT_FOUND) // output [ { "history_id": 6, "history_date": "2022-12-04T15:15:09.533340Z", "history_user": 2, "get_history_type_display": "Changed", "list_changes": [ [ "last_login", null, "2022-12-04T15:15:09.516601Z" ] ] }, ... ] -
How to perform a mathematical operation on two instances of object in Django?
I want to add two numbers from two different objects. Here is a simplified version. I have two integers and I multiply those to get multiplied . models.py: class ModelA(models.Model): number_a = models.IntegerField(default=1, null=True, blank=True) number_b = models.IntegerField(default=1, null=True, blank=True) def multiplied(self): return self.number_a * self.number_b views.py: @login_required def homeview(request): numbers = ModelA.objects.all() context = { 'numbers': numbers, } return TemplateResponse... What I'm trying to do is basically multiplied + multiplied in the template but I simply can't figure out how to do it since I first have to loop through the objects. So if I had 2 instances of ModelA and two 'multiplied' values of 100 I want to display 200 in the template. Is this possible? -
How can I write this sql query in django orm?
I have a sql query that works like this, but I couldn't figure out how to write this query in django. Can you help me ? select datetime, array_to_json(array_agg(json_build_object(parameter, raw))) as parameters from dbp_istasyondata group by 1 order by 1; -
http://127.0.0.1:8000 does not match any trusted origins. Docker Django Nginx Gunicorn
I try to log in to the site admin, but display this. I have no clue, this is my code, can someone help me out!!! My All Code Here -
Django rest framework. How i can create endpoint for updating model field in bd?
I wanted to create an endpoint for article_views and update this field in db. I want to change this field on frontend and update it on db. When I go to url(articles/<int:pk>/counter) I want article_views + 1. model.py: Class Articles(models.Model): class Meta: ordering = ["-publish_date"] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255, unique=True) content = models.TextField() annonce = models.TextField(max_length=255, null=True) publisher = models.ForeignKey(User, on_delete= models.DO_NOTHING,related_name='blog_posts') publish_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) article_views = models.PositiveBigIntegerField(default=0) serializers.py: class ArticlesSerializer(serializers.ModelSerializer): tags = TagsField(source="get_tags") author = ProfileSerializer(source="author_id") class Meta: model = Articles fields = ('id','title', 'author', 'tags','annonce', 'content', 'categories', 'article_views') views.py class ArticlesViewSet(viewsets.ModelViewSet): queryset = Articles.objects.all().order_by('title') serializer_class = ArticlesSerializer -
CIDC with BitBucket, Docker Image and Azure
I am learning CICD and Docker. So far I have managed to successfully create a docker image using the code below: Dockerfile # Docker Operating System FROM python:3-slim-buster # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 #App folder on Slim OS WORKDIR /app # Install pip requirements COPY requirements.txt requirements.txt RUN python -m pip install --upgrade pip pip install -r requirements.txt #Copy Files to App folder COPY . /app docker-compose.yml version: '3.4' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 My code is on BitBucket and I have a pipeline file as follows: bitbucket-pipelines.yml image: atlassian/default-image:2 pipelines: branches: master: - step: name: Build And Publish To Azure services: - docker script: - docker login -u $AZURE_USER -p $AZURE_PASS xxx.azurecr.io - docker build -t xxx.azurecr.io . - docker push xxx.azurecr.io With xxx being the Container registry on Azure. When the pipeline job runs I am getting denied: requested access to the resource is denied error on BitBucket. What did I not do correctly? Thanks.