django FormView code example
Example 1: createview django
from django.urls import reverse_lazy
class YourView(CreateView):
model = Model
fields = ['your_fields']
template_name = 'your_template'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.user = self.request.user
super(YourView, self).form_valid(form)
return redirect('home')
Example 2: django form view
class ContactView(FormView):
form_class = ContactForm
template_name = 'contact-us.html'
success_url = reverse_lazy('<app_name>:contact-us')
def get_initial(self):
initial = super(ContactView, self).get_initial()
if self.request.user.is_authenticated:
initial.update({'name': self.request.user.get_full_name()})
return initial
def form_valid(self, form):
self.send_mail(form.cleaned_data)
return super(ContactView, self).form_valid(form)
def send_mail(self, valid_data):
print(valid_data)
Example 3: formview django
from myapp.forms import ContactForm
from django.views.generic.edit import FormView
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/thanks/'
def form_valid(self, form):
form.send_email()
return super().form_valid(form)
Example 4: django updateview class
from .models import Article
from .forms import UpdateArticleForm
from django.views.generic import UpdateView
class ArticleUpdateView(UpdateView):
model = Article
form_class = UpdateArticleForm
template_name = 'articles/create_article.html'
from .views import ArticleUpdateView
urlpatterns =[
path('articles/<int:pk>/update/', ArticleUpdateView.as_view()),]