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.


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)',
     tip = models.IntegerField(verbose_name='Tip amount (in cents)',
     comments = models.CharField(max_length=255, blank=True, null=True)
     timestamp = models.DateTimeField(auto_now_add=True)


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

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


 def select_bill(request):
     Finds a bill based on its ID number.
     if request.method == 'POST':
         form = BillSelectForm(request.POST)
         if form.is_valid():
             # 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

         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()


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

     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


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