Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Direct Message with django
Please be generous in finding my rude expressions, if any . I don't mean such . It's simply because I'm poor at English . I want to make DM. It's like Twitter. It doesn't have to be rial time. but, I don't know how communicate only two people. Please tell me what I need, I want sample. -
How to update __str__ and slug everytime after Django's model update?
I have created this model in Django which also saves date and slug. But even if I am making these changes again the str and the slug still remains the same and not updating as per the new data. How to fix this ? class EntranceExamination(models.Model): course = models.CharField(max_length=100, blank=True, default='') year = models.PositiveIntegerField(choices=year_choices(),default=current_year(), validators=[MinValueValidator(1984), max_value_current_year]) month = models.PositiveIntegerField(choices=month_choices(),validators=[MinValueValidator(1), MaxValueValidator(12)]) day = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(31)]) start_time = models.TimeField(blank=True) end_time = models.TimeField(blank=True) slug = models.SlugField(editable=False,max_length=100) class Meta: ordering = ['month'] def __str__(self): return f"{self.course}'s exam on {self.slug}" def save(self): if not self.slug: self.slug = f'{self.day}-{self.month}-{self.year}' super(EntranceExamination, self).save() -
400 (Bad Request) when I try to upload images to AWS S3 from browser
I've been struggling with this for weeks now. I am trying to upload images to AWS S3 directly from the browser using boto3's generate_presigned_post(). The server side code seems to be working well, I do get a signed URL but when I try to upload using javascript I get a 400 bad request error. Server code: @csrf_protect def file_upload_view(request): if request.method == 'POST': file_names = request.POST.getlist('img_names') #extracts a list of all file names for files selected by the user. dataList = [] session = boto3.Session() #create an s3 object for uploads. s3 = session.client( 's3', region_name=settings.AWS_S3_REGION_NAME, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, config = Config(signature_version = 's3v4') ) print(settings.AWS_ACCESS_KEY_ID) S3BUCKET = settings.AWS_STORAGE_BUCKET_NAME for fileName in file_names: fname = randomString(30) fname = "media/Ad_images/{}.webp".format(fname) presigned_post = s3.generate_presigned_post( Bucket=S3BUCKET, Key= fileName, Fields={"acl": "public-read", "Content-Type": 'image/jpg'}, Conditions=[ {"acl": "public-read"}, {"Content-Type": 'image/jpg'}, ["content-length-range", 2, 5] ], ExpiresIn=3600 ) dataList.append( { 'original_fname': fileName, 'data': presigned_post, 'url': 'https://{}.s3.eu-west-2.amazonaws.com/{}'.format(settings.AWS_STORAGE_BUCKET_NAME, fname) } ) return JsonResponse(dataList, safe=False) Javascript code (Client-side): async function upload(input) { var form = document.querySelector("form#imgsForm"); var form_data = new FormData(form); var fdata = new FormData(); images = $("#adImgs")[0].files; emptyDisplayDivs = $('*[data-loaded="false"]'); if (images.length > 10 || images.length > emptyDisplayDivs.length) { alert( "Only 10 pictures are allowed. You have selected more than … -
why does JSON dump doesn't work in my code?
I'm trying to put python objects into a JSON file by getting the API from one of the sites but somehow when I run the code nothing has been put in the JSON file. API is working well, as well when I print out the code by json.load I get the output but I have no idea why does dump doesn't work. here is my code: from django.shortcuts import render import requests import json import datetime import re def index(request): now = datetime.datetime.now() format = "{}-{}-{}".format(now.year, now.month, now.day) source = [] author = [] title = [] date = [] url = "http://newsapi.org/v2/everything" params = { 'q': 'bitcoin', 'from': format, 'sortBy': 'publishedAt', 'apiKey': '1186d3b0ccf24e6a91ab9816de603b90' } response = requests.request("GET", url, params=params) for news in response.json()['articles']: matching = re.match("\d+-\d+-\d+", news['publishedAt']) if format == matching.group(): source.append(news['source']) author.append(news['author']) title.append(news['title']) date.append(news['publishedAt']) data = \ { 'source': source, 'author': author, 'title': title, 'date': date } with open('data.json', "a+") as fp: x = json.dump(data, fp, indent=4) return render(request, 'news/news.html', {'response': response}) -
How do I render a form multiple times and allow a single choice?
I have a quiz app and I have a choices model that contains a free text box that allows the user to type in their answer and an is_answer boolean. I want to be able to render a form that has N choices and to allow the user to specify which of the choices is the answer as a radio box. This is my choices form class ChoiceAddForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', "is_answer"] widgets = { 'choice_text': forms.TextInput(attrs={'class': 'form-control', }) } I am currently only able to display one instance of the form and am unsure how to allow multiple copies of the form as part of a radio button group. Any help/insight would be appreciated :) -
how to verify and send otp in single foem using django
class RegistrationForm(forms.Form): otp = forms.CharField(max_length=4,min_length=4,required=True,widget=forms.TextInput(attrs={'type':'number','class': 'form-control'}) ) about_company = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': "About Company"}, )) address = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': "Address"}, )) #industry = forms.ModelChoiceField(label="Industry",queryset=Industry.objects.filter(is_deleted=False, is_active=True, counter__gte=3),required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Select Industry"}))#neha gst gstin_no = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'True', 'placeholder': "Enter GST Number",'size': '10'}, )) company_type = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Company_type"}, )) contact_person_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Contact Person Name"}, )) company = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Company"}, )) email = forms.EmailField(required=True, widget=forms.EmailInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Email"}, )) designation = forms.CharField(max_length=255,widget=forms.TextInput(attrs={'class': 'form-control','placeholder': "Designation"}) ) industry = forms.ModelChoiceField(label="Select location", queryset=Industry.objects.filter(is_deleted=False, is_active=True, ).order_by("name"), required=True, widget=forms.Select(attrs={'class': 'form-control select2','placeholder': "Select Industry"},)) #location = forms.ChoiceField(required=True, choices=[('', 'Select City (First Select State)')], #widget=forms.Select(attrs={'class': 'form-control'})) #state = forms.ChoiceField(required=True, choices=[('', 'Select State')] + [(i.id, unicode(i.name)) for i in #State.objects.filter(is_active=True, #is_deleted=False)], #widget=forms.Select(attrs={'class': 'form-control'})) contact_number = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Mobile"}, )) password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Password"}, )) confirm_password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Confirm password"}, )) #registering_as = forms.ChoiceField(required=True, choices=corporate_choices, #widget=forms.Select(attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) #self.fields['location'].empty_label = "Select City" #self.fields['state'].empty_label = "Select State" def clean(self): try: del self._errors['location'] … -
Import "users" could not be resolved Pylance(reportMissingImports)
I wanted to import my views.py file from my app "users" ind the urls.py of the project. However, I'm getting an error that the "Import "users" could not be resolved". Picture of the problem The urls.py file: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from users import views as user_views # Why is there an error? urlpatterns = [ # Admin Page path('admin/', admin.site.urls), # Homepage path('', include('blog.urls')), path('register/', user_views.register, name = 'register'), path('profile/', user_views.profile, name = 'profile'), path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name = 'login'), path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name = 'logout'), ] The app is also in "INSTALLED_APPS" in the settings.py file: INSTALLED_APPS = [ 'crispy_forms', 'users.apps.UsersConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Folder structure This is probably an easy to solve problem, however I'm fairly new to Django and don't really understand why it says this is an error. In a similar project everything works fine. No error in a similar project, where I did everything the same way as far as I remember. -
DRF serialize through related models data
I've got a problem with DRF serialization. My main goal is to create an instance which has a related field but instead of providing the related models id i want to use it's other unique field. At the same time when I will serialize my model to present it (not create) i would like to get the default related fields value. Here's an example class Comment(models.Model): description = models.TextField() creator = models.ForeignKey(User, ...) x = Creator.objects.get(pk=1) print(x.unique_field) > 'some data' client.post('comment-detail', data={ 'description': 'some description', 'creator_unique_field': 'some data' }) # this should create a comment while using some unique creators field # which is not pk or id print(client.get('comment-detail', data={'pk':1})) { 'description' 'some description', 'creator': 1, } I don't know If i should change models Serializer of ViewSet's create() and retrieve(). Im starting with DRF and can't get my head around it -
ModuleNotFoundError: No module named 'django' in django project
i have anaconda python 3.7 installed on my system. i am creating a django project called learning log in a virtual environment(active at the time when problem appeared) in G drive on my computer. i have defined and migrated the entry model but when i try to register entry with the admin site through file admin.py in the project folder with following code ... from django.contrib import admin from models import Topic Register your models here admin.site.register(Topic) ... and try to run it in my spyder editor it shows -- enter code hereModuleNotFoundError: No module named 'django' -
django-background-tasks management command not running on AWS elasticbeanstalk
Greetings fellow programmers, I am currently using django-background-tasks(https://django-background-tasks.readthedocs.io/en/latest/) to run some background tasks on AWS elasticbeanstalk. I initially use this command in the main .config container commands but I get timeout error in deployment because this management command will never finish(it continues to run on). Now, I am trying using the approach suggested for running cron job on elasticbeanstalk(https://aws.amazon.com/premiumsupport/knowledge-center/cron-job-elastic-beanstalk/). Please take a look at my code, it is not running the command. what is wrong pls? I just need the command python manage.py process_tasks to keep running on. This is working properly on my local machine since i can easily open another terminal to fire up the python manage.py process_tasks command files: "/etc/cron.d/process_tasks_cron": mode: "000644" owner: root group: root content: | * * * * * root /usr/local/bin/99_process_tasks.sh "/usr/local/bin/99_process_tasks.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date # Your actual script content source /var/app/venv/*/bin/activate python manage.py process_tasks commands: remove_old_cron: command: "rm -f /etc/cron.d/*.bak" -
How do i deploy Django application on 3 tier server architecture ? UI , APP, DB server. already have 2tier app running
I have hosted Django application server 2 tier architecture APP & DB server. I need to deploy Django application on 3 tier architecture, UI-APP-DB server. Please help how to do it ? -
How can I stop post method to run by default in Django class based view
I've noticed that both the GET method and the POST method in running. I wanted to run only the GET method when I'm not performing any POST request to that URL. Class Profile(View): template_name = 'profile.html' def get(self, request): # some code... return render(request, self.template_name, context_dict) def post(self, request): # some code... return render(request, self.template_name, context_dict) I don't want to run the POST method if I'm not performing any POST request. I'm new to django. So sorry if it is a dumb question. -
How to set connection-timeout in django channel?
Django channels disconnect the client if it doesn't respond for few seconds. But I can't find where to set that time limit. i checked this issue. It says it will be configurable.But I can't find where to set that limit. thank you -
sending a safe html with django emailmessage
Good day, I'm trying to send a html in django email, pls what more can I added to the code. the email sending is functioning well but it still shows the html tags. from celery import task from django.template.loader import render_to_string, get_template from django.core.mail import EmailMessage from orders.models import Order @task def payment_completed(order_id): order = Order.objects.get(id=order_id) subject = f'Testing html sending' message = render_to_string('orders/order/pdf.html', {'order':order}) email = EmailMessage( subject, message, 'youremai@gmail.com', [order.email, 'youremai@gmail.com'] ) email.content_subtype = 'html' email.send() I've tried render_to_string and get_template same result -
How to increment a serial number in Django model with order by created_at
I'm developing a hospital project! People can apply online appointment for a specific doctor and the people will get a serial number once done the process of online appointment. Here is my model: class Appointment(models.Model): doctor = models.ForeignKey( DoctApp, on_delete=models.CASCADE, related_name="appointments") fee = models.IntegerField(default=1000, validators=[ MaxValueValidator(2000)]) name = models.CharField(max_length=220) phone = models.CharField(max_length=12, default="01700000000") age = models.IntegerField(validators=[MaxValueValidator(200)]) gender = models.CharField(max_length=10, choices=gen_choises) address = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) pat_pic_date = models.DateField() serial_number = models.IntegerField() def __str__(self) -> str: return f"""ID: {self.doctor.id} - {self.doctor.name} - Pat Name: {self.name}""" Can you consider to share the auto-increment fields system to get serial the number fields? -
foreign key serialization drf
i created a model named 'Post'. here is the code: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(default=datetime.now, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date'] i want to get all objects of Post model with users firstname and lastname. in views.py: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def allPost(request): allpost = Post.objects.all() serializer = PostSerializers(allpost, many=True) return Response(serializer.data) in serialisers.py: class UserSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class PostSerializers(serializers.ModelSerializer): user = serializers.RelatedField(many=True,source='user.username') class Meta: model = Post fields = ('body','date','user') -
django mongoDB insert dynamic keys
how to Insert Dynamic keys in django mongodb . settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'seartzDB' } } model.py class DynamicForm(models.Model): name = models.CharField(max_length=250) email = models.EmailField(max_length=250) ... view.py @api_view(['POST', ]) def create_form_view(request): DynamicForm(**request.data).save() return Response({'message': "Successfully Created"}, status=200) urls.py urlpatterns = [path('create/', create_form_view, name="create_form"),] I am using Donjo for mongodb. and Ihave create a model and want to insert multiple undefined fields in DB collection. right now i just use simply DynamicForm(**request.data).save() for insert query. but this query not able to insert undefined fields. -
Define filter parameters dynamically in django queryset
Suppose we have such a model: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Can we put x as a variable inside the filter so that we can have different querysets by giving different args when calling the get_queryset function? def get_queryset(x, y): queryset = Membership.objects.filter(x=y) return queryset -
Django: Sum of regrouped items on template
Provided our models are: Project Payment (foreign key to Project) View is a ListView for Payment on template {% regroup payments by project as project_list %} {% for project in project_list %} {{project}} {{<-- HOW TO OUTPUT THE SUM OF PAYMENTS FOR EACH PROJECT -->}} {% for payment in project.list %} {{payment}} {% endfor %} {% endfor %} How to output the sum of payments for each project? I can do Payment.objects.filter(payer=self.request.user).order_by('-date_created').annotate(total_per_project=Sum('project__donation__amount')) but total_per_project can be used only in the second for loop as {{payment.total_per_project}} while I need to have it in the first one, i.e. {{project.total_per_project}} -
Having trouble printing form credentials
Hey guys im pretty new to django and having a trouble when I try to print the posted credentials on my form. Here is what my html looks like <form method="post" style="font-family: Roboto, sans-serif;font-size: 36px"> {% csrf_token %} <div class="form-group"><input class="form-control" type="text" name="adsoyad" placeholder="Adınız ve Soyadınız" required=""></div> <div class="form-group"><select class="form-control" name="sehir" required=""> <optgroup label="Yaşadığınız Şehir"> <option value="12">Aydın</option> <option value="13">Balıkesir</option> <option value="14">Bilecik</option> <option value="15">Bursa</option> <option value="16">Edirne</option> <option value="17">Eskişehir</option> <option value="18">İstanbul</option> <option value="19">İzmir</option> <option value="20">İzmit</option> <option value="21">Kırklareli</option> <option value="22">Kocaeli</option> <option value="23">Kütahya</option> <option value="24">Manisa</option> <option value="25">Sakarya</option> <option value="26">Tekirdağ</option> <option value="27">Uşak</option> <option value="28">Yalova</option> <option value="29">Çanakkale</option> </optgroup> </select></div> <div class="form-group"><input class="form-control" type="tel" placeholder="Telefon Numaranız" name="telefon" required="" minlength="9" maxlength="10""> </div> <div class="form-group"><select class="form-control" name="medenidurum" required=""> <optgroup label="Medeni Durumunuz"> <option value="12" selected="">Evli</option> <option value="13">Bekar</option> <option value="14">Dul</option> </optgroup> </select></div> <div class="form-group"><input class="form-control" type="text" name="meslek" placeholder="Mesleğiniz" required="" minlength="0" maxlength="30"></div> <div class="form-group"><input class="form-control" type="number" name="dogumyili" placeholder="Doğum Yılınız" min="0" max="2020" required=""> </div> <div class="form-group"> <button class="btn btn-primary" type="submit" style="background: rgb(235,235,235);"> GÖNDER </button> </div> </form> and my views.py is here def index(request): if request.method == 'POST': adsoyad = request.POST['adsoyad'] telefon = request.POST['telefon'] sehir = request.POST['sehir'] medenidurum = request.POST['medenidurum'] meslek = request.POST['meslek'] dogumyili = request.POST['dogumyili'] print(adsoyad, telefon, sehir, medenidurum, meslek, dogumyili) return render(request, 'index.html') The sehir and medenidurum field is not working when … -
Docker django connect non docker postgresql
I have django project and trying to dockerize the project. Everything is working very well but the problem with postgresql. I have installed my postgresql in my local machine, so postgresql host is localhost and my django app running in my local machine docker. I dont want to install postgresql with docker, it's already installed without docker. so i tried to connect this with following infomrmatin: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydbname', 'USER': 'postgres', 'PASSWORD': 'secret', 'HOST': 'localhost', 'PORT': '5432', } } and it is not working, it's firing error. Can anyone help me what can i do in this case? I dont want to install postgres by docker, the datbase should be in my direct local machine. and this is my dockerFile FROM python:3.8.1-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 # Install system packages required by Wagtail and Django. RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" # Install the project requirements. COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . … -
TypeError: UserProfile() got an unexpected keyword argument 'user'
Error TypeError at /spotify/authorize/ UserProfile() got an unexpected keyword argument 'user' Aim is to create a UserProfile as soon as a user is created models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE), liked_songs = models.ForeignKey("Song", on_delete= models.CASCADE, default=None) class Meta: db_table = "UserProfile" def create_profile(sender, **kwargs): if kwargs["created"]: user_profile = UserProfile.objects.create(user=kwargs["instance"]) post_save.connect(create_profile, sender=User) class Album(models.Model): Album_name = models.CharField(max_length=40) class Meta: db_table= "Album" class Song(models.Model): track_name = models.CharField(max_length=250) artiste_name= models.CharField( max_length=200, default=None ) album = models.ForeignKey(Album, on_delete= models.CASCADE) class Meta: db_table="Song" def __str__(self): return self.track_name -
DRF - overrige Serializer.update to update related set
I'm trying to override update method of ModelSerializer so I can update the related set of objects while updating the instance. The problem is that validated_data doesn't include ids of these objects even when I'm passing there to the serializer. def update(self, instance, validated_data): subcontracts = validated_data.pop('subcontracts') # THERE ARE NO IDS HERE contract = super().update(instance,validated_data) instance.subcontracts.exclude(id__in=[x.get('id',None) for x in subcontracts if x is not None]).delete() for subcontract in subcontracts: _id = subcontract.get('id',None) if _id: sc = SubContract.objects.get(id=_id) else: sc = SubContract() for attr, value in subcontract.items(): setattr(sc, attr, value) sc.contract = instance sc.save() return contract Basically, what I want to do: {id:4, some_data..., subcontracts:[{id:1,description:'xxx'},{id:2,description:'yyy'}]} This data would (except updating the instance) delete related subcontracts not having id 1 or 2 and update the rest. Do you know what to do? -
when i use objecs.values('xx') i am losing my related fields
Firstly, sorry for couldn't find right title for my problem. I prapered a queryset in views.py. It is grouping the countries and summing the cities population. There is no problem and i can show the sum of population and grouped country as {% for query in queryset %}<li>{{query.countryname__name}} : {{query.country_population}}</li>{% endfor %} But how can i add location of country which i defined on my models.py? Or other related county fields? Because when i use City.objects.values('countryname__name') i am losing my data and can not reach any field as City.objects.all() :( Models.py class Seasons(models.Model): season = models.CharField(max_length=50) def __str__(self): return self.season class Country(models.Model): name = models.CharField(max_length=30) location = models.CharField(max_length=50) flag_def = models.CharField(max_length=50, null = True, blank = True) season_country = models.ManyToManyField("Seasons") def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=30) countryname = models.ForeignKey(Country, on_delete=models.CASCADE) population = models.PositiveIntegerField() def __str__(self): return self.name views.py def index(request): queryset = City.objects.values('countryname__name').annotate(country_population=Sum('population')) content = { "queryset" : queryset } return render(request,"index.html", content) template.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Population</h1> {% for query in queryset %} <li>{{query.countryname__name}} : {{query.country_population}} {{query.countryname__name.location}} </li> {% endfor %} </body> </html> display: Population Brazil : 7700000 (in here i would like to display … -
ManyToMany field query returns empty set but not empty
I have a many-to-many field that when queried is returning an empty QuerySet but is definitely not empty. I can see this from the admin page. I can see in admin that there is an Application object in Vacancy(id=1). Plus when I query the job for an Application, it returns Vacancy(id=1). I have included my shell script below. models.py class Vacancy(models.Model): CATEGORY_CHOICES = [ ('ADMINISTRATION', 'Administration'), ('CONSULTING', 'Consulting'), ('ENGINEERING', 'Engineering'), ('FINANCE', 'Finance'), ('RETAIL', 'Retail'), ('SALES', 'Sales'), ] employer = models.ForeignKey('Employer', on_delete=models.CASCADE) job_title = models.CharField(max_length=35, default=None) main_duties = models.TextField(default=None, validators=[ MinLengthValidator(650), MaxLengthValidator(2000) ]) person_spec = models.TextField(default=None, validators=[ MinLengthValidator(650), MaxLengthValidator(2000) ]) salary = models.PositiveIntegerField(default=None, validators=[ MinValueValidator(20000), MaxValueValidator(99000) ]) city = models.CharField(choices=CITY_CHOICES, max_length=11, default=None) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15, default=None) max_applications = models.PositiveSmallIntegerField(blank=True, null=True) deadline = models.DateField(blank=True, null=True) applications = models.ManyToManyField('Application', blank=True) active = models.BooleanField(default=True) class Meta: verbose_name_plural = 'vacancies' class Application(models.Model): STAGES = [ ('pre-selection', 'PRE-SELECTION'), ('shortlisted', 'SHORTLISTED'), ('rejected pre-interview', 'REJECTED PRE-INTERVIEW'), ('rejected post-interview', 'REJECTED POST-INTERVIEW'), ('successful', 'SUCCESSFUL') ] candidate = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) job = models.ForeignKey('Vacancy', on_delete=models.CASCADE) cv = models.CharField(max_length=35, default=None) cover_letter = models.TextField(default=None, validators=[ MinLengthValidator(0), MaxLengthValidator(2000) ]) submitted = models.DateTimeField(auto_now_add=True) stage = models.CharField(choices=STAGES, max_length=25, default='pre-selection') manage.py shell >>> from recruit.models import * >>> RA = Vacancy.objects.get(id=1) >>> RA <Vacancy: 1 Research Administrator> …