Django Многошаговая форма
В настоящее время моя регистрация для всех пользователей работает, но я хочу добавить 2 кнопки перед ней, которые будут регистрировать по-разному в зависимости от того, на какой элемент они нажали. Используйте обычную регистрацию, если это пользователь, и используйте другую для доктора.
2 пользователя: Доктор и Пользователь.
<html>
<body>
<button>Doctor</button>
<button>User</button>
</body>
</html>
models.py:
is_doctor -> a boolean
has_credentials -> verifies doctor a file upload -> wants admin to verify before adding
signup.html (отображается на http://localhost:8000/signup/)
{% block content %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
<a href="{% url 'login' %}">Log In</a>
</form>
{% endblock %}
views.py
from django.shortcuts import redirect, render
from .forms import SignUpForm, UserProfileForm
from django.contrib.auth import login, authenticate
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
forms.py
from django import forms
from django.core.files.images import get_image_dimensions
from pages.models import Profile
from django.contrib.auth.forms import UserCreationForm
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = Profile
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
Значение по умолчанию для атрибута type элементов button равно "submit"
, установите его в type="button"
, чтобы создать кнопку, которая не отправляет форму.
<form method="POST">
{% csrf_token %}
<button class="btn-doctor" type="button">Doctor</button>
<button class="btn-user" type="button">User</button>
<input style="display: none;" id="input-doctor" name="is-doctor" type="radio">
<button type="submit">Sign Up</button>
</form>
Тогда вы можете использовать <input type="radio">
, установите display: none
, если вы не хотите показывать его.
Теперь вы можете использовать свойство input radio checked
при нажатии пользователем кнопки 'Doctor'
. Например, с помощью jQuery:
$('.btn-doctor').click(function(){
$('#input-doctor').prop('checked', true);
});
$('.btn-user').click(function(){
$('#input-doctor').prop('checked', false);
});
В вашем views.py
вы можете проверить ввод с именем is-doctor
:
is_doctor = False
if request.method == "POST":
if "is-doctor" in request.POST:
is_doctor = True