django model form edit automatically - django

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.

Related

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

success message is not working with create view

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)

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 How to submit and handle form data in class based views

Can anybody tell me how to handle form submit and fields using class based views.
Here is my views.py
class ProfileView(FormView):
template_name='profile.html'
form_class = UnregisterMealForm
context={}
#method_decorator(login_required)
def form_valid(self, form):
return HttpResponse("You have succesfully unregistered for the meal")
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def dispatch(self,*args, **kwargs ):
if self.request.user.is_active:
context = super(ProfileView, self).dispatch( self.request, *args, **kwargs)
return context
else:
return HttpResponseRedirect('%s?next=%s' % (settings.LOGIN_URL, self.request.path))
def get_context_data( self, **kwargs):
form=UnregisterMealForm(self.request.POST)
meals = ['breakfast','lunch','dinner']
context = {'meals' : meals , 'unregisterform': form}
if form.is_valid():
select_date = request.POST['select_date']
select_meal = request.POST['meal']
context['recent'] = "You have succesfully unregistered for "+ select_meal +" on " + select_date
return context
When I submit the form, it shows an error Attribute Error 'UnregisterMealForm' object has no attribute 'user'
Here is my UnregisterMealForm
class UnregisterMealForm(forms.Form):
MEALS = [('breakfast','breakfast'),('lunch','lunch'), ('dinner','dinner')]
select_date = forms.DateField(widget=DateInput())
meal = forms.CharField(widget=forms.Select(choices=MEALS, attrs={'class':'form-control', 'placehoder':'Choose the Meal' }))
Can anybody help me with this. If you need more information please tell me.
Thanks in advance.
I m a novice in django.
You can save object in your form_valid method:
def form_valid(self, form):
model = YourModel()
model.select_date = form.cleaned_data['select_date']
model.select_meal = form.cleaned_data['meal']
model.save()
messages.success(request, "Your message here")

ListView with Form in Django

I'm new to django framework developers, and I have read a lot of documentation of Class-Based View and Forms.
Now, I want to create a single page (for test purpose) that contains a list of cars and a Forms, at the bottom page, for create a new Car.
this is my views.py
class IndexView(ListView):
template_name = "index.html"
context_object_name = "cars"
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context["form"] = CarForm
return context
def get_queryset(self):
self.brand = self.kwargs.pop("brand","")
if self.brand != "":
return Car.objects.filter(brand__iexact = self.brand)
else:
return Car.objects.all()
def post(self, request):
newCar = CarForm(request.POST)
if newCar.is_valid():
newCar.save()
return HttpResponseRedirect("")
else:
return render(request, "index.html", {"form": newCar})
class CarForm(ModelForm):
class Meta:
model = Car
delete = True
and this is a picture with what I want create.
image
My questions are:
1) this is a "Best-Pratice" for this purpose?
2) The {{ car.name.errors }} in my template are always blank (no validation error shows).
Thanks! … and sorry for my english.
You could go other way around. Create a FormView and put the list of cars in context. That way form handling becomes easier. Like this -
class CarForm(ModelForm):
class Meta:
model = Car
delete = True
class IndexView(FormView):
template_name = "index.html"
form_class = CarForm
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
# Pass the list of cars in context so that you can access it in template
context["cars"] = self.get_queryset()
return context
def get_queryset(self):
self.brand = self.kwargs.pop("brand","")
if self.brand != "":
return Car.objects.filter(brand__iexact = self.brand)
else:
return Car.objects.all()
def form_valid(self, form):
# Do what you'd do if form is valid
return super(IndexView, self).form_valid(form)