Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why Django form show UnicodeEncodeError in Persian language?
I have simple form as below: forms.py: from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): print(form.cleaned_data) return HttpResponseRedirect('/') else: form = NameForm() return render(request, 'form.html', {'form': form}) form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> If I write English character and submit form, it works ok and execute print statement but if I write Persian character like'متن تست' it shows this error: UnicodeEncodeError at / 'charmap' codec can't encode characters in position 132-136: character maps to <undefined> Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Exception Type: UnicodeEncodeError Exception Value: 'charmap' codec can't encode characters in position 132-136: character maps to <undefined> Exception Location: C:\Program Files\Python311\Lib\encodings\cp1252.py, line 19, in encode Raised during: myapp.views.get_name Python Executable: C:\python\test1\venv\Scripts\python.exe Python Version: 3.11.2 Python Path: ['C:\\python\\test1', 'C:\\python\\test1', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.3.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\python\\test1\\venv', 'C:\\python\\test1\\venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 14 Mar 2023 19:06:06 +0000 The string that could not … -
Django auth_user programmingerror when running makemigrations or migrate command
I've searched for this problem over stackoverflow and most of the answers are just to run manage.py makemigrations and manage.py migrate but both those commands fail for me. Whenever I try to start my django application I run into the following error message: django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: SELECT "auth_user"."id" FROM "auth_user" Here is my settings.py: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'simple_history', 'drf_multiple_model', 'backend', 'corsheaders', 'authentication', 'pipeline', 'positions', 'request', ] I can fix this problem if I comment out all my urls in backend/urs.py except for my home url, then I can run makemigrations and migrate. After, I have to uncomment those urls and re-run both makemigrations and migrate. This is the backend/urls.py file: urlpatterns = [ path('', views.UsersListAPIView.as_view(), name="Get Users"), path('<int:pk>/', views.UsersDetailAPIView.as_view(), name="Get Users"), path('login/', views.UserLoginAPIView.as_view()), path('logout/', views.UserLogoutAPIView.as_view()) ] I know how to solve the problem I just don't want to have to do this every time I start my backend. I am going to be using docker containers and would like if the backend just started without issue. I have a migrations folder for every module that has a modules.py and each of these migrations folder have a init.py. Also … -
I have problem with csrf-token when I send reuest with axios
When I send request with axios to my server from 3000 port to 8000 I got 403 forbidden error. But when I send reqest from postman I don't have this error. I am using withCredentials param. And I got csrf token, but when I am sending request on login page I am getting 403 forbidden. How I can get sessionid? axios.get('http://localhost:8000/', { withCredentials: true }) .then((response) => { // const cookies = response.headers['Set-Cookie'] console.log('res', response); let csrf = document.cookie.split('=')[1] console.log('cookie', document.cookie); console.log(csrf); axios.post('http://localhost:8000/', { password: '12345678', username: 'admin@admin.com', csrfmiddlewaretoken: csrf // csrfmiddlewaretoken: 'Njqa9oV5mWmT6fjJhqOYNu8cZ23LgPWK' }, { headers: { // 'X-CSRFToken': csrf, // 'csrftoken': csrf // 'X-CSRFToken': 'Njqa9oV5mWmT6fjJhqOYNu8cZ23LgPWK', // 'X-CSRFToken': csrf, // 'Cookie': `csrftoken=${csrf}` }, withCredentials: true }) .then(res => { console.log('post res', res); console.log(document.cookie) // axios.get('http://localhost:8000/api/devices/v2/thermostats/', { axios.get('http://localhost:8000/api/devices/v2/thermostats/', { headers: { 'X-CSRFToken': csrf, }, withCredentials: true }) .then(res => { console.log('get', res); }) }) }); -
Django: Redirect doesn't work after paypal payment, how to do it right
just like in the title. The redirect is not working after making a paypal payment. The view itself executes correctly but at the end it does not redirect to the correct page. I solved it quite breakneckly by making another view and redirecting it like this window.location.href = "{% url 'order_complete' %}"; but it doesn't look very nice cart.html {% if not item_list %} <p>Cart is empty</p> {% elif user.if_address %} <p>Address is not complete</p> {% else %} <input type="radio" id="pickup" value="pickup" name="shipping" checked/>Personal Pickup <input type="radio" id="inpost" value="inpost" name="shipping"/>Inpost <div id="paypal-button-container"></div> {% endif %} </div> </div> </aside> </div> </div> </section> <script src="https://www.paypal.com/sdk/js?client-id=ASSy-9ZwcMqTUmhxXQbvWkM6gGMm0ZpY-fpQJoMxMTxXHU0qxKVerVhwZSGfJxqUleLOYu5YADkZbTH1&currency=USD"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = "{{ price }}" var url = "{% url 'Checkout' %}" var shippingMethod = "None" paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } }] }); }, onApprove: function(data, actions) { … -
Django form category not showing
I am writing a code for django blogging website it is complete but while adding section of categorizing the list of categories in drop down list in not coming why is that . please anyone help me its urgent for submission of minor project i tried everything i could this is my add post.html {%extends "base.html"%} {% block title %}Add Post{% endblock title %} {% block content %} <h1 style="text-align: center; font-family: 'Open Sans', sans-serif; font-size: 48px; font-weight: bold; color: rgb(174, 255, 229); text-transform: uppercase; letter-spacing: 4px;"> ADD YOUR POST HERE</h1> <table> {% if user.is_authenticated %} <form class="form-control" action="/add_post/" method="post"> {% csrf_token %} <div class="container " style="border:5px solid rgb(0, 0, 0) ; border-radius: 15px; background-color: white;"> {{form.as_p}} <div class="d-flex justify-content-center"> <button class="btn btn-outline-dark" style="position: relative; margin-bottom:20px ;" type="submit">Post</button> </div> </div> </form><br><br> {%endif%} </table> <div class="d-flex justify-content-start container"> <a class="btn btn-dark" style="position: relative;" href="{%url 'Home'%}">Back</a> </div> {% endblock %} this is my forms.py from dataclasses import fields from logging import PlaceHolder from operator import mod from tkinter.ttk import Widget from turtle import title from xml.etree.ElementTree import Comment from django import forms from .models import Post from .models import Comment from django import forms from .models import Category class PostForm(forms.ModelForm): class Meta: … -
Django - how to remove item from dictionary in template?
In my view in Django I have such a function def index(request): user_list = Users.objects.all() page = request.GET.get('page', 1) per_page = request.GET.get('per_page', 10) paginator = Paginator(user_list, per_page) total = paginator.count GET_params = request.GET.copy() try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'polls/index.html', { 'users': users, 'total': total, 'GET_params': GET_params}) In my template I try to use passed GET_params to pagination {% if GET_params %} <a href="?{{GET_params.urlencode}}&page={{ i }}">{{ i }}</a> {% else %} <a href="?page={{ i }}">{{ i }}</a> {% endif %} The reason for what I am doing is that i need to pass many parameters like per_page and page in one URL. The problem is, that above code works by multiply page parameters in every single click of url: /?page=1&page=2&page=3... Is there any way to remove from GET_params dictionary (in template!) all values by given key name? I've tried to remove values from GET_params in a view, but it is not the correct way, because I need a last value of all GET parameters in every request. -
Django gives Field error when passed in a function. Django
I want to order the albums with the 10 highest reviews, but when I order by the function "averageReview' it gives me a field error, what is the solution? views: def homeview(request): highest_rated = albums.objects.order_by('-averageReview')[9] album = albums.objects.all() return render(request, "home/home.html", {'albums' : album, 'highest_rated' : highest_rated }) models: class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') @classmethod def averageReview(self): reviews = ReviewRating.objects.filter(album=self, status=True).aggregate(average=Avg('rating')) avg = 0 if reviews['average'] is not None: avg = float(reviews['average']) return avg def __str__(self): return self.title class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=1500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject or f"ReviewRating #{self.pk}" -
Django app works when URLconf is empty, but sub directories are not being routed to Django
There are a lot of questions here regarding the urls.py issues with Django. A lot seems to depend on how the web server is set up. Running locally in development mode, I get no problems with my Django app, but onced deployed to the webserver, it fails. the project urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('search.urls')), path('admin/', admin.site.urls), ] the app urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.search, name='search'), path('search/', views.search, name='search'), ] views.py def search(request): return HttpResponse("You're at the search page.") The empty path works domain.com/app/ the 'include("search.urls")' works, but the path domain.com/app/search/ and 'domain.com/app/admin' do not. Instead the '/app/search/' directs to a 404 not found page outside the django app. So there is something going on with the webserver that sub directories are not being routed to the Django app. Any help is appreciated. The app is running on a Linux Apache 2.4.55 shared hosting server. I have checked the raw error logs and other answers that were related to internal django urlconf issues but this seems to be outside of django. I am looking at this site: https://thecodelearners.com/deploy-django-web-application-to-apache-server-step-by-step-guide/#create_and_configure_conf_file_for_django_app But it is a … -
How to hash stored passwords in mysql using pbkdf2_sha256 using Django
I have list of user passwords stored as plain text. I think I need a script to run over the stored passwords and hash them. I'm new to Django and not sure where to start or how. I created login and creating accounts only works for new users: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email).first() if user_details and check_password(user_password, user_details.user_password): request.session['logged_in'] = True request.session['user_email'] = user_details.user_email request.session['u_id'] = user_details.user_email request.session['user_name'] = user_details.user_name request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') How can I make previous users log in without creating new accounts for them. -
Django inserting into mySQL database with validate_unique() and save() and a composite primary key
I am trying to insert data into a mySQL database directly from a Django web application I am building. The table I am trying to insert into is called Athlete_T and has a composite primary key value including: 'Fname', 'Lname', and 'DOB'... although Django only allows you to specify one primary key... In my models page I have 'Fname' set to the primary key, as well as a Meta class with a 'unique together' field including the primary key attributes that should specify what qualifies as unique upon inserting a new row into the table. Finally I have my views, where I am getting input from the user and setting all the values equal within an ORM query and using .save() to create a new database entry according to the information provided and entered by the user. According to Django documentation... I should be able to use "Model.validate_unique()" which should check the "unique together" field. I keep getting this error when trying to add a value that has the same "Fname" but the other primary key values are different. Does anyone have any ideas on how to fix this issue or what I am doing wrong? I have tried making … -
Django get context foreign key values
Hi i want to get the values of the foreign key of the object and return it as json models.py message_types = [('txt','text'),('img','image'),('stkr','sticker')] class Images(models.Model): image = models.ImageField(upload_to='static/img/sent/',blank=True,null=True) class MessageType(models.Model): type = models.CharField(max_length=100,choices=message_types) text = models.TextField(blank=True,null=True) image = models.ForeignKey(Images,on_delete=models.CASCADE,blank=True,null=True) sticker = models.ImageField(upload_to='static/stickers',blank=True,null=True) class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('auth.User', on_delete=models.CASCADE) message_type = models.ForeignKey(MessageType,on_delete=models.CASCADE) readed = models.BooleanField(default=False) def __str__(self) -> str: return f'From <Thread - {self.thread}>' views.py context['messages'] = Message.objects.filter(thread=obj).order_by('-created_at') data = serializers.serialize("json", context['messages']) return JsonResponse({'messages':data}, safe=False) i want to be able to access image.url and message.type i've tried to set depth=2 in the serializer but it doesn't work because i'm using a higher version of Django. -
How to have multiple Django adminsites with different themes
I've exactly the same question so I took his text and adapted it because he didn't had any answer. I hope I'll have more luck than him. I have setup a Django project to use both the default admin site and then I have created a separate adminsite. I did this by subclassing admin.AdminSite and registering models with this other admin and it works exactly as intended. However, I want to use a template such as AdminLTE or Jazzmin with this other admin while sticking with the standard admin theme for the default admin site. I do not know how to do this or if it is even possible. I've read this post, this one, which is related to the previous one, and that one but they seem to deal with just some html files and not a whole template like AdminLTE. I tried to use the index_template attribute and the index.html of AdminLTE but it doesn't display my models but the preview of AdminLTE. Maybe one solution should be to create another project, associate it with the db of my main project and add the lines in settings.py as described there but it's not seem to be a pretty … -
Django dynamic FileField upload_to throws RelatedObjectDoesNotExist error
I'm trying to make dynamic upload path to FileField model. So when user uploads a file, Django stores it to this path /folder/(environment.id)/(filename). Here is what I did: def get_upload_path(instance, filename): return f"folder/{instance.environment.id}/{filename}" class FileUploader(models.Model): environment = models.ForeignKey(Environment, on_delete=CASCADE) file = models.FileField( verbose_name="Object Upload", storage=MinioBackend(bucket_name=bucket_name), upload_to=get_upload_path, ) but I have this error FileUploader.environment.RelatedObjectDoesNotExist: FileUploader has no environment. Can someone helps me to resolve this error please -
django file upload - file(PDF) not opening from the path
hello everyone i have simple django app with PDF model (title, file ) everything is working file am able to upload the pdf and its getting uploaded to media folder which i specified for it the problem is when i click the link of the file in django admin the page keeps on loading whithout anything happen i dont get any kind of errors in the terminal am using :Django 3.2.13 models.py from django.db import models class PDF(models.Model): title = models.CharField(max_length=255,null=True,blank=True) file = models.FileField(upload_to='pdf/',blank=True,null=True) urls.py from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' not sure what should happen when clicking the link open/download note:changing the field to "models.ImageField" works fine and able to open the image from the link -
How to distribute Celery workers to different servers and queues with docker
I am trying to do some asynchronous tasks with redis and celery for my django website: I have a small task that only takes 10 seconds and is very simple, but I also have a task that can take several hours and is very resource intensive. I would like to have different queues for each kind of task, and have the easy queue run on my server(same server as the other db, web, redis containers; I am using Docker), but have the other queue run tasks on other external server. Is this possible to do? Should I create an additional redis container in the main server just for these external tasks? Do I just create a celery and a redis container in the external servers? Can a queue be connected to multiple external servers at the same time? Thanks I am able to run the celery tasks on my server( in a different container), but I can't find a way to spread them out like I want: having one queue run on my main server in this container, and the other one use only several external servers. -
How make dataclass for partial update(Patch method)?
Use @dataclass in my project. Now I want to implement @dataclass for PATCH method(partial_update) and initialize only provided arguments. For example: @dataclass class Person: id: int first_name: Optional[str] last_name: Optional[str] birthday: Optional[datetime.date] and use it like: person = Person(id=1, first_name ='Andrew') so now person have only two arguments id and first_name(person.id, person.first_name ) Does someone have understanding how to implement such stuff? P.S. Can't use @dataclass class Person: id: int first_name: Optional[str] = None last_name: Optional[str] = None birthday: Optional[datetime.date] = None because it will provide None to not provided arguments and it will update fields in database with None. I don't want these fields be updated in database, so I don't need them being initialized in dataclass. -
Which backend should I choose for a mobile app?
I am a junior dev and I am trying to create a mobile app with flutter ( ios + android). This app will have the « same » fonctionnality as a social network. However, I don’t know what is the best solution for the backend. I heard about Firebase but I am afraid about being stucked in their server. I also heard about Django but it seems to be for web app. What would you advise me to choose ? ————————————————————- -
Django GraphQL mutation returns null
I'm new to Graphene, Django, and GraphQL and am trying to wrap my head around how it would work when updating tables that use a Foreign Key. I am able successfully create a new author, which does not require populating a foreign key field, but I cannot create a new book, which does require populating a foreign key field. My Question: What is wrong with my implementation that is preventing me from creating a new book? What is Happening When I run the CreateNewBook mutation (shown below), GraphQL returns null as the title and no data is added to dim_all_books. What I Expect I expect that when I run the CreateNewBook mutation that the return results show the title of the book and a new record is appended to the table dim_all_books. What I've Tried When I run the following query, it works fine. mutation CreateNewAuthor{ createAuthor(authorData: { authorName: "William Shakespeare", yearBorn: "1722", yearDied: "1844", country: "Austria", booksWritten: 11 }) { author { authorName } } } However, when I run the following query immediately after that query, I get this result: { "data": { "createBook": { "book": null } } } mutation CreateNewBook { createBook(bookData: { title: "Romeo & … -
Trying to start Django on Apache: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
the goal was to run my django project, which is created in a virtual environment from "virtualenv", on apache. I followed this tutorial, which worked well untill I wanted to start the apache as a windows service which resulted in: [Tue Mar 14 14:43:28.277072 2023] [mpm_winnt:notice] [pid 19800:tid 412] AH00455: Apache/2.4.56 (Win64) mod_wsgi/4.9.4 Python/3.10 configured -- resuming normal operations [Tue Mar 14 14:43:28.278069 2023] [mpm_winnt:notice] [pid 19800:tid 412] AH00456: Apache Lounge VS17 Server built: Mar 6 2023 10:53:37 [Tue Mar 14 14:43:28.278069 2023] [core:notice] [pid 19800:tid 412] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Tue Mar 14 14:43:28.283041 2023] [mpm_winnt:notice] [pid 19800:tid 412] AH00418: Parent: Created child process 8896 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\miniconda3' sys.base_exec_prefix = 'C:\\miniconda3' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\miniconda3' sys.exec_prefix = 'C:\\miniconda3' sys.path = [ 'C:\\miniconda3\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x000050e4 (most recent call first): <no Python frame> … -
Django Timeout when submitting a form with more than 5 fields [closed]
I have a Django website using mysql db running for more than one year, but now when I submit an update form for an instance with attributes more than 6, it gives me time out with no errors. when I decrease the number of attributes to 5 it works fine, no matter what are the 5 attributes it is about their length. I am using the Django UpdateView class. The code doesn't enter the post method it Hults before it. any idea of the cause? Thanks in advance I have updated python version to 3.8 and django version to 4.1.7, but no update happened -
Django: how to change status of cart item, if its quantity more than product's general_quantity?
My models.py: class CartModel(models.Model): CART_STATUS = ( ('n', 'Новая'), ('o', 'Заказана'), ('d', 'Удалена'), ) status = models.CharField( max_length=1, choices=CART_STATUS, blank=True, default='n') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, related_name='cart', verbose_name='Принадлежит') created_at = models.DateTimeField( auto_now_add=True, verbose_name="Дата создания") class Meta: verbose_name = "Корзина" verbose_name_plural = "Корзина" ordering = ('-created_at',) class CartItemModel(models.Model): CARTITEM_STATUS = ( ('a', 'Доступен'), ('n', 'Недоступен'), ('d', 'Удалён'), ) status = models.CharField( max_length=1, choices=CARTITEM_STATUS, blank=True, default='a') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product = models.ForeignKey( ProductModel, on_delete=models.CASCADE, related_name='items', verbose_name="Продукт") quantity = models.IntegerField(verbose_name="Количество") cart = models.ForeignKey( CartModel, on_delete=models.CASCADE, related_name='items', verbose_name="Корзина") class Meta: verbose_name = "Товар корзины" verbose_name_plural = "Товары корзины" class ProductModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=82, verbose_name='Товар') category = models.ForeignKey( ProductCategoryModel, on_delete=models.CASCADE, verbose_name='Категория', related_name='products') description = models.TextField(max_length=256, verbose_name='Описание') price = models.DecimalField( max_digits=6, decimal_places=2, verbose_name='Цена') general_quantity = models.IntegerField(verbose_name='Общее количество') def __str__(self): return self.title class Meta: verbose_name = "Товар" verbose_name_plural = "Товары" My serializers.py class CartItemSerializer(serializers.ModelSerializer): singe_item_price = serializers.SerializerMethodField('get_item_price') def get_item_price(self, obj): return obj.product.price class Meta: model = CartItemModel exclude = ('cart',) class CartSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): items = CartItemSerializer(many=True, required=True) total_sum = serializers.SerializerMethodField('get_field_name') def get_field_name(self, obj): return sum([i.quantity*i.product.price for i in obj.items.all()]) class Meta: model = CartModel # exclude = ('user',) fields = ('id', 'status', 'created_at', 'total_sum', 'items') … -
rtsp stream with django
I'm trying to put a url based on my views.py but it returns the error: Reverse for 'transmition' not found. 'transmition' is not a valid view function or pattern name. project urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from plataforma.views import * from django.views.generic.base import TemplateView urlpatterns = [ path("admin/", admin.site.urls), path('contas/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='index.html'), name='index'), path('plataforma/', TemplateView.as_view(template_name='plataforma.html'), name='plataforma'), path('plataforma/stream', TemplateView.as_view(template_name='stream.html'), name='stream'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls.py: from django.urls import path from .views import * urlpatterns = [ path('plataforma', PlataformaView.as_view(), name='plataforma'), path('stream/', StreamView.as_view(), name='stream'), path('transmition/', transmition, name='transmition'), ] app views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.core.mail import EmailMessage from django.views.decorators import gzip from django.views.generic import TemplateView from django.http import StreamingHttpResponse import cv2 import threading @gzip.gzip_page def transmition(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), mimetype="multipart/x-mixed-replace;boundary=frame") except: pass # return render(request, 'stream.html') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture( "rtsp://jorge:jorge33621005@189.124.26.190:554/cam/realmonitor?channel=1&subtype=1") (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') class … -
Djanog custom models give [return-value] error
I am building some custom model fields for a project, which include a User model and a Team model, both in different directories. I have included the team app in the settings. I included the import in case I am importing incorrectly. from team.models import Team class UserManager(BaseUserManager): def create_superuser( self, name: str, email: str, number: str, password: Optional[str] = None, team: Optional[int]=None, ) -> "User": return self.create_user( name, email, number, password=password, team=team, is_staff=True, is_superuser=True, ) def create_staff( self, name: str, email: str, number: str, password: Optional[str] = None, team: Optional[int]=None, ) -> "User": return self.create_user( name, email, number, password=password, team=team, is_staff=True, is_superuser=False, ) def create_user( self, name: str, email: str, number: str, password: Optional[str] = None, team: Optional[int]=None, is_staff: bool = False, is_superuser: bool = False, ) -> "User": user = self.model( name=name, email=self.normalize_email(email), number=number, password=password, team= team, is_staff=is_staff, is_superuser=is_superuser, ) user.save(using=self._db) token = Token.objects.create(user=user) return user class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=250, unique=True) date = models.DateTimeField("Date", auto_now=True) number = models.CharField(max_length=100, default="") team = models.ForeignKey(Team, on_delete=models.PROTECT, default=1) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name", "number", "password"] def __str__(self) -> str: return f"{self.name} ({self.email}) {self.number}" … -
Throttle admin action django
I have accept_withdraw_request action in my RequestWithdaw admin model class RequestWithdraws(admin.ModelAdmin): list_display = ("get_email", "amount", "address", "is_accept", "is_reviewed") list_filter = ("is_reviewed",) actions = ("accept_withdraw_request", "decline_withdraw_request") @transaction.atomic def accept_withdraw_request(self, request, queryset): for withdraw_request in queryset: if withdraw_request.is_reviewed: self.message_user(request, level=messages.ERROR, message=f"Withdrawal request has already reviewed") return queryset.update(is_reviewed=True) for withdraw_request in queryset: with translation.override(withdraw_request.account.user.language): withdraw_request.account.withdraw(-withdraw_request.amount) amount = withdraw_request.amount - withdraw_request.commission tx_hash = USDT.create_tx_out(withdraw_request.address, amount) self.message_user(request, "Accepted {} withdraws".format(queryset.count())) queryset.update(is_accept=True) How can i throttle it to 1 request per 2 seconds when i push accept_withdraw_request admin action button How can i throttle it to 1 request per 2 seconds when i push accept_withdraw_request admin action button -
For loop with range in django template
How can i make a for loop with range function in django template? i want to search in three lists by using this structure. I tried this and it didn't work: {% for i in range my_list|length %} {{ my_list.i }} {% endfor %}