Need to show result on the same page – Django

Question:

I’m creating a password generator app. The app is working and stores the value on db.

The problem is whenever I refresh, the form resubmits and takes the previous value and stores.

Also, I want to show the email and password on the same page.

Whenever I refresh, I want to show an empty form with empty fields.

Views.py

def home(request):
    if request.method=='POST':
            inputemail = request.POST.get('InputEmail')
            gen = ''.join(random.choices((string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation), k=10))
            newpass = Item(email=inputemail,encrypt=gen)
            newpass.save()
            return render(request,'home.html',{"gen":gen})
        
    
    return render(request,'home.html',{})

Home.html

<form method = 'post' id='pass-form' >
    {% csrf_token %}
    <div class="mb-3">
      <label for="exampleInputEmail1" class="form-label">Email address</label>
      <input type="email" class="form-control" name="InputEmail" >
      <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
    </div>
    
    <button type="submit" name = "submit" class="btn btn-primary">Generate Password</button><br><br>
  </form>
  
    <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">Generated Password</label>
        <input type="text" id="InputPassword" name = "genpassword" value = {{gen}} >
      </div>

Urls.py

urlpatterns = [
    path('',views.home,name='home'),
]
Asked By: Saassy

||

Answers:

According to docs:

you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn’t specific to Django; it’s good web development practice in general.

So you should make another page to show generated password, which will take submitted instance id of Item model created in home view so:

def home(request):
    if request.method=='POST':
        inputemail = request.POST.get('InputEmail')
        gen = ''.join(random.choices((string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation), k=10))
        newpass = Item(email=inputemail,encrypt=gen)
        newpass.save()
        return redirect('success', args=(newpass.pk))
       
    return render(request,'home.html',{})

def success(request, pk):
    item_obj = get_object_or_404(Item, pk=pk)
    return render(request,'success.html', {'gen':item_obj.encrypt})

urls.py

urlpatterns=[
    path('',views.home,name='home'),
    path('success/<int:pk>/',views.success,name='success')
]

success.html

<body>
    <h2>The form  is successfully submitted.</h2>
    <br> 
    <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">Generated Password</label>
            <input type="text" id="InputPassword" name="genpassword" value={{gen}} >
    </div>
    
    <a href="{% url 'home' %}"> Again go to password generator page.</a>
</body>


Another possible solution

You can make email field required in Html form and then hard refresh the page after submitting the form using Javascript’s submit event so the template:

<form method='POST' id='pass-form'>
    {% csrf_token %}
    <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label">Email address</label>
        <input type="email" class="form-control" name="InputEmail" required>
        <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
    </div>
    
    <button type="submit" class="btn btn-primary">Generate Password</button><br><br>
    </form>
    
    <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">Generated Password</label>
        <input type="text" id="InputPassword" name = "genpassword" value ={{gen}} >
    </div>
<script type='text/javascript'>
    let form =  document.getElementById('pass-form');
    addEventListener('submit', (event) => {
        location.reload(true); // hard refreshed
        console.log('hard refreshed')
    });

</script>

Note: Then also there are certain browsers like Microsoft Edge which gives pop up as Resubmit the form? in which they mention The page you’re looking for used information that you entered. Returning to the page might trigger a repitition of any action you took there. Do you want to continue?

The moment you click on continue it creates duplicacy of records, so I think as docs mentions the first approach is better.

Answered By: Sunderam Dubey