Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django only() and values() are not working with prefetch_related()
I want to filter the fields retrieved in a query and get the reverse foreign key using the related_name in a child model using prefetch_related() for the sake of performance optimization when reaching a huge number of database records. I have the following "Seller" Model: class SellerQuerySet(models.QuerySet): def annotate_seller_salary(self): return self.annotate(seller_salary=F('points')*100) class SellerManager(models.Manager): use_for_related_fields = True def annotate_seller_salary(self): return self.get_queryset().annotate_seller_salary() def get_queryset(self): return SellerReviewQuerySet(model=self.model, using=self._db) class Seller(models.Model): name= models.CharField(max_length=50) points= models.IntegerField(default=0) address= models.TextField(max_length=100) And "Product" Model: class Product(models.Model): name= models.CharField(max_length=50) quantity= models.IntegerField(default=0) seller= models.ForeignKey(Seller, on_delete=models.CASCADE, related_name="seller_products") I'm trying to get all the products grouped by the seller. But the issue is that If I retrieved the products first and then tried to group it by the seller, I will not be able to retrieve the annotation function for the "Seller" model along with it. So, I would need to start by retrieving the "Seller" object with its annotations and then use prefetch_related() and Prefetch() to get the Products using the related_name for the seller foreign key. BUT! The problem is, I don't want to get all the "Seller" model fields. I ONLY need the points field and the annotation attribute seller_salary along with the "Product" objects that are associated with … -
Django's on_commit difference in behavior when triggered via Django admin
I am trying to send api call via transaction.on_commit and it is kind of working but I am seeing a different behavior when I edit the model via Django admin vs when this code is triggered by some other means. I have UserRoles model where I am calling post_save.connect(sync_user_roles, sender=UserRole) then in the sync_user_roles(self, **kwargs) I am calling transaction.on_commit( lambda: self._proc_user_role_sync( kwargs["instance"], pre_edit_users=[u.username for u in kwargs["instance"].users.all()], user_role=user_role, library_id=library_id, ) ) And I am just trying to print new users in the _proc_user_role_sync def _proc_user_role_sync( self, instance: "models.UserRole", pre_edit_users: List[str], user_role: str, library_id: str, ): print(f"new users: {[u.username for u in instance.users.all()]}") Whenever I edit user_roles via Django admin, I see the new state of db in the _proc_user_roles_sync, meaning the newly added user is showing up in the print statement. But whenever I trigger this code by making API call to backend, new user is not showing in the print statement, even though I can see it being stored in the db. What exactly is causing this difference and how can I make sure that the newly added user shows up in the _proc_user_role_sync every time the code is triggered? -
Django registration form not hashing password
I'm building a student management system, but there's a problem. When I register a new user, i enter it's username, first name, last name, etc... and password of course. But when I save the form and insert the user in the database, the password is stored as plain text and not hashed. On the other hand, when I create user thru django admin panel the user password i hashed normally and login works... Here is my code: views.py def addUser(request): if request.method == 'GET': form = AddNewUserForm() return render(request, 'addNewUser.html', {'form': form}) if request.method == 'POST': form = AddNewUserForm(request.POST) if form.is_valid(): password = make_password(form.cleaned_data['password']) form.password = password form.save(make_password(form.cleaned_data['password'])) print("New user added!") return render(request, 'addNewUser.html', {'form': form}) return redirect('/users/') .html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST"> {{form}} {% csrf_token %} <input type="submit" value="Add new user"> </form> </body> </html> -
I could not understand a function for the ManyToMany field listing in Django
Non of the similar questions auto listed answer my question: I have the models.py as follows: ```from django.db import models class Location(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=300) def __str__(self): return f'{self.name} ({self.address})' class Participant(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Meetup(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) description = models.TextField() image = models.ImageField(upload_to='images') location = models.ForeignKey(Location, on_delete=models.CASCADE) participants = models.ManyToManyField(Participant) def __str__(self): return f'{self.title} - {self.slug} - {self.description}'``` In order to be able to list the two emails I entered via the Admin panel I had the following Admin.py ```from django.contrib import admin from .models import Meetup, Location, Participant # Register your models here. class MeetupAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'description', 'location', 'get_emails') def get_emails(self, obj): return "\n".join([p.email for p in obj.participants.all()]) list_filter = ('title', 'description') prepopulated_fields = {'slug': ('title', )} search_fields = ('title', ) admin.site.register(Meetup, MeetupAdmin) admin.site.register(Location) admin.site.register(Participant)``` Without using the function return "\n".join([p.email for p in obj.participants.all()])``` I would not have been able to list the two emails represented by the ManyToMany relation My question here is: I would like to understand what does the p and obj here. I would be so grateful if someone could explain how this work. -
Django signals error with Foreign Keys - post_delete on related objects gets called before pre_delete on the ForeignKey
I have 2 model classes: class Company: name = models.... pending_delete = BooleanField class User: company = ForeignKey(Company, CASCADE) On the pre_delete of Company, I try to set pending_delete to True, so that I can access it when the post_delete signal of User is called because of CASCADE. However, for some reason the pre_delete signal (of Company) runs after the post_delete signal of User. This might be intended but I'm not sure that I understand why. -
how to solve the Django ORM N+1 Query performance problem when I didn't use Foreign Key
I carried out the development without setting the Foreign Key in the early stages of development because frequent design modifications were difficult. That's how the service is operated, and performance issues such as N+1 Query problems have occurred. If you look for ways to improve performance, I recommend methods such as select_related(), fetch_related(), etc., and I would appreciate it if you could tell me how to improve without using Foreign_Key. It is a service that is already in operation, so it is virtually impossible to apply the Foreign Key one by one. -
Add an ID field in django ORM
I have an Employee model in my django app like the following: class Employee(models.Model): role_choices = (('CRUD', 'CRUD'), ('View', 'View')) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="company") name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=500, default=0) phone = models.CharField(max_length=500, default=0) city = models.CharField(max_length=500, default=0) But now I want to remove this user field but since it's primaryKey it is asking me to do this: You are trying to add a non-nullable field 'id' to employee without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: providing a value will result in an error since there is no point in giving a single id as default value. How to solve this ? -
What is the correct way to generate a CSV file in Django, Django REST Framework and send it as a streaming response from a POST request?
Generate CSV file using POST request I try to achieve csv download using POST request by below code but not able to get file response it is returning normal response. What will be the valid approach to achieve streaming file response using POST request? import csv from django.http import StreamingHttpResponse from rest_framework.decorators import api_view def generate_csv_data(): # Generate your CSV data here csv_data = [ ['Name', 'Email'], ['John Doe', 'john.doe@example.com'], ['Jane Smith', 'jane.smith@example.com'] ] # Yield each row of CSV data for row in csv_data: yield ','.join(row) + '\n' @api_view(['POST']) def download_csv(request): response = StreamingHttpResponse(generate_csv_data(), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="data.csv"' return response -
django error in auth user model ValueError: Related model 'pcpartpicker.user' cannot be resolved
I am using django authentication and it keeps giving me this error when I run the migrate cmd ValueError: Related model 'pcpartpicker.user' cannot be resolved This is my model : from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass Functions: from django.shortcuts import redirect , render from .error import error from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from ..models import User def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/") else: return error("102", "Invalid username or password", request) else: return render(request, "login.html") def logout_view(request): logout(request) return redirect("/") def register(request): if request.method == "POST": email = request.POST["email"] password = request.POST["password"] confirmation = request.POST["Cpassword"] if password != confirmation: return error("203", "passwords do not match", request) try: user = User.objects.create_user(email, email, password) user.save() except IntegrityError: return error('102', "email in user", request) login(request, user) return redirect('/') else: return render(request, "register.html") login.html {% extends 'layout.html' %} {% block body %} <section class="bg-gray-50 dark:bg-gray-900"> <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0"> <div class="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div class="p-6 space-y-4 md:space-y-6 sm:p-8"> <h1 class="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white"> … -
Paginator in View class everytime call request
I have view with paginate_by field by 6 per page and i pull my request from 3rd party api into view queryset So i have question, everytime i go on page 2 or others, queryset is calling request from api again, so i have to wait to page to load that request. I need to load request and paginate trough that request without calling it on another pages of paginator So how am i suppose to do it? views.py class CustomerContractsListView(LoginRequiredMixin, ListView): template_name = 'contracts/customer/contracts.html' context_object_name = 'list_of_contracts' paginate_by = 6 def get_queryset(self): current_object = self.request.GET.get('ObjectGUID') current_counter_party = self.request.GET.get('CounterpartyGUID') url = config('API_ENDPOINT') + 'GetListContracts' if current_object is not None: object_name = ObjectList.objects.get(GUID=current_object) url = config('API_ENDPOINT') + 'GetListContracts' + '?ObjectGUID=' + str(current_object) if current_counter_party is not None and current_object is not None: url = url + '&CounterpartyGUID=' + str(current_counter_party) url = config('API_ENDPOINT') + 'GetListContracts' + '?ObjectGUID=' + str(current_object) + \ '&CounterpartyGUID=' + str(current_counter_party) response = requests.get(url).json() queryset = [] dict_of_counter_party = {} all_counter_party = CounterParty.objects.all() for i in all_counter_party: dict_of_counter_party[i.GUID] = i.name for item in response: my_js = json.dumps(item) parsed_json = ListContractsSerializer.parse_raw(my_js) for counter in parsed_json.ListOfCounterparty: counter.CounterpartyGUID = dict_of_counter_party[UUID(counter.CounterpartyGUID)] queryset.append(counter) for contracts in counter.ListOfContract: contracts.VAT = contracts.VAT * 100 queryset.append(contracts) return … -
Cant update one to one field in django
views.py file Groups.objects.filter(user_id=request.user.id, group_name=product_name).update(category_id=category) models.py file class Groups(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='Groups_user', unique=False) group_name = models.CharField(max_length=100) links = models.TextField(default='', null=True, blank=True) description = models.TextField(default='', null=True, blank=True) state = models.CharField(default='false', max_length=10) category = models.OneToOneField(ProductCategory, on_delete=models.CASCADE, null=True) Is this correct way to update OneToOne field? I also tried another method but didnt work product = Groups.objects.get(user_id=request.user.id, group_name=product_name) product.category_id = category_id product.save() The error I am getting in pythonanywhere server is OSError: write error. It seems weird. -
Special character and accent marks in Django
I have created a search functionality in django. When I searched for the chateau, it showed the interest with the name Château But when I searched for arpege, it didn't show interest with the name Arpège Here is my code: interest = Interest.objects.filter( Q(name__icontains=searched) | Q(text__icontains=searched) | Q(info1__icontains=searched) | Q(info2__icontains=searched) | Q(info4__icontains=searched) | Q(info5__icontains=searched) | Q(filter_tags__icontains=searched) | Q(meta_description__icontains=searched) | Q(meta_keywords__icontains=searched) ).order_by("-rating") I want to be able to convert all of the special characters in the field "name" in the database first before comparing it with "searched", so I can get the Interest with the name Arpège even if I type arpege. -
Fetching data about tracking Air Cargo with AWB number
I'm a beginner level developer, i want to build a website for AWB (Air Cargo Tracking) tacking. Kindly suggest some ways i can achieve this. I have searched this topic on internet and I'm still confuse about how can i deal with this problem. -
Celery chain of groups and tasks doesn't call next task if group fails
I have created a celery chain that consists of group of tasks and normal tasks, shown below @app.task def task_init(id): # do something print(id) @app.task def task_to_group(id): # do something # raise exception try: print(id) except Exception: raise @app.task def task_status(id): # do something # update the status (end process) if id == 1: id = 2 print(id) @app.task def task_error_handler(id): # do something # handle the failure. update status in db to failed. if id == 1: id = 2 print(id) Created canvas as: id = 1 # this some primary key id from db. chunk = [ task_to_group.si(id).on_error(task_error_handler.s(id)) for id in range(0,5) ] c = chain( task_init.si(id) group(), task_status.si(id) ).on_error(task_error_handler.s(id)) c.apply_async() So, basically the problem I am facing is, if a task in task_to_group fails/raises exception the on_error on that task is called but in the end in the chain the next task to execute be either task_status or on_error``task_error_handler should be called. But none of them are called. The thing I want is, if any task in group fails, the task_error_handler of that group should be called and keep running rest of tasks in group. After group is done the next task either task_status on task_error_handler should … -
How do I fix 'Module social_core.backends.google does not define a GoogleOpenId attribute/class' error in Django login?
I pulled the old Django project but when I log in, I got the following error. Module "social_core.backends.google" does not define a "GoogleOpenId" attribute/class I searched for this error but I can't find any solution. I tried this but not working. Django ImportError: Module "social_core.backends.google" does not define a "GoogleOpenId" attribute/class -
Django/python - boolean checking if id in list of IDs returning false even though it's there?
I am working on the views file for my django project. There is a POST method that checks if an ID is in a list of IDs, but for some reason it's returning false, saying that the posted ID is not in the list. I can see very clearly that it's there. Here is the method: if response.POST.get("followUser"): userToFollowID = response.POST.get("followUser") listOfFollowedUsers = list(userFollowing.objects.filter(username=userInfo.id).values_list('followingList', flat=True)) print(userToFollowID) print(listOfFollowedUsers) print(userToFollowID in listOfFollowedUsers) if userToFollowID not in listOfFollowedUsers: print("we are here?") # t = userFollowing(username = userInfo, followingList = User.objects.get(id=userToFollowID)) # t.save() There's a lot of print statements and jargon, but basically it's supposed to check the POSTed ID and see if it's in the current users list. If the ID is not in the list, it goes into the method and it's supposed to create the database entry. This is the output from the print statements: Output So the POSTed ID in this case is 6, the current user is following [6, 6] (supposed to have unique IDs but will fix afterwards) yet the code print(userToFollowID in listOfFollowedUsers returns false even though it should be True. We get into the if statement and it prints we are here? even though it shouldn't. … -
What is it called when you hash a URL params and map it to the database?
Hi I'm working with Django as my backend and I've been trying to search up this term but I can't seem to find it. For example Spotify has a URL for a song https://open.spotify.com/track/0feI2qZLlaapheeJeznYwZ I'm guessing the hashed ID maps to one of the autogenerated ID's. What would I search up to implement this in my app ? Any references will be greatly appreciated. Thanks in advance :) -
"OperationalError at /checkout table home_checkout has no column named name" in my Django project
Hello to who ever sees this, Hope you all are doing great, I was working on my first Django project and I am facing this error for a while now. I added another form in same format without any hussle but idk why this is happening with this particular form. Hope I could get some help. Thanks in advance. python version - 3.11.3 Django version - 4.2 models.py from django.db import models class Checkout(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phone = models.CharField(max_length=122) address = models.TextField() date = models.DateField() def __str__(self): return self.email views.py from django.shortcuts import render,HttpResponse from datetime import datetime from home.models import Checkout def checkout(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') date = datetime.today() checkout = Checkout(name=name , email = email, phone = phone, address= address, date=date) checkout.save() return render(request, 'checkout.html') HTML code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Checkout</title> </head> <body> <form action="checkout" method="post"> {% csrf_token %} <input type="text" name="name" id="name" placeholder="Name"> <input type="email" name="email" id="email" placeholder="Email"> <input type="text" name="phone" id="phone" placeholder="Phone number"> <textarea name="address" id="address" placeholder="Please enter your address"></textarea> <input type="submit" name="send" id="send" value="Checkout"> </form> </body> </html> … -
How to implement async view through class-based view(CBV) in Django
An AssertionError occurred while trying to operate asynchronous view as class-based view in django(CBV) The python code i wrote is as follows. urls.py from django.contrib import admin from django.conf.urls import include from django.urls import re_path from rest_framework import routers from blog import views router = routers.DefaultRouter() router.register(r'test', views.TestView, 'hello') urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'', include(router.urls)), re_path(r'async_view/', include(router.urls)) ] views.py class TestView(viewsets.ViewSet): LOG = logging.getLogger('test') async def list(self, request, *args, **kwargs): self.LOG.info("async method start!!") queryset = Post.objects.none await asyncio.sleep(3) return HttpResponse("Hello async world!") asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_asgi_application() When i execute command below uvicorn mysite.asgi:application --limit-concurrency 12 --reload --host 0.0.0.0 --port 80 then, An AssertionError occurred AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>` Which part is wrong?? -
React/Django User Register gives me (400 Bad Request)
When I try registering new users through the frontend, it doesn't automatically log me in and it tells me that these new users' emails already exist. From what I can see from Django Admin, the users do get saved/registered and I can login with them. However, it's bothering me that I'm getting these errors and that the new user isn't getting logged in immediately upon creation. This is my first project with Django and redux so any help would be immensely appreciated. Registration Error: {detail: "User with this email already exists"} detail: "User with this email already exists" This is the error I get on the network tab. Console Errors: POST http://localhost:3000/api/users/register/ 400 (Bad Request) Errors that appear on the console Login Errors Errors I get when I login in with an existing user. I don't know if this will effect the function, but my priority is getting the registration issue resolved. RegisterPage.js import React, { useEffect, useState } from "react"; import { Link, useLocation, useNavigate } from "react-router-dom"; import { Form, Button, Row, Col } from "react-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import FormContainer from "../components/FormContainer"; import { login, … -
How do I Display a Dynamic Message Based on Form Values in a Django Template
I want to display different text based on the checked radio button/form value in a Django template, but I'm not sure how I can get a hold of the value and use it. I tried using the value of the form passed up from the view, but that doesn't update on input change. <div class="form-group"> <label for="radio_choice">Radio Choices</label> <br /> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="radio_choice" id="radio-choice-one" value="RCO" /> <label class="form-check-label" for="radio-choice-one">Radio Choice One</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="radio_choice" id="radio-choice-two" value="RCT" /> <label class="form-check-label" for="radio-choice-two">Radio Choice Two</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="radio_choice" id="radio-choice-three" value="RCTh" /> <label class="form-check-label" for="radio-choice-three">Radio Choice Three</label> </div> <br /> <small class="text-black-50"> {% if form.radio_choice.value == 'RCO' %} <b>Radio Choice One</b> - Some text about choice one {% elif form.radio_choice.value == 'RCT' %} <b>Radio Choice Two</b> - Some text about choice two {% elif form.radio_choice.value == 'RCTh' %} <b>Radio Choice Three</b> - Some text about choice three {% endif %} </small> </div> -
Troubleshooting Sentiment Analysis in Django Python Project
models.py code file = models.FileField(upload_to='uploads/') result = models.JSONField(null=True) def analyze_sentiment(self): file_path = "D:/python/analyse/uploads" with open(file_path, 'r', encoding='utf-8') as f: input_sentences = f.readlines() stop_words = [] with open('D:/python/analyse/analyse/models/stopwords.txt', 'r') as f: stop_words = [line.strip() for line in f] positive_words = [] with open('D:/python/analyse/analyse/models/positive_words.txt', 'r') as f: for line in f: word, weight = line.strip().split(',') positive_words.append((word, float(weight))) negative_words = [] with open('D:/python/analyse/analyse/models/negative_words.txt', 'r') as f: for line in f: word, weight = line.strip().split(',') negative_words.append((word, float(weight))) emotion_weights = {} with open('D:/python/analyse/analyse/models/emotion_words.txt', 'r') as f: for line in f: word, emotion, weight = line.strip().split(',') if word not in emotion_weights: emotion_weights[word]= {} emotion_weights[word][emotion] = float(weight) # Initialize counters for each sentiment type num_positive, num_negative, num_neutral, num_emotional, num_sarcastic = 0, 0, 0, 0, 0 # Loop through each sentence and analyze its sentiment for sentence in input_sentences: # Tokenize the sentence into words words = sentence.lower().split() # Remove stop words from the sentence words = [word for word in words if word not in stop_words] # Calculate the sentiment score of the sentence sentiment_score = 0 for word, weight in positive_words: if word in words: sentiment_score += weight for word, weight in negative_words: if word in words: sentiment_score -= weight # Determine the overall sentiment of … -
Django Inactivity Middleware not automatically logging user out
After a 10 minute inactivity interval, I want to log my django user out and update a backend value. However, it is only working when I reload my page or send some sort of request to the server after the 10 minute time interval. Here is my current middleware code: from datetime import datetime, timedelta from django.contrib.auth import logout from codera_main.models import UserDetail class InactivityMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check if the user is authenticated if request.user.is_authenticated: # Check if the session has expired if request.session.get_expiry_age() <= 0: # Log out the user and consider them inactive user_detail = UserDetail.objects.get(user=request.user) if user_detail.isCurrentlyActive: user_detail.isCurrentlyActive = False user_detail.save() print(f"User {user_detail.user} is now inactive and logged out.") logout(request) else: # Retrieve the last activity timestamp from the session last_activity = request.session.get('last_activity') # Check if the last activity timestamp exists and is valid if last_activity: last_activity = datetime.fromisoformat(last_activity) time_since_last_activity = datetime.now() - last_activity print(f"User {request.user} last activity: {last_activity}") print(f"Time since last activity: {time_since_last_activity}") # Check if the user is inactive for more than 10 minutes if time_since_last_activity > timedelta(minutes=10): # Log out the user and consider them inactive user_detail = UserDetail.objects.get(user=request.user) if user_detail.isCurrentlyActive: user_detail.isCurrentlyActive = False user_detail.save() print(f"User … -
Validation of the serial number against the mask [closed]
Валидация серийного номера на соответствие маске Есть две таблицы - тип оборудования и оборудование, у типа есть строка с маской серийного номера, у оборудования есть строка с серийным номером. При создании нового оборудования, должна пройти валидация, то есть строку с серийным номером сравнивают с каждой маской типа оборудования и если обнаруживается соответствие - оборудование прявязывается к типу, вопрос такой, как это лучше реализовать на django rest framework? Проверка осуществялется по принципу: N – цифра от 0 до 9; A – прописная буква латинского алфавита; a – строчная буква латинского алфавита; X – прописная буква латинского алфавита либо цифра от 0 до 9; Z – символ из списка: “-“, “_”, “@”. То есть если оборудование имеет серийный номер 0QWER9@123, ему соответствует маска с символами вида NAAAAXZXXX models.py from django.db import models from django.core.validators import MinLengthValidator from django.core.validators import RegexValidator class Type_Of_Equipment(models.Model): name = models.CharField(verbose_name='Тип оборудования', max_length=64, blank=True, default='Без названия') sn_mask = models.CharField(verbose_name='Маска серийного номера', blank=False, max_length=10, validators=[MinLengthValidator(10), RegexValidator(regex=r'^[NAaXZ]+$', message='Использованы недопустимые символы')]) class Equipment(models.Model): code = models.CharField(verbose_name='Код типа оборудования', max_length=64, blank=True) sn_number = models.CharField(verbose_name='Серийный номер', max_length=10, blank=False, unique=True, validators=[MinLengthValidator(10), RegexValidator(regex=r'^[A-Za-z0-9-_@]+$', message='Использованы недопустимые символы')]) type_of_equipment = models.ForeignKey(Type_Of_Equipment, on_delete=models.DO_NOTHING) is_deleted = models.BooleanField(default=False) # Заготовки для мягкого удаления. def soft_delete(self): self.is_deleted = True self.save() def … -
Error regarding git push heroku main command, pywin32 error
When I am trying to push my new project, I have the following errors when I run git push heroku main in my terminal: remote: INFO: pip is looking at multiple versions of pypiwin32 to determine which version is compatible with other requirements. This could take a while. remote: ERROR: Ignored the following versions that require a different python version: 1.9.5 Requires-Python >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <3. 7 remote: ERROR: Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions: none) remote: ERROR: No matching distribution found for pywin32>=223 remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed This is my requirements.txt file asgiref==3.3.2 astroid==2.4.2 asttokens==2.2.1 backcall==0.2.0 beautifulsoup4==4.9.3 bootstrap4==0.1.0 boto==2.49.0 boto3==1.17.101 botocore==1.20.101 cffi==1.14.5 chromelogger==0.4.3 colorama==0.4.4 comm==0.1.2 debugpy==1.6.6 decorator==5.1.1 distro==1.5.0 dj-database-url==2.0.0 Django==3.2 django-bootstrap3==14.2.0 django-bootstrap4==3.0.1 django-braces==1.14.0 django-crispy-forms==1.11.2 django-debug-toolbar==3.2.1 django-developer-panel==0.1.2 django-misaka==0.2.1 django-storages==1.11.1 django-widget-tweaks==1.4.8 executing==1.2.0 google-compute-engine==2.8.13 gunicorn==20.1.0 houdini.py==0.1.0 importlib-metadata==6.0.0 ipykernel==6.21.2 ipython==8.10.0 isort==5.7.0 jedi==0.18.0 jmespath==0.10.0 jsonpickle==2.0.0 jupyter_client==8.0.3 jupyter_core==5.2.0 lazy-object-proxy==1.4.3 matplotlib-inline==0.1.6 mccabe==0.6.1 misaka==2.1.1 nest-asyncio==1.5.6 numpy==1.24.2 ordereddict==1.1 packaging==23.0 pandas==1.5.3 parso==0.8.1 pickleshare==0.7.5 Pillow==8.2.0 platformdirs==3.0.0 prompt-toolkit==3.0.37 psutil==5.9.4 psycopg2==2.9.6 psycopg2-binary==2.9.6 pure-eval==0.2.2 pycparser==2.20 Pygments==2.9.0 pylint==2.6.0 pypiwin32==223 python-dateutil==2.8.1 pytz==2021.1 pywin32==305 pyzmq==25.0.0 s3transfer==0.4.2 six==1.15.0 soupsieve==2.2.1 sqlparse==0.4.1 stack-data==0.6.2 toml==0.10.2 tornado==6.2 traitlets==5.9.0 typing_extensions==4.5.0 tzdata==2023.3 urllib3==1.26.6 wcwidth==0.2.6 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.14.0 And also I am using python-3.9.16 …