Почему в форме не отображается строка с email?
Пытаюсь сделать регистрацию по почте, все делал по этому гайду
https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef
но в форме строчка с email не отображается, хотя я указал это в forms.py
from django import forms
from .models import Post, Comment
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'body')
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
}
class SignupForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
signup.html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
{% block content %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
{% endblock %}
myblog/views.py
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post, Comment
from .forms import CommentForm
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import login
from .forms import SignupForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignupForm()
return render(request, 'registration/signup.html', {'form': form})
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
# return redirect('home')
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
else:
return HttpResponse('Activation link is invalid!')
class BlogListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'posts'
paginate_by = 2
queryset = Post.objects.all()
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'post_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')
#fields = '__all__'
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
@property
def image_url(self):
if self.image:
return getattr(self.photo, 'url', None)
return None
accounts/views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUpView(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
Если понадобится, скажите какие еще файлы показать, все покажу конечно же
п.с. небольшая ремарочка, в форме у меня указаны 4 строки: 'username', 'email', 'password1', 'password2', именно 'email' почему то не отображается
Я новичок в django, буду благодарен абсолютно любому совету, Спасибо!
Ответы (2 шт):
Если у вас не отображается атрибут help_text у поля email, то тут несколько решений.
Просто в шаблоне вывести (без цикла)
{{form.as_p}}, соответственно будет выведена форма с именами полей и так же будет выведен help_text.В цикле
{% for field in form %}обратиться к{{field.help_text}}В файле forms.py, в вашей форме SignupForm, у поля email сделать widget. То есть:
email=forms.EmialField(max_length=200, widget=(forms.EmailInput(attrs={'placeholder':'Это поле является обязательным'})))'
И в attrs можно указать placeholder.
в accounts/views.py в form_class был UserCreationForm, вместо SignupForm
