how to merge two views functions with minor differences - django

I just wrote two view functions for two different models but they are very similar and only different in some names. what is the best way to merge these two view functions to prevent code repetition?
these are the view functions:
def manager_scientific(request, *args, **kwargs):
context = {}
if request.user.role == 'manager':
template = loader.get_template('reg/scientific-manager-dashboard.html')
users = User.objects.filter(role='applicant', isPreRegistered=True, scientificinfo__is_interviewed=True).order_by('-date_joined')
approved = ScientificInfo.objects.filter(is_approved__exact='0').all()
context['users'] = users
context['all_users'] = len(users)
context['approved'] = len(approved)
context['survey_choices'] = SURVEY_CHOICES
if request.GET.get('user', 'all') == 'all':
users = users
if request.GET.get('user', 'all') == 'new':
users = users.filter(scientificinfo__is_approved__exact='0')
field_list = request.GET.getlist('field')
if field_list:
if 'None' in field_list:
users = users.filter(fields__title=None) | users.filter(fields__title__in=field_list)
else:
users = users.filter(fields__title__in=field_list)
gender_list = request.GET.getlist('gender')
if gender_list:
users = users.filter(gender__in=gender_list)
education_list = request.GET.getlist('education')
if education_list:
users = users.filter(educationalinfo__grade__in=education_list)
work_list = request.GET.getlist('work')
if work_list:
users = users.filter(workinfo__position__in=work_list)
province_list = request.GET.getlist('province')
if province_list:
if 'None' in province_list:
users = users.filter(prevaddress__address_province__in=province_list) | users.filter(
prevaddress__address_province=None)
else:
users = users.filter(prevaddress__address_province__in=province_list)
query_string = request.GET.get('query_string')
if query_string:
name_query = None
for term in query_string.split():
if name_query:
name_query = name_query & (Q(first_name__contains=term) | Q(last_name__contains=term))
else:
name_query = Q(first_name__contains=term) | Q(last_name__contains=term)
users = users.filter(name_query |
Q(educationalinfo__field__contains=query_string) |
Q(educationalinfo__tendency__contains=query_string) |
Q(educationalinfo__university_name__contains=query_string) |
Q(workinfo__organization__contains=query_string) |
Q(ngoinfo__ngo_name__contains=query_string) |
Q(melli_code__contains=query_string))
users = users.distinct()
context['grade_choices'] = []
for g, grade in EDUCATIONAL_GRADE_CHOICES:
count = EducationalInfo.objects.filter(user__in=users, grade=g).count()
context['grade_choices'].append((g, grade, count))
context['work_position_choices'] = []
for p, position in WORK_POSITION_CHOICES:
count = WorkInfo.objects.filter(user__in=users, position=p).count()
context['work_position_choices'].append((p, position, count))
provinces = users.values_list('prevaddress__address_province')
provinces = Counter([d[0] for d in provinces])
context['provinces'] = provinces.items()
paginator = Paginator(users, 25) # Show 25 contacts per page.
page_number = request.GET.get('page', 1)
page_obj = paginator.get_page(page_number)
context['users'] = page_obj
context['is_interviewed'] = ScientificInfo.objects.filter(is_approved__exact='0', user__is_staff=False).count()
context['not_interviewed'] = ScientificInfo.objects.filter(is_interviewed=True, user__is_staff=False).count()
context['men'] = users.filter(gender="male").count()
context['women'] = users.filter(gender="female").count()
context['query_string'] = query_string
return HttpResponse(template.render(request=request, context=context))
and the other one:
def manager_religious(request, *args, **kwargs):
context = {}
if request.user.role == 'manager':
template = loader.get_template('reg/religious-manager-dashboard.html')
users = User.objects.filter(role='applicant', isPreRegistered=True, religiousinfo__is_interviewed=True).order_by('-date_joined')
approved = ReligiousInfo.objects.filter(is_approved__exact='0').all()
context['users'] = users
context['all_users'] = len(users)
context['approved'] = len(approved)
context['survey_choices'] = SURVEY_CHOICES
if request.GET.get('user', 'all') == 'all':
users = users
if request.GET.get('user', 'all') == 'new':
users = users.filter(religiousinfo__is_approved__exact='0')
field_list = request.GET.getlist('field')
if field_list:
if 'None' in field_list:
users = users.filter(fields__title=None) | users.filter(fields__title__in=field_list)
else:
users = users.filter(fields__title__in=field_list)
gender_list = request.GET.getlist('gender')
if gender_list:
users = users.filter(gender__in=gender_list)
education_list = request.GET.getlist('education')
if education_list:
users = users.filter(educationalinfo__grade__in=education_list)
work_list = request.GET.getlist('work')
if work_list:
users = users.filter(workinfo__position__in=work_list)
province_list = request.GET.getlist('province')
if province_list:
if 'None' in province_list:
users = users.filter(prevaddress__address_province__in=province_list) | users.filter(
prevaddress__address_province=None)
else:
users = users.filter(prevaddress__address_province__in=province_list)
query_string = request.GET.get('query_string')
if query_string:
name_query = None
for term in query_string.split():
if name_query:
name_query = name_query & (Q(first_name__contains=term) | Q(last_name__contains=term))
else:
name_query = Q(first_name__contains=term) | Q(last_name__contains=term)
users = users.filter(name_query |
Q(educationalinfo__field__contains=query_string) |
Q(educationalinfo__tendency__contains=query_string) |
Q(educationalinfo__university_name__contains=query_string) |
Q(workinfo__organization__contains=query_string) |
Q(ngoinfo__ngo_name__contains=query_string) |
Q(melli_code__contains=query_string))
users = users.distinct()
context['grade_choices'] = []
for g, grade in EDUCATIONAL_GRADE_CHOICES:
count = EducationalInfo.objects.filter(user__in=users, grade=g).count()
context['grade_choices'].append((g, grade, count))
context['work_position_choices'] = []
for p, position in WORK_POSITION_CHOICES:
count = WorkInfo.objects.filter(user__in=users, position=p).count()
context['work_position_choices'].append((p, position, count))
provinces = users.values_list('prevaddress__address_province')
provinces = Counter([d[0] for d in provinces])
context['provinces'] = provinces.items()
paginator = Paginator(users, 25) # Show 25 contacts per page.
page_number = request.GET.get('page', 1)
page_obj = paginator.get_page(page_number)
context['users'] = page_obj
context['is_interviewed'] = ReligiousInfo.objects.filter(is_approved__exact='0', user__is_staff=False).count()
context['not_interviewed'] = ReligiousInfo.objects.filter(is_interviewed=True, user__is_staff=False).count()
context['men'] = users.filter(gender="male").count()
context['women'] = users.filter(gender="female").count()
context['query_string'] = query_string
return HttpResponse(template.render(request=request, context=context))
the only differences are in model names and template addresses.
and also how can I rewrite them in a class based format?

