1024programmer Java How to include id field in django form?

How to include id field in django form?

I’m trying to create a simple form that pulls records by asking for an ID from the form.

views.py

class Bill(models.Model):
     """
     Represents a single purchase made by a customer at a business.
     """
     business = models.ForeignKey(Businesses)
     customer = models.ForeignKey(User, blank=True, null=True)
     charge = models.ForeignKey(Charge, blank=True, null=True)
     amount = models.IntegerField(verbose_name='Purchase amount (in cents)',
                                  validators=[MinValueValidator(0)])
     tip = models.IntegerField(verbose_name='Tip amount (in cents)',
                                  validators=[MinValueValidator(0)])
     comments = models.CharField(max_length=255, blank=True, null=True)
     timestamp = models.DateTimeField(auto_now_add=True)
 

Table

Import Form from Django Import ModelForm from django.forms Import Bill from transaction.models

class BillSelectForm(ModelForm):
     class Meta:
         model=Bill
         fields = ('id',)
 

views.py

@login_required(login_url='/sign-in/')
 def select_bill(request):
     """
     Finds a bill based on its ID number.
     """
     if request.method == 'POST':
         form = BillSelectForm(request.POST)
         if form.is_valid():
             pass
             # look up db for id number
             # go to bill view page if id found AND bill not paid
             # go back to same page and create message saying wrong bill

     else:
         form = BillSelectForm()

     return render(request, 'bill_select.html', {'form': form})
 

However, on the template, when I use {{ form.as_p }}, I see nothing. Any ideas?

1> e4c5..:


In this case, you should not use ModelForm. Fazil gave a great answer on what a primary key is and why you shouldn’t try to update it. But that’s what the model form is for.

On the other hand, in some cases the client is asked to provide a “reference number”, so the reference number often happens to be the primary key. So in this case the solution would be to use a simple Form instead of a ModelForm.

class BillSelectForm(forms.Form):
     pk = forms.IntegerField()
 

Then

if request.method == 'POST':
     form = BillSelectForm(request.POST)
     if form.is_valid():
         bill = Bill.objects.get(form.cleaned_data['pk'])

 else:
     form = BillSelectForm()
 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/764995

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索