Home > Software engineering >  Read a value from the URL in django
Read a value from the URL in django

Time:12-21

i'm trying to read the value of a url and add it to the models in django.

Basically if i have the following link

my_site.com/special_event/123

How would i be able to catch the last part of the link the (123) and save it as an entry for my models. For context i am trying to do a raffle on my website, and when someone scans a QR code it will send them to my site and the end of the link will be a random number that i will use to raffle. So in this case a person's raffle ticket would be 123.

So far i have this code: the model:

class RaffleEntry(models.Model):
entry_number = models.IntegerField(blank=False)

def __str__(self):
    return self.entry_number

And the view i tried doing it this way:

def add_entry(request, entry_number):
    entry_number = RaffleEntry.objects.create()
    return render(request, 'front/entry_success')

I also tried to add an INT parameter to the URL like this:

    path('special_events/add_entry/<int:entry_number>', views.add_entry, name='special_events/add_entry>'),

Any help or even just point me in the right direction would be greatly appreciated. Thank you.

CodePudding user response:

from random import randint
generated=[]

def generate_random_number(seed):
    random_number=(randint(0,seed))
    return str(random_number)


for i in range(0,10):
        random_number=generate_random_number(9999)
        if not random_number in generated:
        url="my_site.com/special_event/" random_number
        url1=url
        url=(url.split("/"))
        print(url[len(url)-1], url1)
        generated.append(random_number)

print(generated)

4887 my_site.com/special_event/4887

682 my_site.com/special_event/682

3755 my_site.com/special_event/3755

7953 my_site.com/special_event/7953

8867 my_site.com/special_event/8867

5238 my_site.com/special_event/5238

9309 my_site.com/special_event/9309

2424 my_site.com/special_event/2424

3930 my_site.com/special_event/3930

8064 my_site.com/special_event/8064

['4887', '682', '3755', '7953', '8867', '5238', '9309', '2424', '3930', '8064']

CodePudding user response:

So to do what i wanted i just had to change my Views.py, here's the code:

def add_entry(request, entry_number):
RaffleEntry.instance = RaffleEntry.objects.create(entry_number=entry_number)
return render(request, 'front/entry_success.html', {'entry_number': entry_number})

This solved it.

  • Related