You can create one common class that inherits from View Class and then two separate classes that inherit from the previous one. e.g
class ManagerView(View)
template_name = None
model = None
def get(self, request):
...
template = loader.get_template(self.template_name)
approved = self.model.objects.filter(is_approved__exact='0').all()
...
class ManagerReligiousView(ManagerView)
template_name = 'reg/religious-manager-dashboard.html'
model = ReligiousInfo
class ManagerScientificView(ManagerView)
template_name ='reg/scientific-manager-dashboard.html'
model = ScientificInfo

Another way with a class-based view is to emply the rarely-used ability to pass configuration options to it in the url.
class SomeView( AnyClassBasedView):
foo = 'bar'
In urls.py
path( '/do_bar/<int:pk>', SomeView.as_view(), name='do_bar'),
path( '/do_baz/<int:pk>', SomeView.as_view( foo='baz'), name='do_baz'),
And in SomeView, conditional tests on self.foo. Note, you have to declare any such parameter with a default value in the class definition before you can use it in urls.py.
A variant is to use write a view that can handle >1 method of accessing an object by interrogating self.kwargs
path( '/x/<int:pk>', X_View.as_view(), name='x_by_pk'),
path( '/x/<str:order_number>', X_View.as_view(), name='x_by_order'),
where typically the get_object method is subclassed:
class X_View( DetailView):
...
def get_object( self, queryset=None):
if 'pk' in self.kwargs:
obj = get_object_or_404( X, pk=self.kwargs['pk'] )
elif 'order_number' in self.kwargs:
obj = get_object_or_404( X, order_number=self.kwargs['order_number'] )
...
else:
raise ConfigurationError( 'Check urls.py. No valid kwarg was parsed')
return obj
NB this is a simplified get_object which ignores queryset. See the code of get_object for a better template to slot this pattern into. Classy CBVs to the rescue.

