Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating random URLs in Django?

I'm creating a project where:

  1. A user submits an input into a form
  2. That data is input into the database
  3. A random URL is generated (think imgur / youtube style links)
  4. The user is redirected to that random URL
  5. The input data is display on that random URL

forms.py

class InputForm(forms.Form):
    user_input = forms.CharField(max_length=50, label="")
    random_url = forms.CharField(initial=uuid.uuid4().hex[:6].upper())

models.py

class AddToDatabase(models.Model):
    user_input = models.CharField(max_length=50, unique=True)
    random_url = models.CharField(max_length=10, unique=True)

views.py

def Home(request):
    if request.method == 'POST':
        form = InputForm(request.POST)

        if form.is_valid():
            user_input = request.POST.get('user_input', '')
            random_url = request.POST.get('random_url', '')
            data = AddToDatabase(user_input=user_input, random_url=random_url)
            data.save()

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

    else:

        form = InputForm()
        return render(request, 'index.html', {'form':form})

index.html

<form action="" method="POST">
    {{form}}
    {% csrf_token %}
    <input type="submit">
</form>

I'm new to Python / Django, which is probably obvious. The above code allows users to submit an input which is succesfully added to the database. It also generates 6 random characters and adds that to the database.

The problem is I don't know how to turn that random code into a URL and redirect the user there after submitting the form.

I've tried a couple of methods so far, such as adding action="{{ random_url }}" to the index.html form, as well as adding url(r'(?P<random_url>\d+)', views.Home, name='home') to urls.py

like image 373
Liam Avatar asked Oct 30 '22 08:10

Liam


1 Answers

I would recommend using something like Hashids for your URLs instead of uuid.uuid4()[:6], but I think your immediate problem is in urls.py:

url(r'(?P<random_url>\d+)', views.Home, name='home')

Here your regular expression for random_url is \d+. \d+ matches one or more decimal digits, but the values generated by uuid.uuid()[:6] aren't decimal. I think \w will be a better fit.

The other problem is that views.Home doesn't accept the "random URL", so it never knows which one to display. Give it a second argument:

def Home(request, random_url=None):

and then use random_url inside Home to load the correct page from the database. I suspect this should actually happen in a new view function, but I'm not clear on what each page represents so I can't recommend a good name for it.

like image 133
Chris Avatar answered Nov 15 '22 06:11

Chris