Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'HitCountDetailView' object has no attribute 'category'
I am trying to add extra context which does filtering to my DetailView. It throws the error that the view object has no attribute category model class Post(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, blank=True) slug = models.SlugField(max_length=100, unique=True, editable=True) view.py class HitCountDetailView(HitCountDetailView): model = Post template_name = 'detail.html' context_object_name = 'post' slug_field = 'slug' count_hit = True def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['similar_posts'] = Post.objects.filter(category=self.category).exclude(slug=self.slug) return context **urls.py** ```python path('detail/<slug>/', HitCountDetailView.as_view(), name='post-detail') -
Django Tutorial Page Not Found
I have been following along with the Django tutorial for the poll app. I keep getting a 404 error when heading to the site. I have checked quite a few questions for this problem but I wasn't able to find a solution ''' Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^admin/ The empty path didn’t match any of these. ''' my code is as follows mysite\urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] polls\urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ] views: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") -
Django: How to control permissions based on a complex query
I am creating an application using the django rest_framework. I have the following models: Employee (Many to one relationship to Project) Project (Many to one relationship to Manager) Manager The Manager should be able to see all Employees that are not currently assigned to a project, or that are assigned to a project that the Manager is managing. (There can be other managers that assign an employee to their own project, and then other managers can't see them). These are the libraries that I am using: asgiref==3.4.1 Django==3.2.6 django-filter==2.4.0 django-rest-framework==0.1.0 djangorestframework==3.12.4 pytz==2021.1 sqlparse==0.4.1 I'm imagining something like this: class Employee(models.Model): name = models.CharField() assignment = models.ForeignKey('Project', on_delete=models.SET_NULL, null=True, blank=True, related_name='assigned_to_project') class Project(models.Model): name = models.CharField() owner = models.ForeignKey('Manager', on_delete=models.SET_NULL, null=True, blank=True, related_name='managed_by') class Manager(models.Model): name = models.CharField() As far as permissions, I imagine a custom permission on the employee which is something like: def has_permission(self, request, obj=None): if obj: if obj.assignment is not None: """ Start sudo-code - Use the value saved in obj.assignment (for example the PrimaryKey of the project it is assigned to) - Follow that PK to the project table, and look to see if obj.owner is not None. - If it isn't None, take the PK … -
The difference between <str:slug> and <slug:slug> in urls.py of Django application
Why in some cases in urls.py is used str:slug, and in other cases slug:slug? What is the difference? And which option is better to use? And can I use a category slug and then an article slug in one route? -
How to handle form with multiple checkboxes with different values, the same names in django?
I have a problem with handling a form with multiple checkboxes with different values, but the same names using django. HTML: <form name="form1" method="post" id="formToCheck"> {% csrf_token %} <div class="row form-group"> {% for icon in icons_to_show %} <div class="col-md-{{ number }}"> <div class="center"> <i class="large material-icons" style="color: darkslategray">{{ icon }}</i> <p>{{ icon }}</p> <label for={{ icon }}> <input type="checkbox" name="display_type" value="{{ icon }}" id={{ icon }}/> <span>Choose</span> </label> </div> </div> {% endfor %} <button type="submit" class="btn btn-primary blue" style="text-align: center; align-items: center">Submit </button> </div> </form> models.py class MemoryResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now=True, null=True) picked_imges_names = models.CharField(max_length=255, null=True) results = models.FloatField(null=True) status = models.CharField(max_length=255, null=True) def __str__(self): return '{}'.format(self.images_names) @receiver(post_save, sender=User) def create_memory_results(sender, instance, created, **kwargs): if created: MemoryResult.objects.create(user=instance) views.py class MemoryImagesView(TemplateView): template_name = 'accounts/memory.html' icon_to_show = [] def dispatch(self, request, *args, **kwargs): previous_images = self.request.user.memoryimage_set.all().last().images_names.strip("[]'").replace("'", "").replace( " ", "").split(",") how_many = 9 - len(previous_images) self.icon_to_show = render_icons(how_many) + previous_images response = super(MemoryImagesView, self).dispatch(request, *args, **kwargs) return response def get_context_data(self, **kwargs): context = super(MemoryImagesView, self).get_context_data(**kwargs) return context def get(self, request): memory = MemoryResult.objects.filter(user=request.user) frontend = { 'title': 'Memory Results', 'number_mem': 'abcdefghi', 'icons_to_show': self.icon_to_show, 'number': 4, 'memory': memory } return render(request, 'accounts/memory.html', frontend) def post(self, request): picked_icons = … -
how to do sorting of item after completing the search
i have search field i want to give user sorting option so user can do sorting luke price low to high to low in the search result but unable to achieve that my view class search_item(View): def get(self, request): search_item = request.GET.get('search') if search_item: items = Item.objects.filter(Q(name__icontains=search_item)|Q(color__icontains=search_item)) sort_by = request.GET.get("sort", "l2h") if sort_by == "l2h": item = items.order_by("price") elif sort_by == "h2l": item = items.order_by("-price") return render(request, 'search_result.html', {'items':item}) it does the search but unable to do sorting what wrong in my code -
Extra context is no passed to /accounts/login in django 3
I want to pass some configurable data to the login template and all other account template. Currently, I am trying it like this: # urls.py path('accounts/', include('django.contrib.auth.urls'), {'extra_context': {'home_title': settings.HOME_TITLE, 'domain': settings.HOSTNAME}}), However, the data is not picked up by the template. And those variable remain empty strings. Is there a better way to do this? For other pages I am passing the data in the views like this: #views.py def home(request): context = {'home_title': conf_settings.HOME_TITLE} return render(request, 'home.html', context) -
404 Not Found, Nginx config
I just started using Django and I try to deploy my project on the digital ocean server using Nginx. I am trying to set up SSL and domain (and they look good through the SSL checker and Google Dig DNS), however I get the 404 error in the browser once I try to access the webpage: 404 Not Found nginx/1.14.0 (Ubuntu) I have been trying different things with Nginx config but it does not seem to help, here is what I have now: http { ... server { listen 443; ssl on; ssl_certificate /etc/ssl/server_merged_key.crt; ssl_certificate_key /etc/ssl/other_key.key; root /home/mysite1/mysite; server_name domain.net www.domain.net ; location / { root /home/mysite1/mysite/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; } ... } The Django project is located on the home of the server with no directory (just two folders /mysite1/mysite/). The server starts fine. I do not see any GET request on the server side once I see the 404 error on the page. I do see the 400 error You're accessing the development server over HTTPS, but it only supports HTTP., if I try to access through http://IP-IN-NUMBER:8000. Also, the settings.py looks like this, if this relevant to the issue: … -
capture variables with js without saving it in the database
hello I hope you can help me I try to have the size and color variables with the js without going through the database as I did with the price here is the code snippet that I think is necessary html <table class="table table-bordered"> <tr> <th>Colors</th> <td> {% for color in colors %} <button class="btn btn-lg choose-color" data-color="{{color.color__id}}" style="background-color: {{color.color__color_code}}"></button> {% endfor %} </td> </tr> <tr> <th>Sizes</th> <td> {% for size in sizes %} <button data-price="{{size.price}}" class="btn btn-outline-secondary btn-sm choose-size color{{size.color__id}}">{{size.size__title}}</button> {% endfor %} </td> </tr> <tr> <th>Price</th> <th> <span class="product-price">{{data.productattribute_set.first.price}}</span></th> </tr> </table> <hr/> <div class="input-group my-3" style="width:30%;"> <input type="number" value="1" class="form-control" id="productQty" /> <div class="input-group-append"> <input type="hidden" class="product-id" value="{{data.id}}" /> <button> Add to Cart</button> js $(document).on('click',"#addToCartBtn",function(){ var _vm=$(this); var _qty=$("#productQty").val(); var _productPrice=$(".product-price").text(); // Ajax $.ajax({ url:'/add-to-cart', data:{ 'qty':_qty, 'price':_productPrice, }, -
Change the edit url, dynamically using the Datatable Editor
I'm looking on how to update the ajax configuration dynamically using data from a resource when updating a record. Django REST expects the id at the end of the url and the request method must be type PUT -
django database performane separate tables vs GenericRelation
hello i hope you doing well let us say i have 2 models, say A and B and the third is named order .On side of database performance Which way is better?(when the fileds of order is common) one or two . In other words, what are the advantages and disadvantages of each? implementation one: class A(models.Model): order=GenericRelation('Order') fields class B(models.Model): order=GenericRelation('Order') fields class Order(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') vs----- implementation two: class A(models.Model): fields class B(models.Model): fields class OrderA(models.Model): fields class OrderB(models.Model): same fields of orderA -
Django how can i add multiple databases connection dynamically?
I can add to multiple databases on Django but I want to add with a loop or add a new element to the DATABASES object. How can I add to this object list dynamically ?. Can I read from the txt file or models? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'deneme1', 'USER': 'mamp', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8889', 'OPTIONS': { 'autocommit':True, } }, 'database2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'deneme2', 'USER': 'mamp', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8889', 'OPTIONS': { 'autocommit':True, } } -
django migrations making no changes to my admin site after altering my model.py
from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default='awesome') author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) -
Go to the appropriate tab when JavaScript True False
I would like to write JavaScript as follows and move it to Tab4 when it is true, and to display the modal when it is false. Even if it's not modal, it's good to just move to Tab4 when True. How can I solve this problem? If you help me, I'll adopt it right away. javascript // run the webcam image through the image model async function predict() { // predict can take in an image, video or canvas html element var image = document.getElementById("face-image") const prediction = await model.predict(image, false); prediction.sort((a,b) => parseFloat(b.probability) - parseFloat(a.probability)); switch (prediction[0].className){ case "True": resultMessege = "success." break; case "False": resultMessege = "fail" break; default: resultMessege = "error" } $('.result-message').html(resultMessege); for (let i = 0; i < maxPredictions; i++) { const classPrediction = prediction[i].className + ": " + prediction[i].probability.toFixed(2); labelContainer.childNodes[i].innerHTML = classPrediction; } } I want to move tab <input id="tab1" type="radio" name="tabs" checked> <label for="tab1"><img src="https://image.flaticon.com/icons/svg/126/126486.svg"><br>STEP 1<br>1</label> <input id="tab3" type="radio" name="tabs"> <label for="tab3"><img src="https://image.flaticon.com/icons/svg/839/839860.svg"><br>STEP 2<br>2</label> <input id="tab4" type="radio" name="tabs"> <label for="tab4"><img src="https://image.flaticon.com/icons/svg/3064/3064197.svg"><br>STEP 3<br>4</label> -
Could not load a database from C:\Users\Nenye\Documents\fleetmgt\fleetmgt\geoip
I'm working on a python/django web app that should fetch clients current location and calculate his distance after getting his destination from client's input. here's my code: my view: from django.shortcuts import render from geopy.geocoders import Nominatim from .models import Ride from .forms import BookRideForm from .utils import get_geo def book_a_ride_view(request): form = BookRideForm(request.POST or None) geolocator = Nominatim(user_agent="riders") ip = '72.14.207.99' country, city, lat, lon = get_geo(ip) print('country:', country) print('city:', city) print('lat:', lat) print('lon:', lon) msg = "" if form.is_valid(): new_form = form.save(commit=False) destination_ = form.cleaned_data.get('destination') destination = geolocator.geocode(destination_) print(destination) d_lat = destination.latitude d_lon = destination.longitude new_form.rider_id = request.user.id # new_form.save() form = BookRideForm() msg = 'Your booking is Successful' template = 'riders/book_ride.html' context = {"form":form, "msg":msg} return render(request, template, context) Here's utils.py: from django.contrib.gis.geoip2 import GeoIP2 # HELPER FUNCTIONS def get_geo(ip): g = GeoIP2() country = g.country(ip) city = g.city(ip) lat, lon = g.lat_lon(ip) return country, city, lat, lon i get this error: System check identified no issues (0 silenced). August 26, 2021 - 18:56:09 Django version 3.2.6, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /ridersbook_a_ride Traceback (most recent call last): File "C:\Users\Nenye\Documents\fleetmgt\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = … -
Serving Static Images in AWS - Django - Python
I have all of my static images served locally on my Django website project. I need them to be hosted on AWS for my DEBUG = False to work. I have followed many tutorials on how to do this and have had no luck. I have posted my code below for a last-ditch effort hoping that it is just something I have missed. I have my AWS bucket currently as public because that's what I have seen others doing. Any help is greatly appreciated. Thanks! setings.py AWS_ACCESS_KEY_ID = 'AKIAVADFUL4TVW3IKZLA' AWS_SECRET_ACCESS_KEY = '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' AWS_STORAGE_BUCKET_NAME = 'hidden for privacy' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Caracas' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) #STATIC_ROOT = os.path.join(BASE_DIR, 'static') #MEDIA_URL = '/images/' #MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '..','www','media') HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="shortcut icon" type="image/x-icon" href="{% static 'tab_icon.ico' %}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static "css/side.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="stylesheet" href="{% … -
Pass user to model manager
I have a custom model manager: class DBSearch(models.Manager): def search(self, query, user): qs = self.get_queryset() qs = db_search(qs, query) return qs My custom user object has a sting property db_name which I want to pass to using argument of db_manager or to self._db. What is the right way to do that? -
How to make seperate comment section for each item
I am making django app I have a problem I dont have idea how to make seperate comment section to each Item. I do not want to have same comments for every Item on a page. models.py class Comment(models.Model): comment_user = models.OneToOneField(User, on_delete=CASCADE) item = models.OneToOneField(Item, on_delete=CASCADE) content = models.TextField(default='') views.py class ShopDetailView(DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.all() return context -
"The file cannot be reopened." error from django-imagekit after moving a file
I'm using django-imagekit to generate a thumbnail on a Django model: class Book(models.Model): title = models.CharField(null=False, blank=False, max_length=255) thumbnail = models.ImageField( upload_to=upload_path, null=False, blank=True, default="" ) list_thumbnail = ImageSpecField(processors=[ResizeToFit(80, 160)], source="thumbnail", format="JPEG") That works fine. However I'm trying to move the original thumbnail file after upload. Here's a simplified version of my save() method, that just moves the file into a "new" directory and re-saves the object (it's more complicated than that really): def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.thumbnail and "/new/" not in self.thumbnail.path: # Move the thumbnail to correct location. initial_name = self.thumbnail.name initial_path = self.thumbnail.path new_name = os.path.join(os.path.dirname(initial_name), "new", os.path.basename(initial_name)) new_path = os.path.join(settings.MEDIA_ROOT, new_name) if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) os.rename(initial_path, new_path) self.thumbnail.name = new_name kwargs["force_insert"] = False super().save(*args, **kwargs) This works fine by default. But if I have this in settings.py: IMAGEKIT_DEFAULT_CACHEFILE_STRATEGY = "imagekit.cachefiles.strategies.Optimistic" then I get errors resulting from imagekit signals, presumably confused that the file has moved while trying to generate the list_thumbnail. Here's some of the traceback: ... File "/venv-path/python3.8/site-packages/imagekit/specs/sourcegroups.py", line 33, in receiver fn(self, sender=sender, **kwargs) File "/venv-path/python3.8/site-packages/imagekit/specs/sourcegroups.py", line 101, in post_save_receiver self.dispatch_signal(source_saved, file, sender, instance, File "/venv-path/python3.8/site-packages/imagekit/specs/sourcegroups.py", line 124, in dispatch_signal signal.send(sender=source_group, source=file) File "/venv-path/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File … -
Django drf-spectacular - Can you exclude specific paths?
We have a bunch of api's with different versions in urls.py, eg api/v1 api/v2 api/v3 . We want to implement swagger with drf-spectacular, but we only want to expose api/v3 endpoints. Is there a way to do this? I cannot make sense of the documentation. Thanks -
FOREIGN KEY constraint failed. Django allauth error in EmailAddress
I use allauth in my Django app. I have custom User Model and custom Signup Form. At first, Model and Form were in the app called "main", then I created a new app called "user" and moved them to new app. And now I get FOREIGN KEY constraint failed error when I signup new user. I have this in my settings.py: AUTH_USER_MODEL = "user.Account" ACCOUNT_FORMS = { "signup": "user.forms.CustomSignUpForm", } My custom SignUp Form: class CustomSignUpForm(SignupForm): full_name = forms.CharField(max_length=350, label="Full Name", required=True) def save(self, request): user = super(CustomSignUpForm, self).save(request) user.full_name = self.cleaned_data['full_name'] user.save() return user My models.py: class AccountManager(BaseUserManager): def create_user(self, email, full_name, password=None): if not email: raise ValueError("Users must have email address") if not full_name: raise ValueError("Users must have name") user = self.model( email=self.normalize_email(email), full_name=full_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, full_name, password): user = self.create_user( email=self.normalize_email(email), password=password, full_name=full_name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): GENDERS = ( ("M", "Male"), ("FM", "Female"), ("O", "Other") ) SPECIALIZATIONS = ( ("DV", "Developer"), ("DS", "Designer"), ) email = models.EmailField(verbose_name="email", max_length=60, unique=True) full_name = models.CharField(max_length=350) gender = models.CharField(max_length=50, choices=GENDERS) birth_date = models.DateField(null=True, blank=True) specialization = models.CharField(max_length=250, choices=SPECIALIZATIONS) extra_info = models.BooleanField(default=False) contacts = … -
Unable to make multiple requests in a row using the google drive API
I have a problem with my google drive API. I use this code to connect to my google account and get service : from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build def getService(): # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive'] """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'code_secret_client_632139208221-9tetq1fkkbud9ucmcq0bl3k4e3centem.apps.googleusercontent.com.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) service = build('drive', 'v3', credentials=creds) return service It works perfectly, but when I call 2 times for example : result1 = GoogleDrive.service.files().list( pageSize=1000, fields="nextPageToken, files(id, name)").execute() result2 = GoogleDrive.service.about().get( fields="storageQuota").execute() I have this error : ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong … -
how to revoke access token in django_simple_jwt?
I'm using simple JWT in Django and I blacklist the refresh token when user want to log out. but I don't know why access token is still working. how can I revoke it? thank u. -
Django Rest Framework - general approach on handling guest users
I'm trying to implement handling of guest (anonymous) users in my Django/React app using DRF, but I'm not sure exactly how to proceed. What I want eventually is, when a non-registered user comes to my homepage, he can perform limited CRUD operations eg. creating a maximum of 10 tasks, and when he chooses to register, these limitations are then lifted. A while ago, I did the same app but only with Django, and the way I had it set up, was when an anonymous user visited the page, a new user was created without a password. I was using this function to achieve this: def getUser(self): if not self.request.user.is_authenticated: ip = get_client_ip(self.request) if UserAccount.objects.filter(ip_address=ip).exists(): return UserAccount.objects.get(ip_address=ip) random_username = f"{randomString(10)}_guest" random_email = f"{randomString(5)}_guest@example.com" guest_user = UserAccount.objects.create( username=random_username, email=random_email, ip_address=ip, is_active=False, ) return guest_user else: return request.user And later, when this user submitted the registration form, I used the same function to retrieve this "guest" user and updated the rest of the model fields (email...) and set his password. Now, to return to the original question, how would I go about doing the same thing with the rest framework? I was also looking at the DRF documentation, and for authentication, you need … -
Как добавить форму в django, для добавления пользователем разного товара? [closed]
models - тут несколько моделей и хочу, чтобы пользователь смогу выбрать категорию товара и выложить на сайт товар class Product(models.Model): class Meta: abstract = True category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.CASCADE) title = models.CharField(max_length=255,verbose_name='Наименование') slug = models.SlugField(unique=True) image = models.ImageField(verbose_name='Изображение') description = models.TextField(verbose_name='Описание', null=True) price = models.DecimalField(max_digits = 9, decimal_places=2,verbose_name='Цена') class Notebook(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') Processor_freq = models.CharField(max_length=255, verbose_name='Частота ЦП') class SmartPhones(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') sd = models.BooleanField(default=True)