Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

models.py

import uuid

class AddToDatabase(models.Model):
    user_input = models.CharField(max_length=50, unique=True)
    random_url = models.UUIDField(default=uuid.uuid4)

forms.py

from .models import AddToDatabase
class InputForm(forms.ModelForm):

    class Meta:
      model = AddToDatabase
      fields = ["user_input"]

views.py

from django.shortcuts import redirect

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

        if form.is_valid():
            form_instance = form.save(commit=False)
            form_instance.save()
            return redirect("form_detail", random_url=form_instance.random_url)
  return render(request, 'index.html', {'form':form})


def form_detail(request, random_url):
    template = "form_detail.html"
    context = {}
    form_detail = get_object_or_404(AddToDatabase, random_url=random_url)
    context["form_detail"] = form_detail
    return render(request, template, context)

urls.py

from . import views

urlpatterns = [

 url(r'^home/$' views.Home, name="home"),
url(r'^form-detail/(?P<random_url>[-\w]+)/$', views.form_detail, name="form_detail")
]

in form_detail.html template

<div>
  <p> User Input : {{ form_detail.user_input }}</P>
</div>
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!