简体   繁体   中英

How do I make a input from the user to search for something in django/python?

I'm relatively new in python/django thing. Having 3 models with some fields for example:

class Card(models.Model):    
    id = models.AutoField(primary_key=True)    
    cardtype_id = models.CharField(max_length=10)   
    holder_name = models.CharField(max_length=100)   
    card_number = models.IntegerField(default=0)   
    email = models.EmailField(blank=True)   
    birthday = models.DateField(blank=True, default=None)  
    created = models.DateTimeField(default=timezone.now)  
    updated = models.DateTimeField(default=timezone.now)  
    strip = models.CharField(max_length=20, default="strip")

  def __str__(self):
        return self.holder_name

class Transaction(models.Model):
    id = models.AutoField(primary_key=True)  
    description = models.CharField(max_length=100)

class CardTransactions(models.Model):
    card = models.ForeignKey(Card, on_delete=models.CASCADE)   
    transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)   
    value = models.DecimalField(max_digits=7, decimal_places=2, blank=True)   
    value_date = models.DateTimeField(default=timezone.now)   
    created = models.DateTimeField(default=timezone.now)   
    description = models.CharField(max_length=200, blank=True)   
    table_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True)   
    discount = models.DecimalField(max_digits=7, decimal_places=2, blank=True)   
    net_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True)   
    doc_number = models.CharField(max_length=20, blank=True)

How can I ask the user to input, for example, the "card_number" and print out the "description" on a HTML page?

from django.forms import model_to_dict


def my_view(request):
    card_num = request.GET.get('cc')
    return HttpResponse(str(model_to_dict(Card.objects.filter(card_number=card_num).first()))

at least something like that

You will need to write views and templates to do this task.

  • One view would be to render the html template where you will have a form to input the value.

  • Clicking on the button will call another view with parameter card_number which will retrieve the description from the database associated with the card_number and return back to the template where the same can be shown with some div as per your design.

  • Ajax can be used to call the view and fetch the response.

See below links for reference:

https://docs.djangoproject.com/en/2.0/intro/tutorial03/

https://docs.djangoproject.com/en/2.0/intro/tutorial04/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM