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']
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)
Related
I got this error in my functional view:
save() got an unexpected keyword argument 'commit'
I'm try to save one object in database. 'debtors' is Many to Many field in models.py.
forms.py
class ExpenseForm(forms.ModelForm):
class Meta:
model = Expense
fields = ('amount', 'text', 'debtors', 'date', 'time',)
widgets = {
'date': AdminDateWidget(),
'time': AdminTimeWidget(),
'debtors': forms.CheckboxSelectMultiple(),
}
views.py
def expenseformview(request, pk):
if request.method == 'POST':
form = Expense.objects.create(
expenser = request.user,
amount = request.POST.get('amount'),
text = request.POST.get('text'),
date = request.POST.get('date'),
time = request.POST.get('time'),
)
form.debtors.add(request.POST.get('debtors'))
formcoseshare = form.save(commit=False)
formcoseshare.save()
form.save_m2m()
return redirect('expense_detail', pk=pk, expenseid=form.id)
else:
form = ExpenseForm()
return render(request, 'financials/expense_form.html', {'form': form})
How can to solve this problem?
Your form is not an ExpenseForm, it is a model object Expense, hence commit=False makes no sense, and neither does .save_m2m():
from django.contrib.auth.decorators import login_required
#login_required
def expenseformview(request, pk):
if request.method == 'POST':
form = ExpenseForm(request.POST, request.FILES)
if form.is_valid():
form.instance.expenser = request.user
expense = form.save()
return redirect('expense_detail', pk=pk, expenseid=expense.pk)
else:
form = ExpenseForm()
return render(request, 'financials/expense_form.html', {'form': form})
It is however unclear to me what pk is doing here: you do not use it in any way.
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.html', context)
im using a non-model based form django.
once i get the data,i create a model object.
but when im trying to edit my post(a blog/quote based app),im not able to create a form object using the model object for a specific post.
these are my codes:
views.py:
def quote_form(request):
if request.method=='POST':
form=Quote(request.POST)
if form.is_valid():
quote=form.cleaned_data['quote']
author=form.cleaned_data['author']
popularity=form.cleaned_data['popularity']
category=form.cleaned_data['category']
p=Quote1(quote=quote, author=author, popularity=popularity, category=category)
p.save()
return redirect("quote_list")
else:
form=Quote()
return render(request,'quote/form.html',{'form':form})
def quote_edit(request, pk):
q = get_object_or_404(Quote1, pk=pk)
if request.method == "POST":
form = Quote(request.POST,instance=q)
if form.is_valid():
q = form.save(commit=False)
q.author = request.user
q.save()
return redirect('quote_detail', pk=q.pk)
#return render(request,"blog/post_detail.html",{'post':post})
else:
form = Quote(instance=q)
return render(request, 'quote/quote_edit.html', {'form': form})
models.py:
class Quote1(models.Model):
quote=models.CharField(max_length=200)
author=models.CharField(max_length=200)
popularity=models.IntegerField()
category=models.CharField(max_length=40)
forms.py:
class Quote(forms.Form):
quote=forms.CharField()
author=forms.CharField()
popularity=forms.IntegerField()
category=forms.ChoiceField(choices=[('life','life'),('happiness','happiness'),('love','love'),('truth','truth'),
('inspiration','inspiration'),('humor','humor'),('philosophy','philosophy'),('science','science')])
Try this:
def quote_edit(request, pk):
q = get_object_or_404(Quote1, pk=pk)
if request.method == "POST":
form = Quote(request.POST)
if form.is_valid():
quote=form.cleaned_data['quote']
author=form.cleaned_data['author']
popularity=form.cleaned_data['popularity']
category=form.cleaned_data['category']
q.quote=quote
q.author=author
q.popularity=popularity
q.category=category
q.save()
else:
form = Quote(initial=reauest.POST.copy())
return render(request, 'quote/quote_edit.html', {'form': form})
P.S:
Using ModelForm would have been better approach. If you can switch to ModelForm i can help there as well.
I have made a form to give an option for user to withdraw money. That data is saving in admin page but the problem is I have owner variable also, which I want that as the amount data is going to be saved in admin page the owner username should also be saved in admin, which shows who is desiring this amount?
models.py
from django.contrib.auth.models import User
class WithdrawPayment(models.Model):
payment = models.CharField(max_length=100)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = 'Withdraw Payment'
views.py
#login_required
def withdraw(request):
if request.method == 'POST':
form = WithdrawBalance(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, f'Your request has been submitted.')
return redirect('index')
else:
form = WithdrawBalance()
context = {'form': form}
return render(request, 'nextone/withdraw.html', context)
forms.py
class WithdrawBalance(forms.ModelForm):
class Meta:
model = WithdrawPayment
fields = ['payment']
Something like this:
#login_required
def withdraw(request):
form_class = WithdrawBalanceForm
if request.method == 'POST':
form = form_class(request.POST)
obj = form.save(commit=False)
obj.owner = request.user
obj.save()
messages.success(request, f'Your request has been submitted.')
return redirect('index')
else:
form = form_class()
context = {'form': form}
return render(request, 'nextone/withdraw.html', context)
class WithdrawBalanceForm(forms.ModelForm):
class Meta:
model = WithdrawPayment
fields = ['payment']
how to add an error message to be displayed if the user tried to add an entry that is already on the table
forms.py
class AddCatForm(ModelForm):
class Meta:
model = Categories
fields = ['category_name']
labels = {
'category_name': ('إسم الفئة الجديدة')
}
error_messages = {
'category_name': {
'unique': ('الفئة موجودة بالفعل')
}
}
views.py
def add_cat(request):
if request.method == "POST":
form = AddCatForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('/')
else:
form = AddCatForm()
return render(request, "add_cat.html", {'form': form})
When i add an entry that is already there , it just does nothing , i want it to view an error
You might be getting an error which you will not see because of your indentation. Amend it to:
def add_cat(request):
if request.method == "POST":
form = AddCatForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('/')
else:
form = AddCatForm()
return render(request, "add_cat.html", {'form': form})