Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my project name as changed as cannot changed back on pycharm
I've created a project called Socialmedia, few days ago suddenly i noticed the name of the project as changed to a file inside the project as you can see, the project name is manage.py on not Socialmedia the main dir I've tried: Resetting to default IDE and opening the dir project Socialmedia Changing the name Opening the project as Socialmedia -
spoonacular API and django
i have a question. Can i add spoonacular API to my django project? I'm doing a recipe-sharing project and would really like to have a database with ingridients, so i can choose them when making new recipe. My question is if i can have like 2 databases, if that makes sense? i would have djangos database db.sqlite3 and this spoonacular API. Thanks I looked at some youtube tutorial, but it doesnt make sense for me. I tried google it, but unfortunately didnt really catch anything. -
How can I ensure synchronized incrementation of two counters in a Celery async task
I'm encountering a scenario where a single endpoint is receiving multiple concurrent requests for image uploads. Upon successful upload, two counters need to be incremented synchronously. Initially, I tried synchronously incrementing the counters, but due to race conditions, the results were incorrect. Consequently, I implemented an asynchronous Celery task to handle this. However, while one counter stays in sync, the other does not. I'm puzzled why only one counter is affected if both are subjected to the same conditions. I am using Postgres as my database. To address the issue of asynchronous counter incrementation, one potential solution is to remove the counters altogether and instead track the number of uploaded images. However, it's crucial to understand the root cause of the asynchronous behavior to prevent similar issues in the future. This is the piece of code that is doing the increment @shared_task def increment_album_and_event_image_count(album_id): try: with transaction.atomic(): album = Album.objects.get(id=album_id) album.image_count_in_album = F("image_count_in_album") + 1 album.save() album.event.number_of_images_across_albums = ( F("number_of_images_across_albums") + 1 ) album.event.save() return True except Exception as e: logger.error(f"Error incrementing image count: {e}, album: {album}") return False Here the number_of_images_across_albums has correct information while image_count_in_album does not. Here are the model details: class Album(TimeStampedModel): image_count_in_album = models.IntegerField(default=0) event … -
Understanding keycloak authentication with mozilla-django-oidc
I am currently trying to use Keycloak with Django. I use the mozilla-django-oidc package for this and have used this tutorial as a guide, but with my own Keycloak server. So far, everything is working fine. The protected view can only be accessed after logging in via Keycloak. However, django rest framework is causing me problems. I have made the configuration as described in the instructions, but I always get 401 (Unauthorized) back for requests to the Django Rest Framework endpoint. And I don't understand why. As far as I understand it, mozilla-django-oidc sets a "sessionid" cookie to authenticate the user. I can also access the protected view. For a request to the Django Rest Framework endpoint, however, I have to send an Authorization header with the access token according to the mozilla-django-oidc documentation. But where do I get this access token in my single page application to set it in the Authorization header? I have tried to read the access token in the SPA from the mentioned "sessionid" cookie. But this cookie is http only. -
Filling the FormMixin form
Is it possible to populate FormMixin form data without passing the form variable to the template? I have a template, but I don't understand how to create a form with Django, so I just specify the name attribute in the template. The form is created, everything is fine, I override the method get_initial() method, but the form is not filled out Is it possible to do this or do I need to pass the form variable? class CommentEditView(View, FormMixin): form_class = EditCommentForm def get_initial(self): initial = super().get_initial() comment = get_object_or_404(Comment, pk=15) initial['review_text'] = comment.review_text initial['grade'] = comment.grade return initial def get(self, request, comment_id): return render(request, 'catalog/review-edit.html') class EditCommentForm(ModelForm): class Meta: model = Comment fields = ['review_text', 'grade'] <form method="POST"> {% csrf_token %} <textarea class="product-detail-reviews-textarea" name="review_text" id="id_review_text"></textarea> {% for error in form.review_text.errors %} <p class="product-detail-reviews-error">* {{ error }} </p> {% endfor %} <div class="product-detail-reviews-row"> <div class="product-detail-reviews-stars"> <p>Stars:</p> <div class="rating-area"> <input type="radio" id="id_grade_five" name="grade" value="5"> <label for="id_grade_five" title="Star «5»"></label> <input type="radio" id="id_grade_four" name="grade" value="4"> <label for="id_grade_four" title="Star «4»"></label> <input type="radio" id="id_grade_three" name="grade" value="3"> <label for="id_grade_three" title="Star «3»"></label> <input type="radio" id="id_grade_two" name="grade" value="2"> <label for="id_grade_two" title="Star «2»"></label> <input type="radio" id="id_grade_one" name="grade" value="1"> <label for="id_grade_one" title="Star «1»"></label> </div> </div> <button type="submit" class="product-detail-reviews-link">Confirm</a> </div> {% … -
My formset is not valid and i cannot retreive the cleaned_data of each form
I have 3 models below class MenuItem(TranslatableModel): item_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) categories = models.ManyToManyField(MenuCategory, related_name='menu_items') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True), description=models.TextField(_('description'), blank=True, null=True) ) price = models.DecimalField(_('price'), max_digits=10, decimal_places=2, default=0) image = models.ImageField(_('image'), upload_to='menu_items/%Y/%m/%d', blank=True, null=True) is_available = models.BooleanField(_('is available'), default=True) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() def get_absolute_url(self): return reverse('menu_management:item_detail', args=[self.item_id, self.slug]) class MenuOptionGroup(TranslatableModel): group_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='options_groups') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True) ) is_required = models.BooleanField(_('is required'), default=False) max_choices = models.IntegerField(_('max choices'), blank=True, null=True) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() class MenuOption(TranslatableModel): option_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) group = models.ForeignKey(MenuOptionGroup, on_delete=models.CASCADE, related_name='options') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True) ) image = models.ImageField(_('image'), upload_to='menu_options/%Y/%m/%d', blank=True, null=True) price_change = models.DecimalField(_('price change'), max_digits=10, decimal_places=2, default=0) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() From this 3 class I am trying to create a formset that will go through the MenuOptionGroup and pick up their repective menu_option. my form look like the below class MenuOptionGroupForm(TranslatableModelForm): menu_option = forms.ModelChoiceField(queryset=MenuOption.objects.none(), empty_label="No options", required=False) class Meta: model = MenuOptionGroup # Include the fields that … -
Failed to fetch: Js code on Html template
In a JS code I'm using fetch to make GET requests to a url to obtain data in JSON format. The js code is located in my Django project and I use it in some templates. When I click on the button that activates the js script, it tells me that there is an error in the fetch, can someone help me? I have tried to solve it by allowing cross origin but nothing. -
cant link css file to html file with
i cant link a css file to an html file im am using visual studio code and python django to do this my files are like this project |templates | home.html | style.css app.py home.html <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Raleway:400, 600' rel='stylesheet' type='text/css'> <link href='assets/style.css' rel='stylesheet' type='text/css'/> </head> <body> ... </body> style.css html, body { margin: 0; padding: 0; } header { background-color: #333333; position: fixed; width: 100%; z-index: 5; } h1 { font-family: 'Times New Roman', Times, serif; color:cadetblue } app.py from flask import Flask, render_template app = Flask(__name__, template_folder="templates") @app.route("/home") @app.route("/") def index(): return render_template("home.html") i tried using the templates folder, it didnt work i tried without using the templates folder, it didnt work it doesnt raise any error but the page just doesnt has the css style, for example the h1 tags keep being black with the default font, and they shoud be blue with Times New Roman Font Any help would be appreciated 🙂 -
Runs on Local Host but not on heroku
I keep getting this Server 500 error while deploying my to Heroku. It runs perfectly on my Local host. The other page on the site works fine but this one has the News-API. Not sure what to do next. Debug ERROR \`KeyError at / 'articles' Request Method: GET Request URL: https://lvl27-9617c0ce663b.herokuapp.com/ Django Version: 4.2.10 Exception Type: KeyError Exception Value: 'articles' Exception Location: /app/news/views.py, line 13, in index Raised during: news.views.index Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.18 Python Path: \['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'\] Server time: Tue, 19 Mar 2024 23:03:02 +0000 Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) … Local vars /app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py, line 197, in \_get_response response = wrapped_callback(request, \*callback_args, \*\*callback_kwargs) … Local vars /app/news/views.py, line 13, in index a = gaming_news\['articles'\]\` CODE from django.shortcuts import render import requests import os from dotenv import load_dotenv, dotenv_values from newsapi import NewsApiClient load_dotenv() API = os.getenv('NEWS_API') def index(request): url = (f"https://newsapi.org/v2/everything?q=gaming&apiKey={API}") gaming_news = requests.get(url).json() a = gaming_news['articles'] urlToImage = [] author = [] title = [] description = [] url = [] for i in range(len(a)): f = a[i] urlToImage.append(f['urlToImage']) author.append(f['author']) title.append(f['title']) description.append(f['description']) url.append(f['url']) news_list = zip(urlToImage, author, title, description, url) context = {'news_list': news_list} … -
Convert XPS To PDF with Python
I have a Django project. There is a need to convert XPS format to PDF. The PDF file itself can be obtained as a byte array upon request from another system. Perhaps there is some library or working implementation in Python? doc_data = get_PDF_file_in_pilot(project=project, file_id=id) if doc_data.get("error"): return HttpResponse(json.dumps(doc_data), content_type="application/json", status=500) file_name = doc_data["file_name"] file_name_no_extension, file_extension = os.path.splitext(file_name) if doc_data.get("file_name") and doc_data.get("file_content"): file_content = doc_data["file_content"] file_data = { 'status': 'success', 'file': base64.b64encode(file_content).decode('utf-8'), 'file_name': file_name } return JsonResponse(file_data) -
How do I implement forms for user input to register and login in Django when I already have the views using JWT?
I´m learning how to work with JWT(pyJWT) in Django, in this case I´m trying to authenticate users with it, I followed a tutorial and using postman it worked, I use mysql and the passwords were hashed and the tokens were generated succesfully, now the only thing left is to create the forms so the user can input his credentials but I don´t know how to do proceed. Views.py class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found') if not user.check_password(password): raise AuthenticationFailed('Incorrect password') payload = { 'id': user.id, 'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=60), 'iat': datetime.datetime.now(datetime.timezone.utc) } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = {"jwt": token } return response class UserView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unathenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Uathenticated') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) class LogoutView(APIView): def post(self, request): response = Response() response.delete_cookie('jwt') response.data = { 'message': 'Success' } return response Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'password', 'first_name', … -
Django views.py Lookup value from constant list
In a django views.py how do you take a selection (number) from input can get the matching "Description"? For example the user selects 3 and returns "Yellow" colors = [ ('0','black'), ('1','white'), ('2','Red'), ('3','Yellow'), ('4','Blue'), ('5','Green') ] ... colorSelection = form.cleaned_data.get('color') #lookup color description colorDescription = ??? -
Hashing the password if it is not hashed in django
When I try to create a password for the user using the admin interface is doesn't get hashed. So I added this line in the user model def save(self, *args, **kwargs): self.set_password(self.password) While this solves the issue. while creating user using createsuperuser it saves the password as a hash But when I try to login into the admin interface is says incorrect password. I'm sure it's caused by the adding the above line into the code. When i remove the line, createsuperuser works fine but password isn't hashed in the admin interface, when i add the line admin works while createsuperuser doesn't. I want to hash the password if it isn't hashed yet. -
Getting "django.db.utils.ProgrammingError: column "v11.confirmed" must appear in the GROUP BY clause
I am getting "django.db.utils.ProgrammingError: column "v11.confirmed" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...'xandr']::varchar(254)[] AND (V11."id" IS NULL OR V11."confi...".Anyone please suggest what's wrong with the query?thank you in advance data = AdidMeta.objects.filter(id__in=adid_meta_file_list.values_list('adid_meta_id', flat=True)).prefetch_related( "adidmetafileupload_set__creativeencoding_set", "adidmetafileupload_set__creativeacknowledgement_set", "xandrcreative_set", "assets_set__ad_copy_rotation" ).annotate( operators=ArrayAgg("distributors__name", ordering="distributors__name", distinct=True), no_operator=Case( When(Q(operators=[None]) & Q(adidmetafileupload__creativeacknowledgement__isnull=False, adidmetafileupload__creativeacknowledgement__is_received=True, adidmetafileupload__creativeencoding__isnull=False, adidmetafileupload__creativeencoding__is_encoded=True ) & Q( Q(orderline__isnull=False, orderline__status=OrderLine.ACTIVE) | Q(orderline__isnull=True, assets__ad_copy_rotation__orderline__status=OrderLine.ACTIVE) ), then=Value(1) ), default=Value(0), output_field=IntegerField() ), only_dish=Case( When(Q(operators=[OPERATOR_NAME.DISH]) & Q(adidmetafileupload__creativeacknowledgement__isnull=False, adidmetafileupload__creativeacknowledgement__is_received=True, adidmetafileupload__creativeencoding__isnull=False, adidmetafileupload__creativeencoding__is_encoded=True ), then=Value(1) ), default=Value(0), output_field=IntegerField() ), only_directv=Case( When(Q(operators=[OPERATOR_NAME.XANDR]) & Q(xandrcreative__isnull=False, xandrcreative__confirmed=True), then=Value(1) ), default=Value(0), output_field=IntegerField() ), both_dish_directv=Case( When(Q(operators=[OPERATOR_NAME.DISH, OPERATOR_NAME.XANDR]) & Q(adidmetafileupload__creativeacknowledgement__isnull=False, adidmetafileupload__creativeacknowledgement__is_received=True, adidmetafileupload__creativeencoding__isnull=False, adidmetafileupload__creativeencoding__is_encoded=True, xandrcreative__isnull=False, xandrcreative__confirmed=True ), then=Value(1) ), default=Value(0), output_field=IntegerField() ) ).distinct().filter( Q(no_operator=1) | Q(only_dish=1) | Q(only_directv=1) | Q(both_dish_directv=1) ) Tried multiple way but could not resolved the error. -
im trying to setup pytest for the first time but the path is not defined
I'm trying to configure pytest for the first time when i run the command: python -m pytest i get the following error: ImportError: No module named 'Socialmedia.settings.local'; 'Socialmedia.settings' is not a package pytest-django found a Django project in C:\Users\Alon\PycharmProjects\Socialmedia (it contains manage.py) and added it to the Python path. If this is wrong, add "django_find_project = false" to pytest.ini and explicitly manage your Python path. pytest file: [pytest] DJANGO_SETTINGS_MODULE = Socialmedia.settings.local python_files = test_*.py -
How do i fix the problem im having while programming on django
sorry if the explanation isn't very good or if this is a stupid question, im starting to learn djangoenter image description here i've tried changing the debug setting to 'False', but that doesnt allow me to start the server -
MPTT Multiple Inheritance Begins to Fail After Upgrade From Django3.0 to Django3.1
I've been having little luck trying to solve this issue so far. But in order to fix some vulnerable packages I'm upgrading a Django application from 2.8 -> 3.2, going from 2.8 -> 3.0 worked without issue, but as I go to 3.1 I begin failing in the collectstatic step due with the unhelpful django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Here is the definition for the affected class class OrganizationHierarchyNode( MPTTModel, WithAPI, ModelWithSoftDelete, metaclass=classmaker()): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) parent = TreeForeignKey( 'self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) hierarchy_level_map = models.ForeignKey( 'HierarchyLevelMap', null=True, blank=True, on_delete=models.SET_NULL) root = None created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='created_by', on_delete=models.CASCADE) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='modified_by', on_delete=models.CASCADE) hierarchy_scope = models.CharField(max_length=200, null=True, editable=False, blank=True) I'm using django-mptt v0.16.0 and python v3.9. I can see in the logs that it's failing when it calls that classmaker() function def classmaker(left_metas=(), right_metas=()): def make_class(name, bases, adict): print(f"ttyxl Name: {name}") print(f"ttyxl Bases: {bases}") print(f"ttyxl Adict: {adict}") metaclass = get_noconflict_metaclass(bases, left_metas, right_metas) print(f"ttyxl Metaclass: {metaclass(name, bases, adict)}") return metaclass(name, bases, adict) return make_class It will print out once for the base class ttyxl Name: OrganizationHierarchyNode ttyxl Bases: (<class 'mptt.models.MPTTModel'>, <class 'mgmt.api.models.with_api.WithAPI'>, <class 'mgmt.models.base.ModelWithSoftDelete'>) Then immediatly following that it will output ttyxl Name: _MPTTModelBaseWithAPIMeta … -
Static files not being served in nginx properly
I'm running a Django application with gunicorn and nginx. I have a server-side folder structure that looks like the following for my static files: +-- mysite.com/ +-- public/ --- favicon.ico --- robots.txt +-- bookmarks/ --- bookmarks.html +-- static/ --- base.js --- other.js My nginx config is fairly straightforward at the moment: server { server_name mysite.com location /static/ { autoindex off; root /home/myuser/mysite.com/public/; } location / { proxy_pass http://localhost:8001; proxy_set_header Host $host; } } Accessing any file within /static/ works just fine, but when I try to access my robots.txt file, I get a 404 - File Not Found. Adding a separate rule fixes this: location /robots.txt { alias /home/myuser/mysite.com/public/robots.txt; } Must I create a rule per static file / folder, or is there some blanket way to handle this? I'd love for any URL of the form mysite.com/some-file-here.txt to return some-file-here.txt assuming that it exists in my public/ folder on the server. In my example, accessing "mysite.com/bookmarks/bookmarks.html" should return that file, as its present on the server-side file system. What am I missing? -
Getting the Django ORM auth_user.id data using serializer
I have a model of SQLAlchemy. Here is my models.py: class PlaceInfoModel(Base): __tablename__ = 'place_info' id = Column(Integer, primary_key=True, autoincrement=True) owner_id = Column(Integer,nullable=False) name = Column(String(60)) address = Column(String(300)) rating = Column(Float) type = Column(String(20)) image = Column(String) serializer.py: from .models import PlaceInfoModel, sessionmaker,engine from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.fields import CurrentUserDefault class PlaceInfoSerializer(serializers.Serializer): name = serializers.CharField() address = serializers.CharField() rating = serializers.FloatField() image = serializers.CharField(required=False) owner_id = serializers.IntegerField() # i want to auto update it with auth_user.id on POST request This is my views.py: class PlaceViewSet(ViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticatedOrReadOnly, IsPermittedForAction] ordering_fields = ['id', 'name', 'rating', 'address'] def create(self, request): serializer = PlaceInfoSerializer(data=request.data) print(request.user.id) if serializer.is_valid(): Session = sessionmaker(bind=engine) session = Session() place = PlaceInfoModel(**serializer.validated_data) session.add(place) session.commit() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to populate my owner_id in serializers.py somehow from SimpleJWT authentication. I tried to do it with CurrentUserDefault() and failed. -
Is using a hidden input field safe if its value is never submitted?
I'm following a Django tutorial and at one point there is the need to access a template variable {{ totalPrice }} (sum of items in a shopping cart) in a javascript file. This value is critical in the sense that a user should not be able to lower it before it is processed by the javacript. The structure looks like this. checkout.html: Template HTML file which displays {{ totalPrice }}, the value being computed by and passed in via a Django view. checkout.js: The code in this file needs the value of {{ totalPrice }}. The proposed solution (by the tutorial) is as follows. {{ totalPrice }} is put into a hidden (bootstrap class="d-none") input field. The field is not part of a form and cannot be submitted. <input type="number" class="d-none" id="totalPrice" value={{ totalPrice }}> It is then accessed in checkout.js like this. let totalPrice = document.getElementById('totalPrice').value I have a couple questions about this approach. According to my research, using hidden input fields in this manner isn't safe (source1 source2). The first source in fact talks about the very same scenario where a price is stored. However, the difference is that in my scenario, the input field isn't part of … -
TypeError: User_info() got unexpected keyword arguments: 'is_staff'
I defined a table named User_info which inherited AbstractBaseUser and PermissionsMixin,when i tried to create superuser in terminal,it ocurred error...Here are my relative codes: I have scrutinized settings.py to insure the database and AUTH_USER_MODEL is correct from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Create your models here. class CustomUserManager(BaseUserManager): def create_user(self, account, password=None, **extra_fields): if not account: raise ValueError('用户账户必须被设置') user = self.model(account=account, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, account, password=None, **extra_fields): # 创建staff用户的逻辑 extra_fields.setdefault('is_staff', True) extra_fields['is_superuser'] = False # 确保staff用户不是超级用户 return self.create_user(account, password, **extra_fields) def create_superuser(self, account, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('超级用户必须拥有is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('超级用户必须拥有is_superuser=True.') return self.create_user(account, password, **extra_fields) class User_info(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=32) usr_id = models.CharField(max_length=20) number = models.CharField(max_length=12) account = models.CharField(max_length=20,unique=True) gender = models.CharField(max_length=1, choices=[('M', '男'), ('F', '女')], default='M') balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) #is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'account' REQUIRED_FIELDS = ['name', 'usr_id', 'number', 'gender'] # 除了密码和用户名之外的必填字段 def __str__(self): return self.account -
Add CSS Class for each tr Element if it contains specific value
I'm trying to add a class to an tr element in a form when the target value is "New Target". So far only the first Element will add the class, but not every other element where the target value is "New Target". This is my HTML-side: <table id="epoch_forms_table" class="epoch_forms_table"> <tr class="title_row"> <th>{% autoescape off %}{% trans "Target name" %}{% endautoescape %}</th> ... <th class="last"></th> </tr> <tr class="value_row{% if epoch_form.errors %} error{% endif %}"> <td></td> <td><label><input type="number" size="13" step="0.001"></label></td> <td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td> <td><a href="#" class="button icon remove remove_row_button danger"></a></td> </tr> <tr id="last_value_row" class="last_value_row target_background_color"> <td></td> <td></td> <td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td> <td></td> </tr> <tr class="error_row"> {% for field in epoch_form %} <td>{{ field.errors }}</td> {% endfor %} <td></td> </tr> </table> And this is my JavaScript-side: var new_target_element = document.getElementById("last_value_row"); var last_values = []; var index = $("#epoch_forms_table tr.value_row").index(value_row); ... for (let i = 0; i < el.length; i++) { for (let i = 0, cell; cell = new_target_element.cells[i]; i++) { if ($(this).find("td:contains('New target')")) { new_target_element.classList.add("new_target_color"); new_target_element.classList.remove("target_background_color"); } else { new_target_element.classList.add("target_background_color"); new_target_element.classList.remove("new_target_color"); } } } if (last_values[index].length === 0) { last_value_row.find("td:first").html("New target"); } else { ... } } I'm trying … -
Non-Deterministic behavior in PDF library when accessing Django model in between
A Django 4.2 on Python 3.10 application misbehaves sometimes, in a place that should be stateless. If I access the database (postgresql 14 via pcygopg 3.1.18) while working with pypdf 3.17.4, the output document is broken.. in roughly 1 out of 8 attempts. How can I determine the cause of the erratic behavior? The resulting PDF has missing content, so comparing output size is sufficient to determine the bug was triggered: # call as: python3 manage.py minrepro input.pdf import argparse, io from django.core.management.base import BaseCommand from pypdf import PdfReader, PdfWriter from djangoapp.models import DjangoModel def main(fin): pdfout = PdfWriter() pageout = pdfout.add_blank_page(width=200, height=200) for i in range(8): # Note: accessing the database *during* PDF merging is relevant! # without the next line, the problem cannot be reproduced for c in range(31): a = DjangoModel.objects.first() fin.seek(0) for pagein in PdfReader(fin, strict=True).pages: pageout.merge_page(pagein) with io.BytesIO() as fout: pdfout.write(fout) return fout.tell() class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument(dest="pdf", type=argparse.FileType("rb") ) def handle(self, *args, **options): for i in range(30): if i == 0: first_size = main(options["pdf"]) current_size = main(options["pdf"]) if not first_size == current_size: print(f"presumed stateless call was not {i=}, {first_size=} != {current_size=}") This is CPython with insert-ordered dicts, most code should behave the same … -
How to make many-to-many relation for multiple page models with one PageChooser field to select from all of them in Wagtail?
1. Introduction: It is quite easy to make a both side relation between more than two models by creating relation classess to cover all of them. For example: from django.db import models from modelcluster.fields import ParentalKey class NewsToCalendarRelation(models.Model): news = ParentalKey('pages.NewsPage', on_delete=models.CASCADE, related_name='news_calendar_source',null=True) calendar = ParentalKey('pages.CalendarPage', on_delete=models.CASCADE, related_name='news_calendar_target',null=True) class Meta: unique_together = ('news', 'calendar') class NewsToStaticRelation(models.Model): news = ParentalKey('pages.NewsPage', on_delete=models.CASCADE, related_name='news_static_source',null=True) static = ParentalKey('pages.StaticPage', on_delete=models.CASCADE, related_name='news_static_target',null=True) class Meta: unique_together = ('news', 'static') class StaticToCalendarRelation(models.Model): static = ParentalKey('pages.StaticPage', on_delete=models.CASCADE, related_name='static_calendar_source',null=True) calendar = ParentalKey('pages.CalendarPage', on_delete=models.CASCADE, related_name='static_calendar_target',null=True) class Meta: unique_together = ('static', 'calendar') And then to use in page model: class NewsPage(Page): related_news = ParentalManyToManyField('self', blank=True,symmetrical=True) related_calendar = ParentalManyToManyField('pages.CalendarPage', through=NewsToCalendarRelation, blank=True) related_static = ParentalManyToManyField('pages.StaticPage', through=NewsToStaticRelation, blank=True) content_panels = [ AutocompletePanel('related_news', target_model='pages.NewsPage'), AutocompletePanel('related_calendar', target_model='pages.CalendarPage'), AutocompletePanel('related_static', target_model='pages.StaticPage') ] class CalendarPage(Page): related_news = ParentalManyToManyField('pages.NewsPage', blank=True, through=NewsToCalendarRelation) related_calendar = ParentalManyToManyField('self', symmetrical=True) related_static = ParentalManyToManyField('pages.StaticPage', blank=True, through=StaticToCalendarRelation) content_panels = [ AutocompletePanel('related_news', target_model='pages.NewsPage'), AutocompletePanel('related_calendar', target_model='pages.CalendarPage'), AutocompletePanel('related_static', target_model='pages.StaticPage') ] and so for other models… 2. But it would be more efficient to have only one related pages field to choose from all pages. It is no problem to define chooser field for that either PageChooserPanel or AutocompletePanel('related_all', target_model='wagtailcore.Page'). But there is a problem with creating an universal relation between page … -
Optimal Kubernetes Deployment Strategy for Django with Gunicorn (Multi-Process): Fewer Multi-Process Pods vs. One Process per Pod
I'm architecting a Django application to be deployed on Kubernetes, utilizing Gunicorn as the WSGI server with multiple workers configured, essentially adopting a multi-process setup. Given the multi-process nature of my setup, I'm faced with a deployment decision and seeking your experienced opinions on the matter: Deploying Fewer Pods Running Gunicorn with Multiple Workers (Processes) Each: This approach involves deploying a smaller number of pods, where each pod runs a Gunicorn instance configured with multiple workers. My main considerations are around how this setup would affect resource utilization, fault isolation, and resilience of the system as a whole within a Kubernetes environment. Deploying More Pods, Each Running a Single Gunicorn Worker (Process): The alternative is deploying a larger number of pods, with each pod running a Gunicorn instance configured to run a single worker. While I see the potential benefits in terms of fault isolation and scalability, I'm concerned about the overhead and whether this might lead to inefficient resource utilization. I would greatly appreciate insights or experiences related to: Resource Management: How do these approaches compare in terms of resource allocation efficiency and potential overhead in a Kubernetes context? Fault Tolerance and Isolation: Does one strategy offer significant advantages …