Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web world wind implementation in python django [closed]
I am trying to implement web world wind through django framework. The plan is viewing some flight data on virtual globe. For that i tried to use nasa web world wind. I managed to view the index page through manage.py runserver. But the virtual globe is not coming. Any help Page is rendered from server, js controls are loading but the globe is not loading. -
Django 4, ValueError: 'MyModel' instance needs to have a primary key value before this relationship can be used
The issue is a result from the update to django 4, in prior versions the issue was not present. When performing a reverse lookup on a foreign key relation, if the object being used for the reverse look up has not been save to the db (The object has no pk) an exception is raised, ValueError: 'MyModel' instance needs to have a primary key value before this relationship can be used. For example: class Author(models.Model): name = models.CharField(max_length=100) biography = models.TextField() class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) publication_date = models.DateField() new_author = Author(name='John Doe', biography='A new author') reverse_look_up = new_author.book_set.all() # this raises the issue. In django 3.2 and lower, performing this action wouldn't raise an error but rather return an empty queryset of book. You can solve this issue manually, by checking if the object has an id and then only performing the look up if it does, or by saving the object before hand, however I perform this kind of look up in numerous places and it would be difficult to do so. Would there be anyway to perform a generic fix for this, whether it be a change I can make to the model … -
Django Channels chat with one user
I completed my Django Channels. I have confusion about. How to make conversation between two user (me and user2) only. Is it possible to make conversation between only two user (me and user2) without making group If I make group than anyone can join the group and the user2 need to join the group. How can I send messages direct to the user2 -
Do repeated imports into views affect performance in a Django application?
In a situation like this: # views.py def myView(request): import something import other something.doStuff() other.doOtherStuff() return render(request, 'page.html', context) def myOtherView(request): import something import other something.doThings() other.doOtherThings() return render(request, 'page2.html', context) Is importing stuff at view-level a bad practice? Does it affect performance? # views.py import something import other def myView(request): something.doStuff() other.doOtherStuff() return render(request, 'page.html', context) def myOtherView(request): something.doThings() other.doOtherThings() return render(request, 'page2.html', context) Is this second version better/faster? -
Trying to run django project & i get this error mysql.connector.errors.ProgrammingError: 1045(28000)
I am trying to run a project i downloaded from the internet 'geymmanage' i installed all the required libraries. I have also installed mysql and sqlite3 as well (in the project settings i found sqlite3 as backend) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } and in the views.py conn = mcdb.connect(host="localhost", user="root", passwd="", database='myproject1') I tried running the django project but it gives me this error `raise get_mysql_exception( mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Detailed Error Watching for file changes with StatReloader Performing system checks... Successfully connected to database Exception in thread django-main-thread: Traceback (most recent call last): File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/mysql/connector/connection_cext.py", line 308, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Access denied for user 'root'@'localhost' (using password: NO) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/checks/urls.py", … -
Django signals for different apps
I need to have separate signals for each app of my project. But after saving a model in one of the apps signals trigger from all apps, so I have duplicated messages from my signals. What is the right way to set up signals for different apps of Django project? signals.py of my app1: # -*- coding: utf-8 -*- import logging from django.db.models.signals import post_save from django.dispatch import receiver from .models import * @receiver(post_save) def log_app1_updated_added_event(sender, **kwargs): '''Writes information about newly added or updated objects of app1 into log file''' logger = logging.getLogger(__name__) app1_object = kwargs['instance'] if kwargs['created']: logger.info(f'added {app1_object }') else: logger.info(f'updated {app1_object }') signals.py of my app2: # -*- coding: utf-8 -*- import logging from django.db.models.signals import post_save from django.dispatch import receiver from .models import * @receiver(post_save) def log_app2_updated_added_event(sender, **kwargs): '''Writes information about newly added or updated objects of app2 into log file''' logger = logging.getLogger(__name__) app2_object = kwargs['instance'] if kwargs['created']: logger.info(f'added {app2_object }') else: logger.info(f'updated {app2_object }') apps.py of my app1: from django.apps import AppConfig class App1Config(AppConfig): name = 'App1' def ready(self): from app1 import signals apps.py of my app2: from django.apps import AppConfig class App1Config(AppConfig): name = 'App2' def ready(self): from app2 import signals and here … -
Cant get rid of FileNotFoundError in Django ImageField
I have a django model Product which has an image field class Product(BaseProduct): img_height = models.PositiveIntegerField(editable=False, null=True, blank=True) img_width = models.PositiveIntegerField(editable=False, null=True, blank=True) file = models.ImageField('Image', upload_to=product_img_path, height_field='img_height', width_field='img_width', null=True, blank=True, max_length=255) Now because I loaded the products from an Excel file with records over 15,000 there are few that the image path in the file field does not actually exist in my directory. This causes my code to raise a FileNotFoundError every time i try to for product in Product.objects.all() before I am even able to catch the error with a try-except block. I'd like to have an iteration where I can check if the file exists and set the file field to null for records with non-existing files. But this is impossible because the error is raised once I try to call an instance of the artwork or I create the iteration. So the code below: products = Product.objects.all() for product in products: try: if product.file: pass except FileNotFoundError: product.file = None product.save() Raised error: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\project\\media\\products\\blahblah.jpeg' and the stack trace shows error was raised from the iteration line for product in products: I have tried following this thread without any … -
Wagtail PageChooserBlock custom ordering
I'm using PageChooserBlock to display list of objects class ActualSection(models.Model): content = StreamField( [ ("article", PageChooserBlock(page_type="articles.Article")), ], min_num=1, ) Is there any way to put some custom ordering on it? Because now it's seems like having some random order -
how to make a custom error for empty input in a field (i.e. name = serializers.CharField(required=True))?
name = serializers.CharField(required=True) def validate(self,data): if not name: //Return error I want to validate name or check if it's empty in def validate_name(self,value): I tried to trigger def validate and def validate_name and I expected a return from there but instead I am getting error from default rest framework -
How to get header value to the particular class?
def prep_head(self, requestParams, requestType,): return { 'content-type': "application/json", 'id': "xyz" } How to add the id header dynamically? I want to power this one on the prod link. Anhybody please help!!!!!!!!!!!! -
Django pagination of filtered post list
I've been working on a project of a blog where all posts are grouped by rubrics. The posts can be filtered by rubric in the frontend but I've got some problems whith implementing pagination. Paginator works fine and paginates filtered list, when I choose a rubric on my site it shows the number of pages and shows link to the next. But the url it forms ignores rubrication and instead of sending me to something like localhost/blog/?rubric=some_rubric&page=2 it shows localhost/blog/?page=2 The pagination works fine if I input adress by hand. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .filter(status=Post.Status.PUBLISHED) class Rubric(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Rubrics' ordering = ('name',) indexes = [models.Index(fields=['name']),] def __str__(self): return self.name class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') cover_img = models.ImageField(upload_to='post_covers/', blank=True, null=True) rubric = models.ForeignKey(Rubric, on_delete=models.CASCADE, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') excerpt = models.TextField(max_length=500) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) objects = models.Manager() # The … -
I am getting error in console "You need to enable JavaScript to run this app."
I am working on a site that has a back-end with django and a front-end with react js, it was running well locally, but when I run the command on the cloud server, I get the error "You need to enable JavaScript to run this app". JavaScript is enabled in the browser, I also tried different browsers. But I get the same error in all browsers. Please someone help me to overcome this error. -
Gptcache and streaming are incompatible
Now, I have made a chatbot which can stream and answer the question from user. However that chatbot can't stream showing no error in terminal after I implemented init_cache() and changed llm. Here are some parts of my code: class CustomStreamingCallbackHandler(BaseCallbackHandler): """Callback Handler that Stream LLM response.""" def __init__(self, queue): self.queue = queue def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Run on new LLM token. Only available when streaming is enabled.""" self.queue.put(token) def generate_stream(q: Queue, job_done): while (...): try: stream = q.get(True, timeout=1) print(stream) yield stream except: continue def openai_response_generator(queue, retriever, prompt, query, chat_history, job_done): llm = LangChainChat( chat=ChatOpenAI( model_name="gpt-3.5-turbo-16k", streaming=True, temperature=0, callbacks=([CustomStreamingCallbackHandler(queue)]), )) chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=retriever, condense_question_prompt=prompt, return_source_documents=True, ) res = chain({'question': query, 'chat_history': chat_history}) print(res["answer"]) queue.put(job_done) def get_content_func(data, **_): return data.get("messages")[-1].content def init_cache(): onnx = Onnx() cache_base = CacheBase('sqlite') vector_base = VectorBase('faiss',dimension=onnx.dimension, collection_name='for_cache') data_manager = get_data_manager(cache_base, vector_base) cache.init( pre_embedding_func=get_content_func, embedding_func=onnx.to_embeddings, data_manager=data_manager, similarity_evaluation=SearchDistanceEvaluation(max_distance=1), ) cache.set_openai_key() # save data to cache from getting one answer cache.config.auto_flush = 1 init_cache() task = threading.Thread( target=openai_response_generator, args=(queue, retriever, prompt, query, chat_history, job_done) ) task.start() Before I changed llm, it was: llm = chatOpenAI( model_name="gpt-3.5-turbo-16k", streaming=True, temperature=0, callbacks=([CustomStreamingCallbackHandler(queue)]), ) Could you help me with that? I have already tried to change … -
DJango how to set up api and testing in Insomnia?
What should I add in the urls or views? I want to create an api and test in Insomnia, my app name called jqeshop and i create a table call product, i try to get it and display, after that i want to pass it to frontend, it just a practice for me, i need some one help enter image description here enter image description here enter image description here enter image description here This is the error message -
In Django AuthenticationForm, how to check only email and password is_valid
I tried to do this to remove username validation def clean_username(self): return "valid_username" But the is_valid() method is showing false. Even when i give the correct username and password I also tried this def clean_username(self): return self.cleaned_data.get('username') views.py def login(request): if request.method == 'POST': form = LoginUser(request=request.POST, data=request.POST) if form.is_valid(): print(True) print(form.cleaned_data['username']) print(form.cleaned_data['password']) print(form.is_valid()) else: form = LoginUser() context ={ 'form': form, } return render(request, 'login.html', context) forms.py class LoginUser(AuthenticationForm): username = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'class': form_class, 'placeholder': 'username', })) password = forms.CharField(min_length=8, required=True, widget=forms.PasswordInput(attrs={'class': form_class, 'placeholder': 'password', })) def clean_username(self): return "valid_username" I think I need to change the is_valid method -
How to use django_autocomplete_light in django admin page?
I have a 2 model in django models class Country(models.Model): country_name = models.CharField(max_length=30, null=False) country_phone_code = models.CharField(max_length=50, primary_key=True, null=False) country_image = models.CharField(max_length=255, blank=True) is_shipping_available = models.BooleanField(null=False) class State(models.Model): id = models.AutoField(primary_key=True) state_name = models.CharField(max_length=30, null=False) country = models.ForeignKey( Country, on_delete=models.CASCADE, related_name="states" ) is_shipping_available = models.BooleanField(null=False) what i was trying to do register the states model in Modeladmin and have an auto field to select from country model since it is related using the foreign key relation ship and i found out that i can do it using the django_autocomplete_light ? help -
Running Django and PHP on same Ubuntu server
I have a dedicated Ubuntu 22.0 server on which I am running PHP apps using Cyberpanel. I want to use Django on the same server. I have 2 sites inside cyberpanel using wordpress. I want my third site to point to the Django app, not the PHP. What should be the approach to configure it? -
DoesNotExist at /buy_now_payment_done/ Payment matching query does not exist
i have implemented an E-commerce website with razorpay payment integration and when i am got to checkout page with cart items, all logic work properly but when i am click on Buy Now button and then redirect it to "buynow_checkout.html" after that i am making a payment and payment is also successfull but after that i am getting an error : DoesNotExist at /buy_now_payment_done/ Payment matching query does not exist. how to resolve this? here is my code: Buy Now button <a href="{% url 'buy_now' %}?prod_id={{ product.id }}" id="" class="btn btn-danger shadow px-5 py-2 ms-4">Buy Now</a> urls.py path('buy_now/', login_required(views.BuyNow.as_view()), name='buy_now'), path("buy_now_payment_done/", views.buynow_payment_done, name='buynow_payment_done'), path('checkout/', login_required(views.checkout.as_view()), name='checkout'), path("payment_done/", views.payment_done, name='payment_done'), view.py import uuid from django.shortcuts import render,redirect,get_object_or_404 from django.views import View from django.contrib import messages from django.http import HttpResponseRedirect, JsonResponse, HttpResponse from django.conf import settings from django.core.mail import send_mail from django.contrib.auth import authenticate,login,logout from django.urls import reverse from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.db.models import Q from .forms import * from .models import * import razorpay class checkout(View): def get(self,request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity * p.product.discounted_price famount = famount+value totalamount = famount + … -
How to stop my footer design to effect the whole page?
I made this footer but when I include it in my base.html it changes the styling of the other parts I think due to its CSS and it makes some icons look strange what should I do?? if I need to post another part of code please let me know Thanks in advance my index.html (footer) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="vieport" content="width=device-width,initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <title>Document</title> </head> <body> <footer> <div class="footerContainer" > <div class="socialIcons"> <a href=""><i class="fa-brands fa-facebook"></i></a> <a href=""><i class="fa-brands fa-instagram"></i></a> <a href=""><i class="fa-brands fa-telegram"></i></a> <a href="https://github.com/Jasmine-dy"><i class="fa-brands fa-github"></i></a> <a href=""><i class="fa-brands fa-youtube"></i></a> </div> <div class="footerNav"> <ul> <li><a href="">Home</a></li> <li><a href="">Genres</a></li> <li><a href="">Contact Me</a></li> <li><a href="">Your Account</a></li> </ul> </div> </div> <div class="footerBottom"> <p style="margin-top: 10px" >Copyright &copy;2023; Designed by <span class="designer">Jasmine</span> </p> <a href="https://www.freepik.com/free-vector/abstract-background-with-rainbow-coloured-hologram-background_19613969.htm#query=pastel%20holographic%20background&position=2&from_view=keyword&track=ais&uuid=eccfffcb-4044-4b17-8749-40b272baa47e">Image by kjpargeter</a> on <span class="designer"> Freepik</span> <h2></h2> <a target="_blank" href="https://icons8.com/icon/79363/reading-unicorn">Reading Unicorn</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a> </div> </footer> </body> <style> footer{ padding: 0; margin: 0; box-sizing: border-box; } footer{ background-color: transparent; } .footerContainer{ width: 100%; padding: 70px 30px 20px; } .socialIcons{ display: flex; justify-content: center; } .socialIcons a{ text-decoration: none; padding: 10px; background-color: white; margin: 10px; border-radius: 50%; display: flex; } .socialIcons a i{ … -
Cross-domain issues between Vue and Django
I encountered a problem when using CROS to solve cross-domain issues between Vue and Django. In the Django part, I have completed the corresponding settings and can already request Django from the Vue interface at http://localhost:5173. But when I use http://127.0.0.1:5173 to access Vue, a CORS error occurs when requesting Django.As follows: The localhost domain name can be cross-domain normally A cross-domain error occurred in the 127.0.0.1 domain name My Django side has been configured with corsheaders and CORS_ORIGIN_WHITELIST Django settings -
Django: messages.error doesn't work with redirect('/')
I'm so confused in templates main page I have: {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <div class="alert alert-danger" role="alert">{{ message }}</div> {% endif %} {% endfor %} but the message is not printed. in views.py I have def my_form(request): if not str(request.POST['name']): messages.error(request,'error message.') return redirect('/') and in myapp urls.py path('', views.index, name='index'), re_path(r'^MyForm/$', views.my_form, name='my_form') and in the general urls.py re_path(r'^', include('myapp.urls'), name='home') what could be the issue, the log file shows nothing -
Hello, how do I correct this django error because I've already done everything?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/concesionario/lista_vehiculos/ Using the URLconf defined in concesionario_proyecto.urls, Django tried these URL patterns, in this order: Lista_vehiculos.html The current path, concesionario/lista_vehiculos/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This error is from Django I tried all the methods and it doesn't work and I hope to create a project using the Django Framework, of an application for a dealer of new vehicles, the project must contain a use and/or configuration of: Django installation. Creation of the Django project. Creation of the application for the dealership. Creation of the required data models Create the required views. Create the base template to apply to two dependent HTML documents. Execution and correct functional demonstration of the created system -
Django usercreation form not creating user after authentication
I am currently learning Django and working on a project to help me learn, I created my custom usercreation form and everything seems to work except when i fill in the form it does not create a new user, when i open the sign up page it seems to see it as a request to create a new user and doesnt create one since the form hast been filled and it isnt valid and even when i do fill it still doesnt seem to think its valid and renders the sign up form again. i put two print statements in the sign up function in views.py one in the if statement and one outside just to know if a user was actually created from the console and every single time it says user not created meaning the form is never valid views.py: def signup(request): form = RegisterForm(request.POST) if request.method == 'POST': if form.is_valid(): print("User is valid") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') form.save() new_user = authenticate(username=username, password=password) if new_user is not None: authlogin(request, new_user) redirect('home/') print("User created") form = RegisterForm() print("User not created") return render(request, 'registration/signup.html', {'form': form}) forms.py: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'id':'RegisterUsername', 'type':"text", … -
Django and Polars strange slow response behavior
I am using Django rest framework with polars for creating reports. When having big response data, about 3,500 records, a response takes about a minute. At first, I thought the polar process was slow, but then I timestamped the beginning and end, and found out the whole process is about 1 sec. class TaskViewSet(SearchViewSet): """Task view set""" queryset = Task.objects.all() serializer_class = TaskSerializer search_vector = SearchVector("id", "name") permission_classes = [D7896DjangoModelPermissions] filter_backends = [ filters.DjangoFilterBackend, ] filter_class = TaskFilter pagination_class = None def list(self, request, *args, **kwargs): start_time = datetime.now() branch = request.GET.get("branch", None) orders = request.query_params.getlist("order", []) events = request.query_params.getlist("event", []) production_orders = request.query_params.getlist("production_order", []) start_date = request.GET.get("date__gte", None) start_date = ( datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else start_date ) end_date = request.GET.get("date__lte", None) end_date = ( datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else end_date ) # Validate branch is present if not branch: raise ValidationError("The 'branch' field is missing.") _, tasks = WorkOrderManager.get_work_orders( branch, start_date, end_date, orders, events, production_orders ) if not tasks.is_empty(): tasks = tasks.filter(pl.col("unused_components_task") == False).drop( ["unused_components_task"] ) tasks = tasks.with_columns( tasks['date'].dt.strftime('%Y-%m-%d'), tasks['supply_date'].dt.strftime('%Y-%m-%d') ) data = tasks.to_dicts() json_data = json.dumps(data) end_time = datetime.now() total_time = end_time - start_time print(total_time) return Response(json_data, content_type='application/json') Total Time printing in the terminal: printing in … -
How can I process Image in Django
In my Django Application, I am using imagekit to process images in my model but any time I try uploading image error says: module 'PIL.Image' has no attribute 'ANTIALIAS'. Initially, I never had issues with it but recently any time I try to save my form, I get that error. I have upgraded Pillow and used ImageFilter.MedianFilter() instead of ANTIALIAS but error persist. Someone should help with the best way of doing this. I am using Django Django==4.0. See my Model code: from django.db import models from PIL import Image from phonenumber_field.modelfields import PhoneNumberField from imagekit.processors import ResizeToFill, Transpose from imagekit.models import ProcessedImageField from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible @deconstructible class FileExtensionValidator: def __init__(self, extensions): self.extensions = extensions def __call__(self, value): extension = value.name.split('.')[-1].lower() if extension not in self.extensions: valid_extensions = ', '.join(self.extensions) raise ValidationError(f"Invalid file extension. Only {valid_extensions} files are allowed.") Allowed Image extensions image_extensions = ['jpeg', 'jpg', 'gif', 'png'] class ResizeToFillWithoutAntialias(ResizeToFill): def process(self, img): img = super().process(img) return img.resize(self.size, Image.LANCZOS) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=True, null=True) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) date_birth = models.DateField(blank=False, null=True) phone_number = models.CharField(max_length=11, blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) marital_status = …