K
K
Kirill2021-05-07 15:48:10
Django
Kirill, 2021-05-07 15:48:10

Why does FOREIGN KEY constraint failed when deleting an object?

There are two different pages where you can add a transport:
1) Directly from the order page
2) In your personal account

If you add an object (transport) from your personal account, then it is deleted successfully. And when adding it from the order page - FOREIGN KEY constraint failed error.

Object deletion code:
Received when object id is deleted

Transport.objects.get(id=form['transport_id'], _client=client_current).delete()
return HttpResponse('ok')


Add code via personal account:
transport = Transport.objects.create(_client=client_current, brand=form['brand'], model=form['model'],
                                     transport_type=form['transport_type'], gos_number=form['gos_number'])
return HttpResponse(json.dumps({'id': transport.id, 'brand': transport.brand, 'model': transport.model,
                                'transport_type': transport.transport_type,
                                'gos_number': transport.gos_number, 'images': [], 'orders': []}),
                    content_type="application/json")


Code for adding via post:
form = request.POST
user = None
point_id = form['point']
fio = form['fio']
telephone = form['telephone']
date = form['date']
add_info = form['add_info']
try:
    form['register_client']
    if User.objects.filter(username=telephone):
        return HttpResponse(json.dumps({'status': 'err', 'desc': 'User already exists', 'code': 1}), content_type='application/json')
    user_model = User.objects.create(username=telephone, email=form['email'], password=form['password'])
    user = client.objects.create(_user=user_model, fio=fio, email=form['email'], telephone=telephone)
    user_model.user_permissions.add(Permission.objects.get(codename='is_client'))
    login(request, user_model)
except:
    user = client.objects.get(_user=request.user)
try:
    form['create_auto']
    ts = Transport.objects.create(_client=user, brand=form['brand'], model=form['model'],
                                     transport_type=form['transport_type'],
                                     gos_number=form['gos_number'])
except:
    ts_id = form['ts']
    ts = Transport.objects.get(id=ts_id)


Honestly, there may be some kind of jamb somewhere, but I don’t see it. Crutches with try - except:
1) if the user is not registered, then he creates it (+ the corresponding fields come)
2) if you want to create a vehicle directly when ordering

models.py:
class client(models.Model):
    _user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name='Модель пользователя'
    )
    fio = models.TextField(
        verbose_name='ФИО',
    )
    email = models.EmailField(
        verbose_name='Эл. почта',
        unique=True
    )
    telephone = models.CharField(
        verbose_name='Номер телефона',
        max_length=11,
    )

    class Meta:
        permissions = (
            ("is_client", "Can see client's urls"),
        )

    def __str__(self):
        return self.fio


class Transport(models.Model):
    _client = models.ForeignKey(
        client,
        on_delete=models.CASCADE,
        verbose_name='Профиль клиента',
    )
    brand = models.TextField(
        verbose_name='Марка ТС'
    )
    model = models.TextField(
        verbose_name='Модель ТС'
    )
    transport_type = models.CharField(
        choices=att,
        max_length=3,
        verbose_name='Категория ТС'
    )
    gos_number = models.TextField(
        verbose_name='Гос. номер ТС'
    )
    vin = models.TextField(
        verbose_name='VIN номер'
    )

    def __str__(self):
        return str(self.brand) + ' ' + str(self.model)

I know about the incorrect name of the client model. Maybe I'll fix it later.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question