Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project is creating into C:\VTRoot\HarddiskVolume3 by default
I am putting "django-admin startproject mysite". Project is creating in the folder of C:\VTRoot\HarddiskVolume3 by default instate of desire folder. Please help me out. pip install django -
How to get red of 'Apps aren't loaded yet' in django whenever I run the code?
It is just a simple question but I posted full code. I am trying to make a search bar working in django. I wrote code which I am going to show you but whenever I run the code it gives me the following error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I really want to know how to solve this issue? I am posting this question twice okay due to posting issue. It is just a simple question but I posted full code. I am trying to make a search bar working in django. I wrote code which I am going to show you but whenever I run the code it gives me the following error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I really want to know how to solve this issue? I am posting this question twice okay due to posting issue. <body> <div class="container"> <h1>Search Students Information</h1> <form method="post" action="/search/"> {% csrf_token %} <div class="form-group"> <div class="col-lg-5"> <input type="text" name="srh" class="form-control" placeholder="Enter...."> </div> <label class="col-lg-2"> <button type="submit" class="btn btn-danger"> Search </button> </label> </div> </form> <div> search.html {% if messages %} <ul class="messages"> {% for k in messages %} <li style="color:red">{{k}}</li> {% endfor %} </ul> {% endif %} </div><br> <div style="color: blue"> … -
Function SIMILARITY does not exist. Module pg_trgm already exists... How can I clear this error?
After installing PostgreSQL I keep getting an error. "LINE 1: ...T COUNT() FROM (SELECT "blog_post"."id" AS Col1, SIMILARITY...*" HINT: No function matches the given name and argument types. You might need to add explicit type casts. sudo apt install postgresql-contrib psql# CREATE EXTENSION pg_trgm; sudo service postgresql restart (venv) dev-py@devpy-VirtualBox:~/Dev/mysite/mysite$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 12, 2019 - 20:31:19 Django version 2.2.3, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [12/Jul/2019 20:31:32] "GET /blog/search/ HTTP/1.1" 200 995 Internal Server Error: /blog/search/ Traceback (most recent call last): File "/home/dev-py/Dev/mysite/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function similarity(character varying, unknown) does not exist "LINE 1: ...T COUNT() FROM (SELECT "blog_post"."id" AS Col1, SIMILARITY...*" HINT: No function matches the given name and argument types. You might need to add explicit type casts. Any help would be appreciated. It took me 3 days of troubleshooting this before I asked for help but I am sure someone knows the answer and it's simple. If you need any more info please just lmk. -
How do I include a variable in static content in Django template?
I am running Django 2.2.2 attempting to load static conytent whose name is given by a template variable. For a fixed name I can successfully use (for example): however if I try replacing "AS" with the value of a variable, {{ card }}: when I look at the generated HTML the alt tag is expanded as expected but the src tag is URL-escaped: I have tried various placements of the quotes but either get a result like this or a template parsing error. The desired output is (assuming card = AH): -
Django: Paginating Postgres Search Results
I have this tool for searching friends but my pagination returns a bunch of random results. The first page is always relevant to the search terms, so I know it's the pagination that's the problem. What am I doing wrong here? When I paginate to page 2 via ?q=something&page=2 the results appear to be all random (unfiltered results). class PeopleSearchView(LoginRequiredMixin, generic.ListView): context_object_name = 'snapshots' redirect_field_name = "next" paginate_by = 15 def get(self, request, *args, **kwargs): if request.GET.get('q') == None: return HttpResponseRedirect(reverse('people:friends')) return super(FriendsSearchView, self).get(request,*args,**kwargs) def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['query_string'] = self.request.GET.get('q') return context def get_queryset(self): query_string = self.request.GET.get('q') vector = SearchVector('description', weight='A') + SearchVector('location', weight='A') + SearchVector('name', weight='B') query = SearchQuery(query_string) return PeopleSnapshot.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank') -
Modify and display context with output from a form
using a django form, im taking user input in the form of a url, and sending a request to that url. what i want to do is parse out the status code of the response, and add it to the context dictionary and display it in the template. i typically send a request and parse the response as follows: import requests url = input('what url?') response = requests.get(url) stat_code = str(response.status_code) print(stat_code) but since im trying to do this with django, this now involves form.py to take the url as user-input, as well as view.py logic and template.html to display it. project/app/forms.py class SearchForm(forms.Form): def send_request(self): response = api.execute('findCompletedItems', dct_request) stat_code = response.status_code return stat_code project/app/views.py class SearchView(FormView): template_name = 'search.html' form_class = SearchForm success_url = 'results' context_object_name = 'item' def form_valid(self, form): form.get_sales_history() return super().form_valid(form) def get_context_data(self): context = super(SearchView, self).get_context_data() context['stat_code'] = stat_code return context but there is no visible output. project/templates/results.html <h1>{{ item.stat_code }}</h1> ive been trying to figure this out literally all day long, and ive tried lots of different things. i got everything to work except for the actual displaying of the response data stat_code. i sincerely apologize if this is a jumbled mess, as … -
I'm new to Django framework and I'm having an error "ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package"
I'm creating an app directory for web scraping which is scrape inside my django_project. I'm having an an error in importing a class from my models.py module into my views.py module. Here's my code in models.py from django.db import models # Create your models here. # model -- headline (title, url, date) class Headline(models.Model): title = models.CharField(max_length=120) url = models.TextField() event_date = models.TextField() def __str__(self): return self.title and this code in views.py from django.shortcuts import render, redirect import requests requests.packages.urllib3.disable_warnings() from bs4 import BeautifulSoup from .models import Headline # Create your views here. def scrape(): # Use the session to get the URL session = requests.Session() url = 'https://allevents.in/malacca/all?ref=cityhome-popular' # Content is basically grabs all the HTML that comes from the session content = session.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") # Return a list #item = soup.find_all('div', class_="event-item") for item in soup.find_all('div', class_="event-item"): title = item.find("h3").text.strip() linkhref = item.find("h3").find("a").get('href') date_posted = item.find("div", {"class":"right"}) new_headline = Headline() new_headline.title = title new_headline.url = linkhref new_headline.event_date = date_posted new_headline.save() return redirect('/event/') after try run python views.py from cmd this error is appeared Traceback (most recent call last): File "views.py", line 5, in <module> from .models import Headline ModuleNotFoundError: No module named '__main__.models'; '__main__' … -
Is there a way to move to the bottom using jquery animate scroll?
Is there a way to move to the bottom using jquery animate scroll? ex $(".go_btn").click(function(){ const number = $(".go_input").val(); if(number == 1){ $('html, body').animate({ 'scrollTop' : $("#index_first").offset().bottom }); } $('html, body').animate({ 'scrollTop' : $("#index_"+number).offset().top }); }) and is this possible? 'scrollTop' : $("#index_first").offset().bottom + 10px up very thank you for let me know ~!~! -
Django , how to find the difference for two given tables SQLite DB
Given two entities of the same table and would like to find the difference between them in an effective way -
How to make custom UserCreationForm for admin page for custom user?
How to make custom UserCreativeForm for admin page? I tried this but it doesn't work. my models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True, blank=True, null=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField( _('staff status'), default=False, ) my forms.py: from django.contrib.auth import get_user_model User = get_user_model() class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') phone = forms.CharField(label="Phone number", required=False, max_length=15, help_text='Required. Inform a valid phone number.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'phone', 'password1', 'password2', ) admins.py: class CustomUserAdmin(UserAdmin): add_form = SignUpForm model = CustomUser list_display = ['email', 'username', 'phone', ] admin.site.register(CustomUser, CustomUserAdmin) How to make custom UserCreativeForm for admin page? I tried this but it doesn't work. -
Ngnix Not Serving Static Files In Production
I keep getting 404 Not Found Error when i try to load any static file from my project even after collecting staticfiles. I tried changing some of the configuration in settings.py and NGINIX config too, but nothing seems to be working NGINIX CONFIG server { listen 80; server_name 134.209.169.204; location = /favicon.ico {access_log off; log_not_found off;} location /static/ { root /home/lekan/181hub; } location /media/ { root /home/lekan/181hub; } location / { include proxy_params; proxy_pass http://unix:/home/lekan/181hub.sock; } } SETTINGS.PY STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I expect the static files to load without any problem, please let me know if there's a problem with my configuration -
Redirect to Google OAuth returns 404 within API test while working in the browser
I am trying to test my API before and after it redirects to Google OAuth but it strangely leads to 404 error. However, when I use the exact same URL in the browser (by copying and pasting), it magically works as usual. Using Django, apart from the tests, it also works fine. Essentially, I tried to use both direct and indirect URLs with varying query strings, yet all in vain. Below, you can find a simple way of replicating the problem. I am using social django and django rest framework. The url redirects to https://accounts.google.com/o/oauth2/auth with an additional query string. from rest_framework.test import APITestCase from rest_framework import status class ClientPath(APITestCase): def test_google(self): url = "/sociallogin/google-oauth2/" response = self.client.get(url, SERVER_NAME="127.0.0.1:8000", follow=True) self.assertEqual(response.status_code, status.HTTP_200_OK) The response says: '<h1>Not Found</h1><p>The requested resource was not found on this server.</p>', however when I try to open the URL including the query string, containing client_id, redirect_uri, response_type and scope (I am not posting it as it contains sensitive information) in the browser, it works. It shows me a typical "Sign in with Google" page. -
Input type Date not have value in page RTL and have value when page LTR
I have project using Django framework and i user i18n to support English and Arabic I have create form for add customers and i use the input type date to pick the date it works fine in LTR but when chane direction to RTL it lost the value when i submit the form the form model: enter code here class patienForm(forms.ModelForm): class Meta: model = patientModel fields=['Patient_Name_en', 'Email', 'Birth_Date'] widgets = { 'Patient_Name_en': forms.TextInput(attrs={'class': 'form-control'}), 'Email': forms.EmailInput(attrs={'class': 'form-control'}), 'Birth_Date':forms.DateInput(attrs={'class':'form-control','type':'date','max':dt}), } the view : class createPatientView(CreateView): model=patientModel template_name='reception/patientmodel_form.html' form_class=patienForm def form_invalid(self, form): print(form.instance.Birth_Date) print(form.instance.Email) print(form.instance.Patient_Name_en) return HttpResponse(form) def form_valid(self, form): print(form.instance.Birth_Date) print(form.instance.Email) print(form.instance.Patient_Name_en) return HttpResponse(form) the result of the above code : when page is RTL it call form_invalid and print: None alfaifi@fds.com.sa Abdullah Alfaifi when the same page but LRT it call form_valid and print : 2014-07-12 alfaifi@fds.com.sa Abdullah Alfaifi What will be the issue -
How to fix: CORB block for google chrome (Axios request)
I'm using Django with Rest framework and React to make a call to this API url. I already enabled CORS, however, the axios request is still blocked by CORB. Also tried to temporarily disabling it, by starting Chrome with the following command line flag: --disable features=CrossSiteDocumentBlockingAlways,CrossSiteDocumentBlockingIfIsolating componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff' } }).then(res => { this.setState({ article: res.data }); console.log(`http://127.0.0.1:8000/api/${articleID}`); //console.log(res.data); }); } WARNING: Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/api/1 with MIME type application/json. -
Django modelform field: when only one option exists, set that option as the default in dropdown
I have a Prescription modelform that lets users (employees at a medical office) create prescriptions. Users must select a "prescriber" for each prescription. "Prescriber" is filtered in views.py to show only prescribers that practice in the user's office. I'm trying to work an if / else statement into the modelform view: if my queryset filter options = only one option, make that the default in the form (appearing as if it has already been chosen in the dropdown, instead of the blank option that appears) I've been going down rabbit holes on SO all afternoon. Please help! Views.py @login_required(login_url="/login") def new_rx(request): if request.method == "POST": form = PrescriptionForm(request.POST) if form.is_valid(): prescription = form.save(commit=False) prescription.status = Prescription_status.objects.get(pk=1) # draft status prescription.medical_office = request.user.medical_office # medical office prescription.save() return redirect('vhome') else: form = PrescriptionForm() form.fields["prescriber"].queryset = CustomUser.objects.filter(medical_office=request.user.medical_office, prescriber=True) return render(request, 'app/new_rx.html', {'form': form}) forms.py class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription fields = ('prescriber', 'medication', 'quantity', 'directions', 'refills', 'earliest_permitted_fill_date', 'daw',) widgets = { 'earliest_permitted_fill_date': DatePickerInput(), # default date-format %m/%d/%Y will be used } -
Getting None values for POST request (via the Axios library) sent to Python/Django
I am building a web app with Django/Python and trying to send data to a controller via a POST request using the Axios library (within Vue.js code). The POST QueryDict seems to be empty and I can't see why that is happening: changeCountry: function(e, id){ console.log("Let's change the country") console.log(e.target.value) // is printing correctly console.log(id) // also printing correctly axios({ method: 'post', url: '/template/country', data: { id: id, country: e.target.value }, headers: { 'X-CSRFToken': "{{csrf_token}}" } }) .then(function (response) { alert(response.data); // this is returning what I expect }) .catch(function (error) { console.log(error); }) }, The Python method looks like this: def update_template_country(request): pprint(request.POST) # prints an empty QueryDict id = request.POST.get('id') country = request.POST.get('country') print(id, country) #prints None None return HttpResponse("The country is changed") # this is being returned back to the client The console.log messages at the top print what I expect and since there is no error I am assuming the CSRF header token is fine. Have I missed something obvious or misunderstood how this is working? -
How to override change model object form?
I am trying to override change model form for adming page but don't know why it doesn't work. Can smb help me please? My forms.py: from django import forms from django.contrib.auth.forms import UserChangeForm from django.contrib.auth.models import User class CustomUserChangeForm(UserChangeForm): email = forms.EmailField(required=True, label="Email") phone = forms.CharField(label="Phone number") class Meta: model = User fields = ("username", "email", "phone", ) My admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'phone', ] admin.site.register(CustomUser, CustomUserAdmin) My models.py class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True, blank=True, null=True) I am trying to override change model form but don't know why it doesn't work. Can smb help me please? -
Django admin template override does not work on Heroku
I'm try to override the actions.html file found in django/contrib/admin/templates/admin. This is the file I am overriding with. {% extends "admin/actions.html" %} {% block actions-counter %} {% if actions_selection_counter %} <span class="action-counter" data-actions-icnt="{{ cl.result_list|length }}">{{ selection_note }}</span> {% endif %} {% endblock %} I am only trying to override it for a specific model. This change works fine when I run Django on my local development server using the runserver command, but when the project is deployed to Heroku, the changes are not seen and the default template is still displayed. My project hierarchy looks like this project | | __templates | | __admin | | __my_app | | __model | | __actions.html I've also tried arranging it like project | | __my_app | | __templates | | __admin | | __my_app | | __model | | __actions.html Both ways work locally, but not on Heroku. -
how to display several bootstrap cards on the same row
i am trying to display retrieved data from database in cards using bootstrap 4 the data is retrieved correctly but the problem is in the displaying of these cards because it just been displayed on a vertical way each card on a row. what i need is to display let say 3 or 4 cards on the same row. code: {% for obj in object_list %} <div class="container"> <div class="row"> <div class="col-md-4"> <div class="card"> <!--Card image--> <img class="img-fluid" src="https://mdbootstrap.com/img/Photos/Others/images/43.jpg" alt="Card image cap"> <!--Card content--> <div class="card-body"> <!--Title--> <h4 class="card-title">name:{{ obj.name}}</h4> <!--Text--> <p class="card-text">{{obj.content}}</p> <a href="#" class="btn btn-primary">Button</a> </div> </div> </div> </div> </div> {% endfor %} -
Is necessary to learn SQLAlchemy when using Django?
I'm a intermidiate Django Developer. All the Database and Tables creations are done with Django Models. I was wondering when should a programmer used SQLAlchemy, which scenarios are the best to use this instead of the regular Django Models? -
My Delete modalForm always delete the first object in the dataModel?(Django)
I made a modal using bootstrap to delete user entries in a list view so i had to iterate with a for loop in the template so it always deletes the first object, also it never closes. How I can make the button of each entry unique that it deletes this object only. here's the modal : {% for obj in patients %} <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete" aria-hidden="true"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete patient!</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Are you sure you want to delete this patient?</p> </div> <div class="modal-footer"> <form method="POST" action="{% url 'patients:patient_delete' obj.pk %}"> {% csrf_token %} <input class="btn btn-danger" value="Yes" type="submit" > <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </form> </div> </div> </div> </div> {% endfor %} and here's my triggering button : <button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Delete</button> -
Create a Bootstrap accordian for items in a python for loop
I am trying to create a Bootstrap accordian for a list of items in a Django database. When rendered, currently my code will only collapse and expand on the first item in the for loop. For other items, when I click on these the first item expands/collapses, not the item being clicked on. Looking for a solution please. <div class="panel-group"> <div class="panel panel-default"> {% for issue in issues %} <div class="panel-heading"> <div class="panel-title"> <a data-toggle="collapse" data-target="#collapse1"><h3><i class="fas fa-chevron-down"></i> {{ issue.title }}</h3></a> </div> </div> <div id="collapse1" class="panel-collapse collapse"> <p><strong>Type: </strong>{{ issue.type }}</p> <p class="issue-description"><strong>Description: </strong>{{ issue.description }}</p> <p><strong>Requested By: </strong>{{ issue.requested_by }}</p> <p><strong>Date Created: </strong>{{ issue.date_created }}</p> <p><strong>Status: </strong>{{ issue.status }}</p> <p><strong>Date Completed: </strong>{{ issue.completed_date }}</p> <p><strong>Upvotes: </strong>{{ issue.upvotes }}</p> </div> {% endfor %} </div> </div> -
How do i filter a foreign key to get only specefic values in Django?
I have a model where I am creating a company. The model takes the name of a company, if the company has any parents ie: Quicktrip # 1345 parent company is Quicktrip Corp. How the parent is being made is that any company being created has the potential to be a parent. How do i filter through the list of companies so only certian ones are set as parent? I tried to check if the company has more than one location then its a parent but that did not work. parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) With the current code it sets all my companys i created to be a parent. -
How to pass user object into forms field
I am trying to pass a user object from my views.py into my forms.py to the user field and save a new object. The user field is a foreign key in the model. I can do a select dropdown widget like with the jobSite field but im trying to automatically pass the user object on submit instead of the current user having to select another user from the drop down. I've tried passing the user through as an initial key value from the views.py like so form = entryTime(request.POST, initial={'user': user}) I've tried a few different variations of that but so far haven't been able to successfully get the user object to save to the user field. forms.py class entryTime(ModelForm): class Meta: model = Entry fields = [ 'user', 'start_time', 'end_time', 'jobSite', ] widgets = { 'start_time': DateTimePicker( options={'useCurrent': True, 'collapse': False}, attrs={'append': 'fa fa-calendar', 'icon_toggle': True} ), 'end_time': DateTimePicker( options={'useCurrent': True, 'collapse': False}, attrs={'append': 'fa fa-calendar', 'icon_toggle': True} ), 'jobSite': Select() } def __init__(self, *args, **kwargs): super(entryTime, self).__init__(*args, **kwargs) self.fields['start_time'].widget.attrs['class'] = 'form-control' self.fields['end_time'].widget.attrs['class'] = 'form-control' self.fields['jobSite'].widget.attrs['class'] = 'form-control' views.py def addTimeEntry(request, userId): user = User.objects.get(pk=userId) form = entryTime() if request.POST: form = entryTime(request.POST) if form.is_valid(): print('form is valid') args={"form":form} … -
Annotate filtered queryset to another queryset
Okay, what I have. Tour — main model, TourTranslation — model for translated Tour information and TourArrival — tour arrivals (dates when each tour starts) In my view I get all TourTranslation's for current language. And then I need to annotate to each object in this queryset another filtered queryset like TourArrival.objects.filter(tour=<CURRENT_OBJECT_TOUR_FROM_TOURTRANSLATION>, date__gt=timezone.now) I know that I can just use setattr() method and iterate all over TourTranslation.objects.filter(language=<CURRENT_LANGUAGE>) and manually add all TourArrivals, but it does query each time, so summary it will be len(TourTranslation.objects.filter(language=<CURRENT_LANGUAGE>)) queries per user request and it is very much. How can I do it by doing one query? models.py (to undestand models' structure) class Tour(models.Model): class Meta: verbose_name = "тур" verbose_name_plural = "туры" REGION_CHOICE = ( ('e', 'Европа'), ('b', 'Беларусь') ) COLOR_CHOICE = ( ('y', 'Жёлтый'), ('g', 'Зелёный'), ('b', 'Голубой'), ('r', 'Красный') ) color = models.CharField(max_length=1, default='b', choices=COLOR_CHOICE, verbose_name="Цвет страницы") region = models.CharField(max_length=1, default='b', choices=REGION_CHOICE, verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Внутреннее название") image = models.ImageField(upload_to="tours/static/img/", verbose_name="Основное изображение") duration = models.PositiveIntegerField(verbose_name="Длительность (в днях)") seat = models.PositiveIntegerField(verbose_name="Количество мест") cost = models.PositiveIntegerField(verbose_name="Стоимость тура в BYN") images = models.ManyToManyField('TourImage', verbose_name="Фотографии с туров") def __str__(self): return self.name class TourArrival(models.Model): class Meta: verbose_name = "заезд" verbose_name_plural = "заезды" ordering = ['date'] tour = …