I have a Django form that a user enters one input into. After submitting they are taken to a URL associated with their input.
The database contains user_input and associated_url fields.
The user_input has the value unique=True set. When a duplicate input is entered the following displays on the website This value user_input already exists in the database even though I didn't set this so it. This may be feature of form.is_valid()?
So it immediately recognizes duplicate values, but I am trying to set it so that if a duplicate value is entered then it will just take the user to the associated_url for that value.
i.e.
Existing database table:
user_input associated_url
hello https://stackoverflow.com
If a user were to input hello into the form again, it would immedietly take them to https://stackoverflow.com instead of showing This value user_input already exists in the database
Code:
def Primary(request):
form = Form()
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
... saving to database, redirect etc.
I need to be able to check if the input value is a duplicate. If it is then get the associated_url from the same row as the duplicate user_input entry and redirect the user there.
To do this myself I attempted adding an else statement to the form.is_valid condition, but that seems like bad practice because it will attempt to redirect regardless of the error(?) and because I don't know how to get the associated_url associated with the input value.
You have multiple options for this but some of them are.
param = request.POST["param"]
if YourModel.objects.get(param=param):
redirect('/myurl/{}'.format(param))
else:
if form.is_valid():
# other code
Or write your own custom clean() method for the form you're using.