Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to build a social app, where users can post, join groups, add groups etc. but im stuck with an error
I am trying to make a user to be able to see the group details whenever they click on the group name from the group lists, just like facebook. but the slug isn't working i am getting this error.** Reverse for 'single_group' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['group/posts(?P<slug>[\w-]+)/$']** group models.py from django.db import models from django.urls import reverse from django.utils.text import slugify from django import template from django.contrib.auth import get_user_model register = template User = get_user_model() class Group(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) description = models.TextField(max_length=300, blank=True, default= '') description_html = models.TextField(editable=False, default= '', blank=True) members_field = models.ManyToManyField(User, through= 'Group_member') def get_absolute_url(self): kwargs = {'slug':self.slug} return reverse('single-group', kwargs=kwargs) class Meta: ordering = ['name'] class Group_member(models.Model): group = models.ForeignKey(Group, related_name='membership', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_group', on_delete= models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = ('group', 'user') group views.py i made use of Class base view for this project from typing import Any from django.shortcuts import render from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from . import models from django.urls import reverse from django.contrib import messages from django.shortcuts import get_object_or_404 from django.db import IntegrityError class Create_group(generic.CreateView, LoginRequiredMixin): model = models.Group fields = ('name', … -
How can I change the header color and language in django-import-export?
I have a resource to export class RequestResource(resources.ModelResource): class Meta: model = Request fields = ("service__name","user_name","user_address","user_number","user_email","region__name","tariff__name",'status','employee','comment','creation_date','type','connection_status') How do I export the names that are specified in verbose_name? Is it also possible to change colors in excel? -
django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') in my remote web app
I have been working on a django chatting application. The link to the site is https://aniconnect.org so you can check it out if you want to see the error in action. So I am using django-channels for websockets and the websocket connection is being opened and closed instantly. I just checked it out in my console logs. The following is the consumers.py file: from channels.generic.websocket import AsyncWebsocketConsumer import json from django.contrib.auth.models import User from .models import ChatRoom, Message, Profile from asgiref.sync import sync_to_async @sync_to_async def save_message_to_database(chatroom_name, username, message): try: chatroom = ChatRoom.objects.get(name=chatroom_name) user = User.objects.get(username=username) user_profile = Profile.objects.get(user=user) new_message = Message.objects.create(chat_room=chatroom, sender=user_profile, content=message) print("Message saved to DB:", new_message) except ChatRoom.DoesNotExist: print(f"Chatroom with name '{chatroom_name}' does not exist.") except Profile.DoesNotExist: print(f"User profile with username '{username}' does not exist.") except Exception as e: print(f"Error occurred while saving the message: {e}") @sync_to_async def get_chatroom_by_name(name): try: return ChatRoom.objects.get(name=name) except ChatRoom.DoesNotExist: return None @sync_to_async def get_messages_for_chatroom(chatroom): return list(Message.objects.filter(chat_room=chatroom).order_by('timestamp')) class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() print(f"WebSocket connection opened for room: {self.room_name}") chatroom = await get_chatroom_by_name(self.room_name) if chatroom: print(f"Chatroom: {chatroom.name}") else: print(f"Chatroom '{self.room_name}' not found.") messages = await get_messages_for_chatroom(chatroom) for message in messages: … -
Recursive Query with Django-CTE
I have a Tree model that i need to prefetch all the childs and user of the comments all at once: class AnalysisComment(MPTTModel, TimeStampMixin): parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE, help_text=_("User who created the blog."), related_name="analyses_comments", ) text = models.TextField(_("Text")) analysis = models.ForeignKey( Analysis, verbose_name=_("Analysis"), related_name="comments", on_delete=models.CASCADE, ) objects = CTEManager() now this is how I'm getting the analyses with comments: def recursive_comments(cte): return ( AnalysisComment.objects.filter(level=0) .union( cte.join(AnalysisComment, parent=cte.col.id), all=True, ) ) cte = With.recursive(recursive_comments) comments = cte.join(AnalysisComment, id=cte.col.id).with_cte(cte) qs = Analysis.objects.prefetch_related( "tags", "playlists", Prefetch("comments", queryset=comments, to_attr="parent_comments"), ) and i call the childs with obj.child.all() in my serializers. now there are a lot of duplicate objects in the response. and also calls a query for each comment: -
django.urls.reverse() matching URL pattern instead of name
I am coding a Django project for a Wikipedia-like site (CS50W project 1). I have one app inside the project called encyclopedia. Inside my views.py file for this app, I have a redirect, for which I use the django.urls.reverse() function. The link to the documentation for this function can be found here. Now for the problem: If the user visits /wiki/file where file is not a valid page, then the markdown file will not be found in the entry view. And, as you can see, it is supposed to redirect you to the not found page. However, the code return HttpResponseRedirect(reverse("notfound")) loops the user back to the entry view indefinitely, instead of the user being redirected to the not found page. I have found two solutions so far: One can reorder the URL patterns so that the notfound pattern appears before the entry pattern, or a slash can be added to either of the aforementioned URL patterns. I am, however, looking for the cause of the problem. I am currently considering the possibility that the reverse() function is using the URL pattern instead of the name for some reason. urls.py file for encyclopedia: from django.urls import path from . import … -
Django usage and plugins ecosystem
Why there is a drop in use of django in the world? New plugins count, maintain of existing plugins are lacking more and more. Django is very user friendly. This is crazy, stackoverflow.com says it needs at least 220 characters. Can't a question be small than 220 characters? Crazy stuff. -
How can I make a content based movie recommendation system with Django real-time data?
I am working on a project for my school. I have a Django program where I keep information about 1 million movies in Model Movie with features like title, genre and actors. models.py class Genre(models.Model): title = models.CharField(max_length=255) class Actor(models.Model): name = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) genre = models.ManyToManyField(Genre) actors = models.ManyToManyField(Actors) I am trying to create a celery function to train my model once in a day at 12 AM. tasks.py @shared_task def train_and_save_video(): movie_data = Movie.objects.all().exclude(actors__isnull=True, genre__isnull=True) features = movie_data.values_list('id', 'title', 'actors__name', 'genre__title') # over to you, I think we can go with TfidfVectorizer, RandomForestClassifier using pipeline # or cosine_similarity using CountVectorizer and csr_matrix but I don't think so that, this is a good approach. I want the program to learn a little bit each time I add a new movie (concatenate a new movie object to the trained model), without making it learn from scratch with all the movies every time. Can someone explain how to do this? May be we can achieve this using signals.py or admin.py -
Running own conftest for every application
I have several applications in my project each application has its own tests: app/tests/test_block1.py test_block2.py ... And every tests folder has its own conftest.py I want to drop database for every app. I use this fixture: @pytest.fixture(scope="package") def django_db(django_db_blocker): with django_db_blocker.unblock(): call_command("sqlflush") with django_db_blocker.unblock(): call_command("migrate", "--noinput") yield None Scope function and class does not fits for me. I tried module scope and all tests outside a single file fails. I tried package scope and all tests outside a single folder fails. I tried session scope and behaviour was the same. What will be the good variant in my case? Is there any variant except writting one big conftest file instead of different conftest files for every application? -
Multiple NoReverseMatch errors at password reset Django
I'm working on Django project, still new at Django. I'm trying to follow instructions from this book but there are some changes in my project. I'm trying to create login/registration with Django, but I'm stuck with reset password section. I know that my problem is related to name spacing but cannot figure out why is that and why isn't redirecting to pages mentioned in errors. I have two errors: Error 1: NoReverseMatch at /password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Error 2: NoReverseMatch at /reset/MQ/set-password/ Reverse for 'password_reset_complete' not found. 'password_reset_complete' is not a valid view function or pattern name. urls.py from django.urls import path, include from . import views from .feeds import LatestLessonsFeed from django.contrib.auth import views as auth_views app_name = 'learning_app' urlpatterns = [ #lessons path('', views.lesson_list, name='lesson_list'), path('<int:year>/<int:month>/<int:day>/<slug:lesson>/', views.lesson_detail, name='lesson_detail'), #tags path('tag/<slug:tag_slug>/', views.lesson_list, name='lesson_list_by_tag'), #feed path('feed/', LatestLessonsFeed(), name='post_feed'), # previous login view # path('login/', views.user_login, name='login'), # login / logout urls #path('login/', auth_views.LoginView.as_view(), name='login'), #path('logout/', auth_views.LogoutView.as_view(), name='logout'), # change password urls #path('password-change/', auth_views.PasswordChangeView.as_view(), name='password_change'), #path('password-change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), # reset password urls #path('password-reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), #path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), #path('password-reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), #path('password-reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), #dashboard path('dashboard/', views.dashboard, name='dashboard'), #django … -
How to sort data from django serializer
Here is my code: class PackageMetaSerializer(ParameterBaseSerializer): expired_delta = serializers.SerializerMethodField(method_name='calculate_delta', read_only=True) package = platforms_serializers.PackageSerializer( parameters=("uuid", "id", "name", "platform", "type", "period") ) expire_date_datetime = serializers.DateField("%Y/%m/%d") class Meta: model = account_models.UserToPackageMeta fields = "__all__" depth = 4 def calculate_delta(self, instance): today = datetime.date.today() last_package = instance.expire_date_datetime return (last_package - today).days class UserSerializer(ParameterBaseSerializer): packages = PackageMetaSerializer( read_only=True, many=True, source="package_metas", parameters=("id", "token", "created_date", "package", 'expired_delta'), ) last_package = serializers.SerializerMethodField( method_name="get_last_package", read_only=True ) has_active_package = serializers.SerializerMethodField( "check_user_activity", read_only=True ) is_profile_completed = serializers.SerializerMethodField( "check_profile_completed") has_unread_notification = serializers.BooleanField(read_only=True) birth_date = PersianDateField(format="%Y/%m/%d", required=False) class Meta: model = account_models.User fields = "__all__" extra_kwargs = {"password": {"write_only": True}} depth = 4 Whenever I use the UserSerializer, I want the data to be sorted by the expired_delta I got from the other serializer. How can I do that from the serializer side? Sort data by expried date -
Django models.CheckConstraint causing "TypeError: 'staticmethod' object is not callable"
I have a model named Therapist written as follows: from django.contrib.auth.models import User from django.core.exceptions import ValidationError class Therapist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Also a model named **Appointment ** with some constraints. class Appointment(models.Model): therapist = models.ForeignKey(Therapist, on_delete=models.CASCADE) client = models.ForeignKey(User, on_delete=models.CASCADE) slot = models.DateTimeField() def validate_not_match_therapist_client(self): if self.therapist.user == self.client: raise ValidationError('Therapist and client cannot be the same user.') def clean(self): self.validate_not_match_therapist_client() class Meta: constraints = [ # Same client booking multiple appointments at the same slot (different therapists) models.UniqueConstraint( fields=['client', 'slot'], name='multiple_same_date_time_appointment' ), # therapist booking his/her own appointment models.CheckConstraint( check=~models.Q(therapist__user=models.F('client')), name='therapist_client_are_same' ) ] In this project, **Therapist **objects can also book appointments but I wanted to restrict them from booking any appointments with itself. So, I wrote the second constraint like this: # therapist booking his/her own appointment models.CheckConstraint( check=~models.Q(therapist__user=models.F('client')), name='therapist_client_are_same' ) It works fine when I run **makemigrations **, but when I run **migrate **it throws this following error: Traceback (most recent call last): File "/home/user/project/manage.py", line 22, in <module> main() File "/home/user/project//manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/base.py", line412, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/base.py", line458, in execute output = … -
Django orm filling out 3 interrelated forms on one page and passing each other last inserted id. Issue if form 2 o 3 fail. Form 1 stays fatherless
I have come across an interesting issue (probably because of my lack of knowledge): I have 3 tables (3 forms) that are interrelated. Address, property and photos. The first table or form is Address, it is populated by using a select list. So, on clicking the submit button, that first form will populate a row in Address table. Then I obtain that last id in order to pass it to form 2, properties and the properties will pass the last id inserted to photos, so the three are related by Foreign Keys. What happens in this scheme? If the Property form fails because someone enters bad input in a text field, the model will reject it and will return the user back to the form. BUT, notice that the row in table address was already inserted and it will stay there. Yes, you may say that I could include a line of code in the processing of form Properties, that if it fails, it should delete the recently address row inserted but that doesn't help me because the id sequence will not be reset in the table, it will leap to the next one leaving a gap in the id … -
Shopify Python API Pagination
I am trying to implement pagination using the Shopify API in a Django App but I am not sure how to do so. I read the documentation and have to know that we can get the link of the next and previous page of a resource endpoint through the API but cannot figure out how to implement it in a Django App. My view looks like this: import shopify from shopify_app.decorators import shop_login_required @shop_login_required def index(request): orders = shopify.Order.find(status='any') return render(request, 'home/index.html', {'orders': orders}) index.html: {% extends "base.html" %} {% load template_tags %} {% block content %} <div id="orders"> <div style="display: flex;"> <h2 style="width: 50%;">Your recent orders</h2> </div> {% if orders %} <div class="order-list"> <p id="page-toggle"> <a href="#"> <span id="prev-page">&lt; <b>PREV PAGE</b> </span> </a> <a href=""> <span id="next-page"> <b>NEXT PAGE</b>&gt; </span> </a> </p> {% for order in orders %} <div class="order box"> <div class="wrapper"> <a style='width: 25%; color: black;' href="https://{{ current_shop.domain }}/admin/orders/{{ order.id }}" target="_blank">{{ order.name }}</a> <span style='width: 25%;'>{{ order.created_at | convert_str_date }}</span> <span style='width: 25%;'>{{ order.total_price }} {{ order.currency }}</span> <span style='width: 25%;'>From: {{ order.billing_address.name }}</span> </div> <a href="#" class="download-button"> <button>DOWNLOAD</button> </a> </div> {% endfor %} </div> {% else %} <em class="note">There are no orders in your store.</em> … -
django constance localize language
I use django-constance CONSTANCE_CONFIG = { 'MESSAGE_ROSETTE_DISCONNECT': ('Device {device_name} disconnected from the rosette', 'Message that device disconnection from the rosette'), 'MESSAGE_ROSETTE_CONNECT': ('Device {device_name} connected to the rosette', 'Message that device connection to the rosette'), ... } I want set the different text for different languages. Is it possible? Something like this CONSTANCE_CONFIG = { 'MESSAGE_ROSETTE_DISCONNECT': { 'en': ('Device {device_name} disconnected from the rosette', 'Message that device disconnection from the rosette'), 'it': ('Same about {device_name} in Italian language', 'Italian text'), } ... } What is the best way to implement it? And how to call the constanse? Now its like this: text = config.MESSAGE_BATTERY_LEVEL.format(device_name=self.device.name) -
How to store a loaded PIL image or just the Blob Binary Data in a Django SQLite Database temporarily?
My Django backend views.py looks something like this where I have successfully received a blob data and read the image using PIL def predictor(request): blob = request.FILES['image'].read() thumb = Image.open(BytesIO(blob)) rgb_im = thumb.convert('RGB') # thumb.show() # successfully displays the image in imageviewer image_io = BytesIO() rgb_im.save(image_io, format='jpeg') # save to model form = FaceImage(name="random", image=ContentFile(image_io.getvalue())) form.save() print("Image Successfully saved") return And my models.py is shown below: class FaceImage(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='images/') def __str__(self): return self.name The output of my code successfully prints the line "Image Successfully saved" but when I view the database in django the ImageField seems to be empty only the name is saved not the image itself. Is there anyway I can save the image in imagefield or rather save a blob data in the database because I just want to save the image temporarily where I would delete the image after doing some image processing stuff so I do not care about the database being bloated by any data. I have viewed several instructions on how to save a pil image in django database but couldnt quite make it work. -
Django ORM calculate score and win from tables. Please click on description links to see model screenshots
I am new bie to django ORM and struggling to use ORM. Please help me. I have 3 tables in django model and i want to write some getter methods under model classI need help to create methods, I am not able to understand how to calculate values using ORM Create a method on the Team model that returns the total number of matches played by the team Create a method on the Team model that returns the total number of matches won by the team Create a method on the Team model that returns the total number of matches lost by the team Your help is really meaningful to me. Thank you. -
Creating a service layer with Django Rest Framework
I am fairly new to web-development and just studing design patterns and code architecture. Now, I am developing service layer for business logic. And here I have a dillema. One approach is to use command design pattern. Where I have a class which implements user creation and related processes (e.g. sending email, writting logs etc), also this class has one public method (entry point) and private methods, called inside the entry point. Here is the example of what I mean. class CreateUser: def _create_user(self, **data) -> User: # here perform creation of user itself, requesting repository layer ... def _send_email(self, **data) -> None: # here I send email def _write_logs(self, **data) -> None: # writing logs to a file def execute(**data): self._create_user(**data) self._send_email(**data) self._write_logs(**data) On the other hand, there is a approach where I create a common service as a class, that handles user authentication and registration and for each user action has one method: class UserService: def create_user(self, **data) -> User: # call to repository # send email # write logs def update_user(self, **data) -> User: # call to repository # write logs I don't really know what solution I should choose. I suppose that the command pattern is … -
PermissionError: [Errno 13] Permission denied: '/app/static/admin/fonts/README.txt'
I am trying to deploy a django app for the first time on a EC2 Ubuntu 22.04 instance. I have everything set up in a docker-compose file and working on my Windows 11 machine, but I am running into issues with permissions. The instance's user is ubuntu and I can read, write and execute within the folder. I have tried adding it to the dockerfile but that does not seem to have any effect. Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python # Stage1: Create Wheels FROM python as python-build-stage ARG BUILD_ENVIRONMENT=production # required for make and setup for postgres RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev COPY Backend/requirements . RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt # Stage 2: Setup Django FROM python as python-run-stage ARG BUILD_ENVIRONMENT=production ARG APP_HOME=/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} RUN addgroup --system django \ && adduser --system --ingroup django django RUN apt-get update && apt-get install --no-install-recommends -y \ libpq-dev \ netcat \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* COPY --from=python-build-stage /usr/src/app/wheels /wheels/ RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ && rm -rf /wheels/ # django … -
Display contents of the database table selected by user in Django
As per user selection I want to display course details. I do not want to create multiple pages for each course detail. So, at course-detail.html I am passing a course-code as hidden value in html form which is table name in my database project. When a user submits the query for course, I pass the course-code value by POST method into my views.py file. But there I am not able to use post method string as a model name. courses.html {% for courses in english_courses %} <form action="{% url "course-detail" %}" method="POST"> {% csrf_token %} <input type="hidden" name="course-code" value="{{courses.course_code}}"> <button class="btn-lg btn-primary d-inline-flex align-items-center" type="submit" onclick="document.location.href='{% url "course-detail" %}';"> {{course.name}} </button> &nbsp; {% endfor %}</form> views.py def course_detail(request): if request.method == "POST": course_request = request.POST['course-code'] course_request = course_request.capitalize() course_details = course_request.objects.all() return render(request, 'course-detail.html', {'course': course_details}) else: messages.warning(request, "Link seems to be broken. Please contact admin.") return render(request, 'course-detail.html') this throws an error: AttributeError at /english/course-detail 'str' object has no attribute 'objects' -
data = json.loads(request.body.decode('utf-8')) error no se por que :(
Me da este error "data = json.loads(request.body.decode('utf-8'))" al querer cargar un json traido de un js con django. Es para un proyecto escolar :( El codigo recibe una foto tomada por el navegador y la guarda y el error aparece al recibir el post por parte del html Aqui el codigo del view del proyecto. from django.shortcuts import render from django.http import JsonResponse import json import base64 import os import logging from random import randint logging.basicConfig(level=logging.DEBUG) def Inicio(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) image_url = data.get('image_url', '') # Guarda la imagen físicamente en la carpeta de medios guardar_imagen_fisicamente(image_url) return JsonResponse({'message': 'Imagen recibida y guardada con éxito.'}) return render(request, 'plantilla1.html') def guardar_imagen_fisicamente(image_url): # Decodifica la imagen base64 image_data = image_url.split(",")[1] image_binary = base64.b64decode(image_data) # Guarda la imagen en la carpeta de medios ruta_carpeta = 'capturas' ruta_completa = os.path.join('media', ruta_carpeta, generar_nombre_imagen()) ruta_completa = os.path.join("C:/myproject/myproject/", ruta_completa) with open(ruta_completa, 'wb') as f: f.write(image_binary) def generar_nombre_imagen(): n = randint(0,999999999) nombre_imagen = f"imagen_{n}.png" return nombre_imagen Cosas como url y settings estan bien, ya esta revisado pero me da error en cuando quiero obtener la data, y es que me explota enter image description here Inexperadamente si me toma la foto, es decir si hace … -
How to check if a Django CharField is empty
I've been working on a Django database project and I need to return a value only if a CharField is not empty. class author(models.Model): name = models.CharField(max_length=255, unique=True, help_text='Article author') pronouns = models.CharField(max_length=255, help_text='Enter pronouns (optional)', blank=True, verbose_name='Pronouns (optional)') if pronouns != '': def __str__(self): return f'{self.name} ({self.pronouns})' else: def __str__(self): return self.name Despite me not entering anything in the pronouns field when testing, it still acts as if it has a value and returns Name () with nothing in those parentheses. I have tried, checking if it is None or '' and setting default='' and then checking if it is not equal to the default. None of those have worked. How do I fix this? -
DRF serializer validation of inputs across multiple nested fields
I'm using DRF serializers for models with measurements with units. Here's my model: class Cargo(models.Model): length = models.FloatField() height = models.FloatField() weight = models.FloatField() input_length_unit = models.IntegerField(choices=LengthUnits.choices) input_weight_unit = models.IntegerField(choices=WeightUnits.choices) I have the following serializers to convert data like {"length": {"value": 10, "unit": 1}, ...} to my model schema: class FloatWithUnitSerializer(serializers.Serializer): value = serializers.FloatField() unit = serializers.IntegerField() def __init__(self, unit_type, field_name, *args, **kwargs): super().__init__(*args, **kwargs) self.unit_type = unit_type self.field_name = field_name def to_representation(self, instance): value = getattr(instance, self.field_name) unit = getattr(instance, f"input_{self.unit_type}_unit") # convert from database unit to input unit value = value * UNITS[self.unit_type][unit] return {"value": value, "unit": unit} def to_internal_value(self, data): # convert from input unit to database unit value = data["value"] / UNITS[self.unit_type][data["unit"]] return {self.field_name: value, f"input_{self.unit_type}_unit": data["unit"]} class CargoSerializer(serializers.ModelSerializer): length = FloatWithUnitSerializer("length", "length", required=False, source="*") height = FloatWithUnitSerializer("length", "height", required=False, source="*") weight = FloatWithUnitSerializer("weight", "weight", required=False, source="*") class Meta: model = models.Cargo fields = ["length", "height", "weight", "input_length_unit", "input_weight_unit"] This works, but now I want to prevent unit-mixing. For example given the unit type "length", which includes the "length" and "height" fields (units are meters, feet, etc), they need to post the same unit for both, e.g. {"length": {"value": 10, "unit": 1}, "height": {"value:15", "unit": 1}}. … -
django-otp and dj-stripe conflict
i'm searching a way to implement django-otp and dj-stripe in a web project but i think there is a conflict because django-otp uses custom admin_site.register() to register models while dj-stripe uses admin.site.register(). i'm triyng with the following code but not works because all stripe model are registered not following list_display field customizations as in admin.py on github repository. #urls.py from django.contrib import admin from django.urls import path, include from account.admin import admin_site urlpatterns = [ path("realadmin/", admin_site.urls), path("stripe/", include("djstripe.urls", namespace="djstripe")), ] #admin.py from django_otp.admin import OTPAdminSite from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.admin import TOTPDeviceAdmin # Stripe modules from djstripe import models class OTPAdmin(OTPAdminSite): pass admin_site = OTPAdmin(name='OTPAdmin') # Script to register all models modelsarray = django.apps.apps.get_models() # Register other django-otp models with the custom admin site (admin_site) for model in modelsarray: try: if model.__module__.startswith("dj-stripe"): # Register with the default admin.site for dj-stripe models admin.site.register(model) elif model == Customer: admin_site.register(model, CustomerAdmin) else: # Register with the custom admin site for other models (e.g., django-otp) admin_site.register(model) except admin.sites.AlreadyRegistered: pass so, i want to register stripe's models using admin.site.register because in this way i can use admin.py code of github repository but i need also to use admin_site.register for otp secutiry tool. can … -
How to get value from select2 in Django
I am trying to add a new constraint, but according to the data, the code takes all values except acc_id4 and c_center, and the result is always something like Row 1: acc_id4=None, description=salary 10/2023, doc=1023, d_date=2023-11-25, debit=1000, credit=0.00, c_center=None I don't know why it's always nothing Is the problem in the template or in the Django code? And how do I solve this problem? Note: The JavaScript code creates a new row and makes the old row read-only. It also copies the values except for the acc_id4 and c_center values. It also makes the generated name add a number after the _ sign. html {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Acc Entry</title> <link rel="shortcut icon" href="{% static 'image/daleel.ico'%}" > <link rel="stylesheet" href="{% static 'css\Entry.css'%}"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="{% static 'plugins/fontawesome-free/css/all.css'%}"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600&display=swap" > <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> </head> <body> <div class="radio"> <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" > <label class="btn btn-outline-primary" for="btnradio1">New</label> <input type="radio" class="btn-check" name="btnradio" id="btnradio2" value="save" autocomplete="off"> <label class="btn btn-outline-primary" for="btnradio2">Save</label> <input type="radio" class="btn-check" … -
Running sphinx-build -b html docs_source/ docs/ leads to AttributeError: 'Values' object has no attribute 'link_base'
I have a Django 4.2 project and wish to run the Sphinx to generate the docs. When I run: sphinx-build -b html docs_source/ docs/ I got the following error: Exception occurred: File "C:\ProgramData\Anaconda3\envs\django_3_8\Lib\site-packages\django\contrib\admindocs\utils.py", line 116, in _role inliner.document.settings.link_base, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'Values' object has no attribute 'link_base' The full traceback has been saved in C:\Users\user\AppData\Local\Temp\sphinx-err-r_cbc4k5.log, if you want to report the issue to the developers. The list of the installed packages is as follows: Package Version alabaster 0.7.13 amqp 5.1.1 anyio 3.5.0 argon2-cffi 21.3.0 argon2-cffi-bindings 21.2.0 asgiref 3.7.2 asttokens 2.0.5 attrs 22.1.0 autopep8 1.6.0 Babel 2.13.1 backcall 0.2.0 beautifulsoup4 4.12.2 billiard 3.6.4.0 bleach 4.1.0 celery 5.1.2 certifi 2022.12.7 cffi 1.15.1 charset-normalizer 3.3.2 click 7.1.2 click-didyoumean 0.0.3 click-plugins 1.1.1 click-repl 0.2.0 colorama 0.4.6 comm 0.1.2 coverage 7.2.2 cryptography 39.0.1 debugpy 1.5.1 decorator 5.1.1 defusedxml 0.7.1 diagrams 0.23.3 Django 4.2.7 django-debug-toolbar 4.0.0 django-nose 1.4.6 django-postgres-extra 2.0.8 djangorestframework 3.14.0 djangorestframework-simplejwt 4.4.0 docutils 0.20.1 drf-extra-fields 3.5.0 drf-spectacular 0.26.2 entrypoints 0.4 et-xmlfile 1.1.0 executing 0.8.3 fastjsonschema 2.16.2 filetype 1.2.0 graphviz 0.20.1 idna 3.4 imagesize 1.4.1 inflection 0.5.1 ipykernel 6.19.2 ipython 8.18.0 ipython-genutils 0.2.0 jedi 0.18.1 Jinja2 3.1.2 jsonschema 4.17.3 jupyter_client 8.1.0 jupyter_core 5.3.0 jupyter-server 1.23.4 jupyterlab-pygments 0.1.2 kombu 5.3.1 lxml 4.9.2 Mako 1.3.0 Markdown 3.5.1 MarkupSafe …