success message is not working with create view - django

I have used SuccessMessageMixin class but then also in the createview I did'nt get the success message but in the updateview it is working when I return the super().form_valid(form)
class DepartmentCreateView(LoginRequiredMixin, PermissionRequiredMixin,SuccessMessageMixin ,CreateView):
template_name = 'departments/create_department.html'
form_class = DepartmentForm
success_url = reverse_lazy('departments:departments')
permission_required = ('departments.add_department',)
def form_valid(self, form):
department = form.save(commit=False)
department.created_by = self.request.user
department.updated_by = self.request.user
department.slug = slugify(uuid.uuid4())
department.save()
message = '[{"created": {}}]'
# retriving ContentType object
ct_obj = ContentType.objects.get(model='department')
# creating history object
history = History.objects.create(
action_time=timezone.now(),
action='created',
user=department.created_by,
content_type=ct_obj,
object_id=department.id,
change_message=message,
)
history.save()
return super().form_valid(form)

You haven't actually set a success message.
class DepartmentCreateView(LoginRequiredMixin, PermissionRequiredMixin,SuccessMessageMixin ,CreateView):
success_message = "Department was created successfully"
...
Note, your form_valid is saving things twice. You should do:
def form_valid(self, form):
form.instance.slug = slugify(uuid.uuid4())
return super().form_valid(form)

Related

Send mail after deleting django Model

I've been using send_mail() for when someone creates a Group (model) or updates it, but I've been having trouble figuring out the function for deleting.
This works for when someone creates a Group:
class CreateGroup(CreateView):
model = Group
form_class = GroupForm
template_name = 'create_group.html'
def form_valid(self, form):
instance = form.save()
account = self.request.user.account
send_mail (
f"Thanks for creating {instance.name}",
'create group',
NOTIFICATION_EMAIL,
[account.user.email],
fail_silently=False
)
return HttpResponseRedirect(reverse('group_detail', args=[str(instance.pk)]))
class UpdateGroup(UpdateView):
model = Group
form_class = EditGroupForm
template_name = 'update_group.html'
def form_valid(self, form):
instance = form.save()
account = self.request.user.account
send_mail (
f"Thanks for updating {instance.name}",
'update group',
NOTIFICATION_EMAIL,
[account.user.email],
fail_silently=False
)
return HttpResponseRedirect(reverse('group_detail', args=[str(instance.pk)]))
That works, but how do I do it for DeleteView:
class DeleteGroup(DeleteView):
model = Group
template_name = 'delete_group.html'
success_url = reverse_lazy('home')
Is there something like form_valid() for DeleteView? Or does form_valid() work for those views as well if there's a form associated. I assume a view needs a form for form valid and I thought there wasn't a form since I'm just deleting a Group.
Is there something like form_valid() for DeleteView?
As of django-4.0, a DeleteView [Django-doc] uses the FormMixin [Django-doc], and thus has a .form_valid(…) method [Django-doc]. It works with a simple Form, that has no fields, and this is thus only used to simplify the logic, and will let Django validate the CSRF-token, and then delete the object.
Since django-4.0, you thus can use .form_valid(…):
# since Django 4.0
class DeleteGroup(DeleteView):
model = Group
template_name = 'delete_group.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
send_mail (
f'Thanks for deleting{self.object}',
'delete group',
NOTIFICATION_EMAIL,
[self.request.user.email],
fail_silently=False
)
return super().form_valid(form)
Before django-4.0, you can override the .delete(…) method [Django-doc], and send the email, so:
# beforeDjango 4.0
from django.http import HttpResponseRedirect
class DeleteGroup(DeleteView):
model = Group
template_name = 'delete_group.html'
success_url = reverse_lazy('home')
def delete(self, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
send_mail (
f'Thanks for deleting{self.object}',
'delete group',
NOTIFICATION_EMAIL,
[self.request.user.email],
fail_silently=False
)
return HttpResponseRedirect(success_url)
For deleting you send a POST or DELETE request to the view.

Django Initialize Form current user with CreateView

I wanto to display the current user in the form before submitting.
views.py
class PostEncabezadoReporte(LoginRequiredMixin, CreateView):
login_url = '/login/'
redirect_field_name = 'redirect_to'
form_class = PostEncabezadoReporteForm
template_name = "crear_reporte.html"
def form_valid(self, form):
object = form.save(commit=False)
object.user = self.request.user
object.startweek, object.endweek = self.weekdatetimeconverter(
object.semana)
object.folio = self.getfolio(
object.user, object.semana, object.tipo_reporte)
self.validar_unico = self.reporte_unico(
object.user, object.semana, object.cliente)
if self.validar_unico == 0:
object.save()
else:
return self.form_invalid(form)
return super(PostEncabezadoReporte, self).form_valid(form)
forms.py
class PostEncabezadoReporteForm(forms.ModelForm):
class Meta:
model = EncabezadoReporte
fields = ('user', 'tipo_reporte', 'tipo_gasto', 'cliente',
'semana', 'folio')
widgets = {'semana': forms.DateInput(attrs={'type': 'week'}),
}
I alreayd tried to override the init in the form and is not working, I can select the user in the field but I want it to be displayed at init.
I have tried to override the init in the form but I had a problem, I was missing a line after the super, this is an example of another form init that I did:
def __init__(self, *args, **kwargs):
self.carro = kwargs.pop('encabezado')
super(AgregarGastoReporte, self).__init__(*args, **kwargs)
self.fields['encabezado'].initial = self.carro

django model form edit automatically

I have a little question :)
I want to add/edit user directly with django model. I did that :
class AddClientView(generic.FormView):
success_url = 'manager/liste'
form_class = AddClientForm
template_name = 'Manager/Clients/formClient.html'
def get_context_data(self, **kwargs):
retour = super(AddClientView, self).get_context_data()
retour['forms'] = AddClientForm
return retour
def form_valid(self, form):
retour = super(AddClientView, self).form_valid(form)
form.save()
return retour
class EditClientView(generic.FormView):
success_url = '/manager/liste'
form_class = AddClientForm
template_name = 'Manager/Clients/formClient.html'
def get_context_data(self, **kwargs):
retour = super(EditClientView, self).get_context_data()
client = Clients.objects.get(id=self.kwargs["client"])
retour['forms'] = AddClientForm(instance=client)
retour['client'] = client
return retour
def form_valid(self, form):
retour = super(EditClientView, self).form_valid(form)
a = Clients.objects.get(id=self.kwargs['client'])
a.prenom = form.cleaned_data['prenom']
a.nom = form.cleaned_data['nom']
a.telephone = form.cleaned_data['telephone']
a.mail = form.cleaned_data['mail']
a.adresse = form.cleaned_data['adresse']
a.date_anniversaire = form.cleaned_data['date_anniversaire']
a.save()
for pConseomme in form.cleaned_data['pConsomme']:
a.pConsomme.add(pConseomme)
for pInteret in form.cleaned_data['pInteret']:
a.pInteret.add(pInteret)
return retour
For edit, i want to do the same as add, like that :
just a
form.save()
But it does not work ... it creates a new user. How i can do that ?
Thanks guys !
You can do the same for the edit but consider adding a new user and updating a user is not the same thing. When you add it creates a new user but when you edit you should first find the specific user and change its data and later you can save the model.
user= get_object_or_404(User, pk=form.cleaned_data['user'].pk)
You can youse get_object_or_404() to find the user according to its pk and the do the same procedure you did on add.

