Есть 3 модели: Advertisements(Хранит объявления), AdvertisementsStatus(статус объявления) и AdvertisementsInfo(Данные об авторе публикации)
Как сделать так, чтобы в модели AdvertisementsInfo пользователи не дублировались? Если есть уже пользователь в таблице: не создает новую запись, а использует уже существующую.
Вот код: (models.py)
from django.db import models
# Create your models here.
class Advertisements(models.Model):
title = models.CharField(max_length=200, verbose_name='Заголовок')
text = models.TextField(max_length=1000, verbose_name='Текст')
date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')
status = models.ForeignKey('AdvertisementsStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='status')
publisher = models.ForeignKey('AdvertisementsInfo', default=None, null=True, on_delete=models.CASCADE,
related_name='publisher')
class AdvertisementsStatus(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class AdvertisementsInfo(models.Model):
user_name = models.CharField(max_length=100, verbose_name='Имя пользователя')
phone_number = models.CharField(max_length=100, verbose_name='Телефон пользователя')
forms.py
from django.forms import ModelForm, TextInput, Textarea
from advertisements.models import Advertisements, AdvertisementsInfo
class AdvertisementsForm(ModelForm):
class Meta:
model = Advertisements
fields = ['title', 'text', 'status']
widgets = {
"title": TextInput(attrs={
"class": "form-input",
"placeholder": "Введите заголовок",
}),
"text": Textarea(attrs={
"class": "form-input form-textarea",
"placeholder": "Введите текст"
}),
}
class AdvertisementsInfoForm(ModelForm):
class Meta:
model = AdvertisementsInfo
fields = '__all__'
widgets = {
'phone_number': TextInput(attrs={
"placeholder": 'Введите номер'
}),
'user_name': TextInput(attrs={
"placeholder": 'Введите имя'
}),
}
views.py
from django.shortcuts import render, redirect
from django.views.generic import CreateView
from django.http import HttpResponseRedirect
from advertisements.froms import AdvertisementsForm, AdvertisementsInfoForm
# Create your views here.
def index(request):
return render(request, 'advertisements/base.html', {})
class CreateAdvertisements(CreateView):
template_name = 'advertisements/create_adv.html'
adv_info_form = AdvertisementsInfoForm()
adv_form = AdvertisementsForm()
def get(self, request, *args, **kwargs):
context = {'person': self.adv_info_form, 'form':self.adv_form}
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
adv_info_form = AdvertisementsInfoForm(request.POST)
adv_form = AdvertisementsForm(request.POST)
if (adv_form.is_valid() and adv_info_form.is_valid()):
adv_f = adv_form.save(commit=False)
inf_adv_f = adv_info_form.save()
adv_f.publisher_id = inf_adv_f.id
adv_f.save()
return HttpResponseRedirect('/home/')
else:
error = 'Ошибка'
context = {'person': self.adv_info_form, 'form': self.adv_form, 'error': error}
return render(request, self.template_name, context)