B
B
Balundula2022-04-18 21:12:29
Django
Balundula, 2022-04-18 21:12:29

How to exclude duplicate rows in a model?

There are 3 models: Advertisements(Stores ads), AdvertisementsStatus(ad status) and AdvertisementsInfo(Data about the author of the publication)
How can I prevent duplicate users in the AdvertisementsInfo model? If there is already a user in the table: does not create a new entry, but uses an existing one.

Here is the code: (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)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Markin, 2022-04-18
@Balundula

Usually such constraints are made using constraints

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question