when a condition satisfied redirect to one page if failed redirect to another page using success url in class based views

when the if condition is valid then i want to redirect the page to success.html page and if not valid redirect to faild.html page.How can it possible using class based views.
class LogView(FormView):
form_class = LogForm
template_name = 'log.html'
success_url='failed'
def get_success_url(self):
if not self.success_url:
raise ImproperlyConfigured("No URL to redirect
to.Provide a success_url.")
return str(self.success_url)
def form_valid(self,form):
cc=''
nam1 = self.request.POST.get('nam')
roll1 = self.request.POST.get('roll')
obj=Register.objects.all()
for i in obj:
if str(i.name) == str(nam1) and str(i.rollno) == str(roll1):
else:
pass
else:
pass
You can use form_valid and form_invalid method for this:
class LogView(FormView):
form_class = LogForm
template_name = 'log.html'
success_url='failed'
def form_valid(self, form):
"""
If the form is valid, redirect to the supplied URL.
"""
nam1 = self.request.POST.get('nam')
roll1 = self.request.POST.get('roll')
obj=Register.objects.filter(name=nam1, rollno=roll1).exists()
if obj:
return HttpResponseRedirect(self.get_success_url())
else:
return HttpResponseRedirect('failed')
def form_invalid(self, form):
"""
If the form is invalid
"""
return HttpResponseRedirect('some_invalid_url')
class LogView(FormView):
form_class = LogForm
template_name = 'log.html'
success_url='success'
def form_valid(self, form):
nam1 = self.request.POST.get('nam')
roll1 = self.request.POST.get('roll')
obj=Register.objects.filter(name=nam1, rollno=roll1).exists()
if (obj==True):
return HttpResponseRedirect(self.get_success_url())
else:
return HttpResponseRedirect('failed')

Django form - key error

I have a form implemented in a ListView. The form is used for editing existing items. However I get a key error when i try to submit the form:
File "C:\Users\John\Desktop\website\app\views.py", line 124, in form_valid
id = self.kwargs['id']
KeyError: 'id'
[14/Dec/2016 21:42:09] "POST /car/ HTTP/1.1" 500 99346
This is the main code:
class CarListFormView(FormView):
form_class = CarListForm
def form_valid(self, form):
id = self.kwargs['id']
obj = Car.objects.get(pk=id)
form = CarListForm(instance=obj)
car = form.save(commit=False)
if self.request.user.is_staff:
car.agency = Agency.objects.get(agency_id=9000)
else:
car.agency = self.request.user.agency
car.save()
return redirect('car_list')
What causes this key error?
Thanks!
id is not in your kwargs, that is causing the KeyError. In fact, you don't need to load the car like that. Your method can be simplified to this:
from django.views.generic import UpdateView
class CarListFormView(UpdateView):
model = Car
form_class = CarListForm
template_name = 'something/car_form.html'
def form_valid(self, form):
car = form.save(commit=False)
if self.request.user.is_staff:
car.agency = Agency.objects.get(agency_id=9000)
else:
car.agency = self.request.user.agency
car.save()
return redirect('car_list')