Related

select filtering and removal if they are already present in the db

look at the picture before answering me.
that group2 is inside saved in the db with the button I open a modal that allows me to save other groups in the db and I would like that the same groups no longer appear in that select if I have already added them
form.py
class EserciziForm(forms.ModelForm):
class Meta:
model = models.DatiEsercizi
exclude = ['gruppo_single']
#fields = '__all__'
class GruppiForm(forms.ModelForm):
class Meta:
model = models.DatiGruppi
exclude = ['gruppi_scheda']
views.py
def creazione(request, nome):
scheda = get_object_or_404(Schede, nome_scheda = nome)
eserciziFormSet = formset_factory(EserciziForm, extra = 0)
if request.method == "POST":
gruppo_form = GruppiForm(request.POST, prefix = 'gruppo')
if gruppo_form.is_valid():
gruppo = gruppo_form.save(commit = False)
gruppo.gruppi_scheda = scheda
gruppoName = gruppo_form.cleaned_data['dati_gruppo']
gruppo.save()
esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi')
for esercizi in esercizi_formset:
esercizi_instance = esercizi.save(commit = False)
esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName)
esercizi_instance.save()
return HttpResponseRedirect(request.path_info)
else:
gruppo_form = GruppiForm(prefix = 'gruppo')
esercizi_formset = eserciziFormSet(prefix='esercizi')
context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset}
return render(request, 'crea/passo2.html', context
models.py
class DatiGruppi(models.Model):
giorni_settimana_scelta = [
("LUNEDI","Lunedì"),
("MARTEDI","Martedì"),
("MERCOLEDI","Mercoledì"),
("GIOVEDI","Giovedì"),
("VENERDI","Venerdì"),
("SABATO","Sabato"),
("DOMENICA","Domenica")
]
giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-')
dati_gruppo = models.ForeignKey(
Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo')
gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda')
class Schede(models.Model):
nome_scheda = models.CharField(max_length=100)
data_inizio = models.DateField()
data_fine = models.DateField()
utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente')
You can override a form field before instantiate it like this :
views.py
from django import forms
if request.method == "POST":
# Post logic here
else:
# We try to retrieve group that the current user is not yet in.
# Not your logic, but to sum up, you have to retrieve the groups
# which had not yet been added.
# Use a filter that permit you to retrieve only groups which had not yet been added.
group_to_add = Group.objects.filter(...)
GruppiForm.base_fields['group_field'] = forms.ModelChoiceField(
queryset=group_to_add)
# Instantiate the form now
# In this form, the choices are only those contained in the group_to_add queryset
form = GruppiForm(prefix = 'gruppo')

How to chain a multi-feature search in Django

I have a 3 filter search for a job. One is for the job title/decription/company, one for job category for e.g Banking and one for the location for e.g New York
How do I chain the query such that it should render me the appropriate results if I specified any one filter and if I specified all 3 it should perform an AND. I tried doing it with if else, but it is becoming too long. Is there another way?
Here is my code:
views.py
if request.method == "POST":
internship_desc = request.POST['internship_desc']
internship_ind = request.POST['internship_industry']
internship_loc = request.POST['internship_location']
results = []
if internship_desc != "" and internship_desc is not None:
query_results = Internship.objects.filter(
Q(internship_title__icontains=internship_desc) |
Q(internship_desc__icontains=internship_desc) |
Q(recruiter__company_name__icontains=internship_desc)
)
if internship_ind !="" and internship_ind is not None:
if internship_desc != "" and internship_desc is not None:
query_results = query_results.objects.filter(
industry_type__iexact=internship_ind)
else:
query_results = Internship.objects.filter(industry_type__iexact=internship_ind)
if internship_loc !="" and internship_loc is not None:
if internship_desc != "" and internship_desc is not None and internship_ind !=""
and internship_ind is not None:
query_results = query_results.objects.filter(
industry_type__iexact=internship_ind)
query_results = query_results.objects.filter(
recruiter__company_region__iexact=internship_loc)
I think this is what you are trying to do.
result = Internship.objects.all()
if internship_desc:
result = result.filter(internship_desc__icontains=internship_desc)
if internship_ind:
result = result.filter(industry_type__iexact=internship_ind)
if internship_loc:
result = result.filter(recruiter__company_region__iexact=internship_loc)
Your best bet is using django_filters for these sort of filtering.
import django_filters
class InternshipFilter(django_filters.FilterSet):
company_name = django_filters.CharFilter(
field_name='recruiter__company_name',
lookup_expr='icontains'
)
class Meta:
model = Internship
fields = {
'internship_title': ['icontains'],
'internship_desc': ['icontains'],
}
and pass it to template like this:
context['filter_form'] = InternshipFilter().form
and use it in your view to return the filtered objects:
InternshipFilter(self.request.GET, queryset=Internship.objects.all()).qs
more info here

Follow & unfollow system django

i have follow and unfollow system for my app but when i want that using the if statement html changes from follow to unfollow automatically..
but unfortunately my for loop always gives False in views.py and i don't know what is wrong.
here is my models.py file
class FollowUser(models.Model):
profile = models.ForeignKey(to=Profile, on_delete=models.CASCADE)
Followed_by = models.ForeignKey(to=User, on_delete=models.CASCADE)
def __str__(self):
return "%s" % self.Followed_by
here is my views.py file
class UserListView(ListView):
model = Profile
context_object_name = 'users'
template_name = 'dashboard/user_list.html'
def get_queryset(self):
si = self.request.GET.get("si")
if si == None:
si = ""
profList = Profile.objects.filter(Q(phone__icontains = si) | Q(location__icontains = si) | Q(gender__icontains = si) | Q(organization_name__icontains = si)).order_by("-id");
for p1 in profList:
p1.followed = False
ob = FollowUser.objects.filter(profile=p1, Followed_by=self.request.user.profile.id)
if ob:
p1.followed = True
return profList
Instead of using the user.profile.id to search the user by profile id , you should search by its user only.
ob = FollowUser.objects.filter(profile=p1, Followed_by=self.request.user.profile.id)
try:
ob = FollowUser.objects.filter(profile=p1, Followed_by=self.request.user)

Is there any easy way to get all the inputs in one line?

search = True if (
request.POST.get('name') or request.POST.get('city') or
request.POST.get('email') or request.POST.get('tag') or
request.POST.get('status') or
request.POST.get('source') or
request.POST.get('assigned_to')
) else False
I tried request.POST.get('name',.....etc)
But it is now working. Can i assign all in one place.
Full code of views.py
def lead_list_view(request):
queryset = Lead.objects.all().exclude(status='converted'
).select_related('created_by'
).prefetch_related('tags', 'assigned_to',)
if request.user.role == 'ADMIN' or request.user.is_superuser:
queryset = queryset
else:
queryset = queryset.filter(
Q(assigned_to__in=[request.user]) |
Q(created_by=request.user))
if request.method == 'GET':
context = {}
if request.GET.get('tag', None):
queryset = queryset.filter(tags__in = request.GET.getlist('tag'))
open_leads = queryset.exclude(status='closed')
close_leads = queryset.filter(status='closed')
context["status"] = LEAD_STATUS
context["open_leads"] = open_leads
context["close_leads"] = close_leads
context["per_page"] = request.POST.get('per_page')
context["source"] = LEAD_SOURCE
context["users"] = User.objects.filter(
is_active=True).order_by('email').values('id', 'email')
tag_ids = list(set(queryset.values_list('tags', flat=True,)))
context["tags"] = Tags.objects.filter(id__in=tag_ids)
return render(request, 'leads.html', context)
if request.method == 'POST':
context = {}
search = True if (
request.POST.get('name') or request.POST.get('city') or
request.POST.get('email') or request.POST.get('tag') or
request.POST.get('status') or
request.POST.get('source') or
request.POST.get('assigned_to')
) else False
context["search"] = search
request_post = request.POST
if request_post:
if request_post.get('name'):
queryset = queryset.filter(
Q(first_name__icontains=request_post.get('name')) or
Q(last_name__icontains=request_post.get('name')))
if request_post.get('city'):
queryset = queryset.filter(
city__icontains=request_post.get('city'))
if request_post.get('email'):
queryset = queryset.filter(
email__icontains=request_post.get('email'))
if request_post.get('status'):
queryset = queryset.filter(status=request_post.get('status'))
if request_post.get('tag'):
queryset = queryset.filter(tags__in=request_post.getlist('tag'))
if request_post.get('source'):
queryset = queryset.filter(source=request_post.get('source'))
if request_post.getlist('assigned_to'):
queryset = queryset.filter(
assigned_to__id__in=request_post.getlist('assigned_to'))
queryset = queryset.distinct()
open_leads = queryset.exclude(status='closed')
close_leads = queryset.filter(status='closed')
context["status"] = LEAD_STATUS
context["open_leads"] = open_leads
context["close_leads"] = close_leads
context["per_page"] = request.POST.get('per_page')
context["source"] = LEAD_SOURCE
context["users"] = User.objects.filter(
is_active=True).order_by('email').values('id', 'email')
tag_ids = list(set(queryset.values_list('tags', flat=True,)))
context["tags"] = Tags.objects.filter(id__in=tag_ids)
context["assignedto_list"] = [
int(i) for i in request.POST.getlist('assigned_to', []) if i]
context["request_tags"] = request.POST.getlist('tag')
tab_status = 'Open'
if request.POST.get('tab_status'):
tab_status = request.POST.get('tab_status')
context['tab_status'] = tab_status
return render(request, 'leads.html', context)
# return context
You can do like
inputs = ['name','city','email','tag','status','source','assigned_to']
search = inputs in request.POST.keys() #boolean
To check all input parameters present and have value or satisfy some other check:
inputs = ['name','city','email','tag','status','source','assigned_to']
search = all (bool(request.POST.get(input)) for input in inputs)
bool() check can be replaced with any other required check.
To just check required parameters are present in request, disregarding their value:
inputs = ['name', 'city', 'email', 'tag', 'status', 'source', 'assigned_to']
params = request.POST.keys()
search = all(input in params for input in inputs)
or
inputs = ['name', 'city', 'email', 'tag', 'status', 'source', 'assigned_to']
search = set(inputs).issubset(set(request.POST.keys()))

Django - POST request not retrieved correctly

I'm working on a inventory control in Django and i want a form to control the action that will be made. If a record for the product already exist, it should update the quantity. If it doesn't exist, it should create the record for it. Besides that, one form field will have three choices. One will add the form value to que product quantity, other will subtract and another one will change to the value in the form.
The model is quite big, because i set some choices for the form fields. There it is:
from django.db import models
from django import forms
from django.forms import ModelForm
class Produto(models.Model):
CAMISA = "CM"
QUADRO = "QD"
CANECA = 'CN'
ESCOLHAS_PRODUTO = (
(CAMISA, 'Camisa'),
(QUADRO, 'Quadro'),
(CANECA, 'Caneca'),
)
tipo = models.CharField(max_length = 40,
choices=ESCOLHAS_PRODUTO,
default=CAMISA)
class Camisa(Produto):
MASCULINA = 'MA'
FEMININA_BASICA = 'FB'
FEMININA_GOLA_V = 'FV'
INFANTIL = 'IN'
MODELO_CAMISA = (
(MASCULINA, 'Masculina'),
(FEMININA_BASICA, 'Feminina Basica'),
(FEMININA_GOLA_V, 'Feminina Gola V'),
(INFANTIL, 'Infantil'),
)
modelo = models.CharField(max_length = 50,
choices=MODELO_CAMISA,
)
AMARELA = 'AM'
AZUL_CLARO = 'AC'
AZUL_ESCURO = 'AE'
BRANCA = 'BR'
CINZA = 'CI'
LARANJA = 'LA'
MARFIM = 'MA'
ROSA = 'RO'
PRETA = 'PR'
VERDE_MUSGO = 'VM'
VERMELHA = 'VR'
CORES_CAMISA = (
(AMARELA, 'Amarela'),
(AZUL_CLARO, 'Azul Claro'),
(AZUL_ESCURO, 'Azul Escuro'),
(BRANCA, 'Branca'),
(CINZA, 'Cinza'),
(LARANJA, 'Laranja'),
(MARFIM, 'Marfim'),
(ROSA, 'Rosa'),
(PRETA, 'Preta'),
(VERDE_MUSGO, 'Verde Musgo'),
(VERMELHA, 'Vermelha'),
)
cor = models.CharField(max_length = 40,
choices=CORES_CAMISA,
)
TAMANHO_P = 'TP'
TAMANHO_M = 'TM'
TAMANHO_G = 'TG'
TAMANHO_GG = 'GG'
TAMANHO_XG = 'XG'
TAMANHO_02_ANOS = '02'
TAMANHO_04_ANOS = '04'
TAMANHO_06_ANOS = '06'
TAMANHO_08_ANOS = '08'
TAMANHO_10_ANOS = '10'
TAMANHO_12_ANOS = '12'
TAMANHO_14_ANOS = '14'
TAMANHO_CAMISA = (
(TAMANHO_P, 'P'),
(TAMANHO_M, 'M'),
(TAMANHO_G, 'G'),
(TAMANHO_GG, 'GG'),
(TAMANHO_XG, 'XGG'),
(TAMANHO_02_ANOS, '2 Anos'),
(TAMANHO_04_ANOS, '4 Anos'),
(TAMANHO_06_ANOS, '6 Anos'),
(TAMANHO_08_ANOS, '8 Anos'),
(TAMANHO_10_ANOS, '10 Anos'),
(TAMANHO_12_ANOS, '12 Anos'),
(TAMANHO_14_ANOS, '14 Anos'),
)
tamanho= models.CharField(max_length = 50,
choices=TAMANHO_CAMISA,
)
quantidade = models.IntegerField()
def __unicode__(self):
return self.modelo
class CamisaForm(ModelForm):
ADICIONAR = 'ADC'
REDUZIR = 'RED'
ALTERAR = 'ALT'
ACOES = (
(ADICIONAR, 'Adicionar Quantidade'),
(REDUZIR, 'Reduzir Quantidade'),
(ALTERAR, 'Alterar para Quantidade'),
)
acoes = forms.ChoiceField(
choices=ACOES,
)
class Meta:
model = Camisa
And the following view:
def index(request):
produtos_estoque = Camisa.objects.all()
template = 'estoque/index.html'
modelos_camisa = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo = request.POST['modelo'], cor = request.POST['cor'], tamanho = request.POST['tamanho'])
if request.POST['acoes'] == 'ADC':
produto_atualizar.quantidade = produto_atualizar.quantidade + request.POST['quantidade']
elif request.POST['acoes'] == 'RED':
produto_atualizar.quantidade = produto_atualizar.quantidade - request.POST['quantidade']
elif request.POST['acoes'] == 'ALT':
produto_atualizar.quantidade = request.POST['quantidade']
produto_atualizar.save()
except:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response(template, { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : modelos_camisa.iteritems(), }, context_instance=RequestContext(request))
But what is happening is that the form is just creating another record for the product, even if it already exists. Not sure if the rest of the model is important for this question, will post it if necessary. Can somebody help me on this one? Thanks
Please post the Model this is acting on - it will have some useful information, like constraints or lack thereof etc. OK cool, no unique constraints in there causing insert violations.
First thing I would recommend is using the forms cleaned_data to access form values instead of the raw POST data, form.is_valid() does a lot of work to process the raw data into acceptable inputs for Model data.
Second thing is that except clause will catch ANY exception which I suspect is your problem... Something else is going wrong which is creating the new record in the except clause. Be specific, like except Camisa.DoesNotExist:
Third thing is to put those constants on the Model so you can reference them from the Form and View instead of literal strings. This is just a cleanliness / code style recommendation.
A little cleanup might look like:
MODELOS_CAMISA = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
def index(request):
produtos_estoque = Camisa.objects.all()
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo=form.cleaned_data.get('modelo'), cor=form.cleaned_data.get('cor'), tamanho=form.cleaned_data.get('tamanho'))
quantidade = form.cleaned_data.get('quantidade')
acoes = form.cleaned_data.get('acoes')
if acoes == Camisa.ADC:
produto_atualizar.quantidade = produto_atualizar.quantidade + quantidade
elif acoes == Camisa.RED:
produto_atualizar.quantidade = produto_atualizar.quantidade - quantidade
elif acoes == Camisa.ALT:
produto_atualizar.quantidade = quantidade
produto_atualizar.save()
except Camisa.DoesNotExist:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response('estoque/index.html', { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : MODELOS_CAMISA.iteritems(), }, context_instance=RequestContext(request))
(Sorry for any grammatical errors, my Portuguese is not great)
That should be enough to get you started, if you add more information I can edit and elaborate my answer. Good luck!