Housi
Housi

Reputation: 47

How to make the appearance of form in django?

I am trying to make a form but it is not showing me. Instead it is giving me error UnboundLocalError at /withdraw/ local variable 'form' referenced before assignment How to resolve this issue?

views.py

@login_required
def withdraw(request):
    if request.method == 'POST':
        form = Withdrawapayment(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your request has been submitted.')
            return redirect('balance')

    context = {'form': form}
    return render(request, 'nextone/withdraw.html', context)

models.py

class WithdrawPayment(models.Model):
    payment = models.DecimalField(max_digits=100, decimal_places=2)

    class Meta:
        verbose_name_plural = 'Withdraw Payment'

forms.py

class Withdrawpayment(forms.ModelForm):
    class Meta:
        model = WithdrawPayment
        fields = ['payment']

Upvotes: 1

Views: 93

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You are handling for POST request only so change your view like this:

@login_required
def withdraw(request):
    if request.method == 'POST':
        form = Withdrawapayment(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your request has been submitted.')
            return redirect('balance')
    else:
        form = Withdrawpayemnt()
    context = {'form': form}
    return render(request, 'nextone/withdraw.html', context)

Upvotes: 5

Related Questions