Last active
March 8, 2023 14:25
-
-
Save ILoveBacteria/55b374670d65ceeb38e0e7c789bcf6af to your computer and use it in GitHub Desktop.
A simple form in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
class NameForm(forms.Form): | |
your_name = forms.CharField(label='Your name', max_length=100) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form action="/your-name/" method="post"> | |
{% csrf_token %} | |
{{ form }} | |
<input type="submit" value="Submit"> | |
</form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponseRedirect | |
from django.shortcuts import render | |
from .forms import NameForm | |
def get_name(request): | |
# if this is a POST request we need to process the form data | |
if request.method == 'POST': | |
# create a form instance and populate it with data from the request: | |
form = NameForm(request.POST) | |
# check whether it's valid: | |
if form.is_valid(): | |
# process the data in form.cleaned_data as required | |
# ... | |
# redirect to a new URL: | |
return HttpResponseRedirect('/thanks/') | |
# if a GET (or any other method) we'll create a blank form | |
else: | |
form = NameForm() | |
return render(request, 'name.html', {'form': form}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment