Home > OS >  Need to show result on the same page - Django
Need to show result on the same page - Django

Time:11-13

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 >
      <label for="exampleInputEmail1" >Email address</label>
      <input type="email"  name="InputEmail" >
      <div id="emailHelp" >We'll never share your email with anyone else.</div>
    </div>
    
    <button type="submit" name = "submit" >Generate Password</button><br><br>
  </form>
  
    <div >
        <label for="exampleInputPassword1" >Generated Password</label>
        <input type="text" id="InputPassword" name = "genpassword" value = {{gen}} >
      </div>

Urls.py

urlpatterns = [
    path('',views.home,name='home'),
]

CodePudding user response:

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 >
            <label for="exampleInputPassword1" >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 >
        <label for="exampleInputEmail1" >Email address</label>
        <input type="email"  name="InputEmail" required>
        <div id="emailHelp" >We'll never share your email with anyone else.</div>
    </div>
    
    <button type="submit" >Generate Password</button><br><br>
    </form>
    
    <div >
        <label for="exampleInputPassword1" >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 mentions 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.

  • Related