I'm creating a project where:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With