@sparkjet

Не могу создать модель после того как отправляю форму (RelatedObjectDoesNotExist)?

У меня есть форма на странице которая должна создавать модель. Но после того как я ее отправляю Django выдает ошибку о том, что якобы модель не имеет wallet атрибут, однако это не так. Тем не менее если создавать модель через admin панель никаких ошибок нет.

views.py
class OperationCreateView(CreateView):
    form_class = forms.OperationCreateForm
    template_name = 'profiles/operation-create.html'
    success_url = reverse_lazy('profiles:current_wallet')
    extra_context = {'title': 'Create operation'}

    def form_valid(self, form):
        wallet = Wallet.objects.get(pk=self.kwargs['pk'])
        Operation.objects.create(wallet=wallet, **form.cleaned_data)

        if self.request.user == wallet.owner:
            messages.success(self.request, 'The operation was successfull')
            return redirect(self.success_url)

        raise Http404('There is no page you are looking for')

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)


models.py
class Operation(models.Model):
    '''
    Operation class stand for determine payment and repayment
    '''
    wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE)
    amount = models.DecimalField(
        _('Money payment/repayment amount'),
        decimal_places=2,
        max_digits=11,
        default=0.00,
    )

    description = models.TextField(
        _('Description for your payment/repayment'),
        max_length=100,
        help_text=('100 letters max length.'),
    )

    # decide will it be payment or repayment
    option = models.CharField(
        _('Operation type'),
        max_length=13,
        choices=[('PAYMENT', 'Payment'), ('REPLINISHMENT', 'Replinishment')],
    )

    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'{self.option}: {self.pk}'

    def get_amount(self):
        return '{}{}'.format(self.wallet.currency, self.amount)

    def clean(self):
        if self.option == 'REPLINISHMENT':
            # check, if the payment amount + wallet balance will be
            # more than wallet can accommodate
            if len(str(self.amount + self.wallet.balance)) > 12:
                raise ValidationError(
                    {'amount': 'There is no more space in the wallet.'}
                )
        elif self.option == 'PAYMENT':
            if self.amount > self.wallet.balance:
                raise ValidationError(
                    {'amount': 'The amount of payment is more than you have on your wallet.'}
                )

    def save(self, *args, **kwargs):
        if self.option == 'PAYMENT':
            self.wallet.balance = self.wallet.balance - self.amount
        elif self.option == 'REPLINISHMENT':
            self.wallet.balance = self.wallet.balance + self.amount

        self.wallet.save()
        return super().save(*args, **kwargs)


URL к этому сайту
path('wallets/<int:pk>/operation-create', views.OperationCreateView.as_view(), name='operation_create')


operation-create.html
{% extends "profiles/base_profile.html" %}
{% load crispy_forms_tags %}

{% block blck %}
	<div class="w-50 mx-auto">
		<form method="POST" class="mt-4">
			{% csrf_token %}
			{{ form|crispy }}
			<input type="submit" value="Create" class="btn btn-primary">
		</form>
	</div>
{% endblock blck %}


Ошибка
Environment:

Request Method: POST
Request URL: localhost:8000/profile/wallets/1/operation-create

Django Version: 3.0.4
Python Version: 3.8.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'authapp.apps.AuthappConfig',
'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Марина\Desktop\practice\mWallet_w\mWallet\profiles\views.py", line 246, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\forms\forms.py", line 180, in is_valid
return self.is_bound and not self.errors
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\forms\forms.py", line 175, in errors
self.full_clean()
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\forms\forms.py", line 378, in full_clean
self._post_clean()
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\forms\models.py", line 404, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\db\models\base.py", line 1207, in full_clean
self.clean()
File "C:\Users\Марина\Desktop\practice\mWallet_w\mWallet\accounts\models.py", line 149, in clean
if len(str(self.amount + self.wallet.balance)) > 12:
File "C:\Users\Марина\Desktop\practice\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 196, in __get__
raise self.RelatedObjectDoesNotExist(

Exception Type: RelatedObjectDoesNotExist at /profile/wallets/1/operation-create
Exception Value: Operation has no wallet.

https://imgur.com/a/iroWdly (скрин)
  • Вопрос задан
  • 135 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы