简体   繁体   中英

How can I pass string from HTML file to view in django?

I'm new in django and i have this input in HTML,and i nedd to get the string typed from the user and send for my views.py:

        <form id="username_exists_form" method='GET'>
            Name: <input type="username" name="username" />
            <button type='submit'> Check </button>           
        </form> 

That's my view.py, i nedd the string replace "username":

    template_name = 'Exames.html'
    def get_context_data(self,**kwargs):
        context = super(ShowExames, self).get_context_data(**kwargs)
        exames = Examlabs.objects.filter(id_atendimento = username)
        context.update({'exames': exames})
        return context
    def get_queryset(self):
        return Examlabs.objects.all()```

First, create a UserForm

myapp/forms.py

class UserForm(forms.Form):
   user = forms.CharField(max_length = 100)

Inside the view.py

from myapp.forms import UserFrom

def user_form(request):   
   if request.method == "POST":
      # Get the posted form
      my_user_form = UserFrom(request.POST)
      
      if my_user_form.is_valid():
         # do anything here
         username = my_user_form.cleaned_data['username']
   else:
      my_user_form = UserFrom()
        
   return render(request, 'mypage.html', {"username" : username})

Inside mypage.html

<html>
   <body>
      <form name = "form" action = "{% url "myapp.views.user_form" %}" 
         method = "POST" >{% csrf_token %}
               <input type = "text" name = "username" />
               <button type = "submit" value = "Submit" ></button>
      </form>
   </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM