blechreiz-website/musicians/views.py

104 lines
3.3 KiB
Python

from django.views.generic.edit import UpdateView
from django.views.generic import ListView
from musicians.models import Musician
from django import forms
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
class MusicianList( ListView):
model = Musician
class UserEditForm(forms.ModelForm):
first_name = forms.CharField( max_length = 60)
last_name = forms.CharField( max_length = 60)
email = forms.EmailField()
def __init__(self, *args, **kw):
if 'instance' in kw.keys():
user = kw['instance'].user
initVals = { 'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email }
if not 'initial' in kw.keys():
kw['initial'] = initVals
else:
kw['initial'].update(initVals)
super(UserEditForm, self).__init__(*args, **kw)
self.helper = FormHelper()
self.helper.form_id = 'id-exampleForm'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.form_action = '/musicians/martin' # TODO
self.helper.add_input(Submit('submit', 'Submit'))
self.helper.form_class = 'form-horizontal'
#self.helper.layout = Layout(
# Fieldset(
# 'Edit User',
# 'first_name',
# 'last_name',
# 'birthday',
# ),
#)
self.fields.keyOrder.remove('first_name')
self.fields.keyOrder.remove('last_name')
self.fields.keyOrder.remove('email')
self.fields.keyOrder.insert(0, 'first_name')
self.fields.keyOrder.insert(1, 'last_name')
self.fields.keyOrder.insert(2, 'email')
def save(self):
if self.is_valid():
super(UserEditForm,self).save()
self.instance.user.first_name = self.cleaned_data['first_name']
self.instance.user.last_name = self.cleaned_data['last_name']
self.instance.user.email = self.cleaned_data['email']
self.instance.user.save()
class Meta:
model = Musician
exclude = [ 'user','image' ]
#fields = '__all__'
def user_edit( request, username ):
musician = get_object_or_404(Musician, user__username=username )
if request.method == 'POST': # If the form has been submitted...
form = UserEditForm(request.POST) # A form bound to the POST data
form.instance = musician
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/musicians/' + username) # Redirect after POST
else:
form = UserEditForm( instance= musician )
return render(request, 'musicians/musician_edit.html', { 'form': form, } )
class MusicianUpdate( UpdateView ):
model = Musician
#fields = []
template_name = "musicians/musician_edit.html"
success_url = '/books/'