Get data from django database - django

So,how get data from django database?I have django models and created 2 objects there.I want to get 2 objects and write in html file. admin panel: https://i.stack.imgur.com/7WUZr.png
view.py
def vds(request):
HTML_STRING = render_to_string("vds.html", context=context1)
return HttpResponse(HTML_STRING)
VDSTARIFS_obj = VDSTARIFS.objects.get(id=1)
context1 = {
"prise": VDSTARIFS_obj.prise,
}
file with models
class VDSTARIFS( models.Model):
prise = models.CharField(max_length= 10,)
def __str__(self):
return str(self.prise)```

Referring to the Django docs:
https://docs.djangoproject.com/en/3.2/intro/tutorial03/#a-shortcut-render
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
Edited for your model
from django.shortcuts import render
from .models import VDSTARIFS
def vds(request):
ALL_VDSTARIFS = VDSTARIFS.objects.all()
FIRST_VDSTARIF = ALL_VDSTARIFS[:1]
# Get prise
prise = FIRST_VDSTARIF.prise
# Alternatives to print 'prise' in template
# Pass only the first item of vds list
context = {
"FIRST_VDSTARIF": FIRST_VDSTARIF
}
# Pass prise only
context = {
"prise": prise
}
# All records in html also the needed one in separated item
context = {
"ALL_VDSTARIFS": VDSTARIFS,
"FIRST_VDSTARIF": FIRST_VDSTARIF
}
return render(request, 'vds.html', context)
}
In template you can use if
https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#if
{# Runs along all tarifs and print only one, not good. #}
{% for vdstarif in ALL_VDSTARIFS %}
{% if vdstarifs.id == "1" %}
{{ vdstarif.prise }}
{% endif %}
{% endfor %}
{# Only print the needed one #}
{{ FIRST_VDSTARIF.prise }}
{# Print prise #}
{{ prise }}
You might follow python and django coding conventions and my suggestions.
Rename VDSTARIFS -> VdsTarif (look at your admin page, Django adds 's' to your model to make it plural)
Use singular names for your models and add a suffix to variable names in views like vdstarif_list.
For "prise" field use DecimalField, looks like it is a CharField. Is it prise or price?
https://docs.djangoproject.com/en/3.2/ref/models/fields/#decimalfield
from django.shortcuts import render
from .models import VdsTarif
def vds(request):
vdstarif_list = VdsTarif.objects.all()
context = {
"vdstarif_list" : vfstarif_list[:0].prise
}
return render(request, 'vds.html', context)

Related

Dynamically Add or Remove WTForms validators in Flask

Is there a way to do this?
Below is an example of what I'm trying to do:
class TestForm(FlaskForm):
email = EmailField('Email', validators=[InputRequired('Email is required.')])
start = SubmitField()
Then in a route:
del form.email.validators
# I also tried:
form.email.validators.remove
Basically I want to use stored data to determine if the field should be required or not for a predefined form.
Dynamically create an internal subclasses of the form within your view. Remove any validators from the fields of the internal subclass and then instance a form from the internal subclass. In code, something like:
Define a form, the first_name field has two validators.
class TestForm(FlaskForm):
first_name = StringField(validators=[InputRequired(), Length(8)])
submit = SubmitField()
In your view:
# Dynamic subclass
class F(TestForm):
pass
# Remove the length validator.
# Validators are in a dict called kwargs
validators = F.first_name.kwargs.get('validators')
for validator in validators:
if isinstance(validator, Length):
validators.remove(validator)
# instance a form
_form = F()
# use the form ....
Single file example app.py:
from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import InputRequired, Length
app = Flask(__name__)
app.config['SECRET_KEY'] = '13332311ecd738748f27a992b6189d3f5f30852345a1d5261e3e9d5a96722fb9'
class TestForm(FlaskForm):
first_name = StringField(validators=[InputRequired(), Length(8)])
submit = SubmitField()
html_template = '''
{% if form.first_name.errors %}
<ul class="errors">
{% for error in form.first_name.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form role="form" method="post" action="" name="Form1">
{{ form.hidden_tag() }}
{{ form.first_name }}
{{ form.submit() }}
</form>
'''
success_template = '''
<h1>Success</h1>
'''
#app.route('/', methods=['GET', 'POST'])
def index():
# Dynamic subclass
class F(TestForm):
pass
# Remove the length validator.
# Validators are in a dict called kwargs
validators = F.first_name.kwargs.get('validators')
for validator in validators:
if isinstance(validator, Length):
validators.remove(validator)
# instance a form
_form = F()
# print the validators
for field in _form:
print(f"Field: {field.name} has {len(field.validators)} validator(s)")
for validator in field.validators:
print(validator)
if _form.validate_on_submit():
print('Validation passed')
return render_template_string(success_template)
return render_template_string(html_template, form=_form)
if __name__ == '__main__':
app.run()
You can try:
form.email.validators = ()
This worked well for me.
You can also add back the validators with:
form.email.validators = [InputRequired('Email is required')]

DJANGO 2.0 Displaying Data from the database

i am new to django and i am unable to get to print to the html page.How do you display the information retrieved from the database into a blank html page?
blank.hml
<body>
<h1>Classes Added</h1>
{% for i in classInfo %}
<h1>{{ i.label }}</h1>
{% endfor %}
</body>
models.py
class EventType(models.Model):
'''
Simple ``Event`` classifcation.
'''
objects = models.Manager()
abbr = models.CharField(_('abbreviation'), max_length=4, unique=False)
label = models.CharField(_('label'), max_length=50)
class Meta:
verbose_name = _('event type')
verbose_name_plural = _('event types')
def __str__(self):
return self.label
views.py
def displayClass(TemplateView):
templateName = 'blank.html'
def get(self,request):
form = ClassCreationForm()
classInfo = EventType.objects.all()
print(classInfo)
args = {'form' : form, 'classInfo' : classInfo}
return render(request,self,templateName,{'form':form})
forms.py
class ClassCreationForm(forms.Form):
classroom = forms.CharField(label = 'Class Name',max_length=50)
I think you need to understand how the views.py file works. You should have your business logic included in there and the pass it along to the template to be rendered. It can be passed along by the return feature you have included in your code. Although, in your return feature you are only passing a templatename and the form you wanted to render. There isn't data related to the EventType queryset being passed to your template as it is not included in the return context.
Now, personally I like working with Django Class-Based-generic-Views (CBV), since a lot of the code is included in there for you. I am not sure if you have got to the point of learning these yet but I would check them out.
If you would like to add a form into this, you could do so by adding FormMixin which is part of the generic mixins Django provides.
How I would structure your view.py code using generic views is as follows:
from django.views import generic
from django.views.generic.edit import FormMixin
from YourApp.forms import ClassCreationForm
from YourApp.models import EventType
class DisplayClass(FormMixin,generic.ListView):
template_name = 'blank.html'
form_class = ClassCreationForm
def get_queryset(self, *args, **kwargs):
return EventType.objects.all()
If you decide to use class based views you will need to add additional criteria to your urls.py file (the .as_view()):
from django.urls import path
from . import views
urlpatterns = [
path('yoururlpath/', views.DisplayClass.as_view()),
]
Then in your template:
{% for i in object_list %}
<h1>{{ i.label }}</h1>
{% endfor %}
rendering your form...
{{ form.as_p }}

How to use django smart-selects with modelform?

I'm using smart-selects.
Edited : Here is the code that works for me, after adding {{ form.media.js }} in the template , thanks to #Evangelos
models.py :
from django.db import models
from smart_selects.db_fields import ChainedForeignKey, ChainedManyToManyField
class ChoixTangente(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class ChoixModele(models.Model):
name = models.CharField(max_length=255)
tangentes = models.ManyToManyField('Choixtangente', blank=True)
def __str__(self):
return self.name
class TypeModele(models.Model):
tangente = models.ForeignKey(ChoixTangente, blank=True, null=True)
type_modele = ChainedForeignKey(
ChoixModele,
chained_field="tangente",
chained_model_field="tangentes",
show_all=False,
auto_choose=True,
blank=True, null=True
)
def __unicode__(self):
return str(self.pk)
form.py :
from django import forms
from .models import ChoixTangente, ChoixModele, TypeModele
class TypeModeleForm(forms.ModelForm):
class Meta:
model = TypeModele
fields = ('tangente', 'type_modele')
views.py
from .models import ChoixTangente, ChoixModele, TypeModele
from .forms import TypeModeleForm
def type_modele_new(request):
if request.method == "POST":
form = TypeModeleForm(request.POST)
if form.is_valid():
modele_instance = form.save()
return redirect('calculs.views.type_modele_detail', pk=modele_instance.pk)
else:
form = TypeModeleForm()
return render(request, 'calculs/type_modele_new.html', {'form': form})
def type_modele_detail(request, pk):
modele_instance = get_object_or_404(TypeModele, pk=pk)
return render(request, 'calculs/type_modele_detail.html', {'modele_instance': modele_instance})
template : type_modele_new.html
{% load staticfiles %}
<form method="POST">
{% csrf_token %}
**{{ form.media.js }}**
{{ form.as_p}}
<input type="submit" value="Submit">
</form>
urls.py
from django.conf.urls import url, include
from . import views
from smart_selects import urls as smart_selects_urls
urlpatterns = [
url(r'^chaining/', include('smart_selects.urls')),
url(r'^type_modele/new/$', views.type_modele_new, name='modele_new'),
url(r'^type_modele/(?P<pk>[0-9]+)/$', views.type_modele_detail, name='modele_detail'),
]
Edited : and here was the problem :
I have it working fine in admin :
I create ChoixTangente instances
I create ChoixModele
instances and select ChoixTangentes instances in the list
I can create TypeModele" instances by selecting "tangente" in a list of ChoixTangente and "type_modele" in the list of corresponding ChoixModele choices resulting from the steps 1) and 2)
see Admin form screenshot
I whish to have my users do the same through a form. But I can't have it working.
the field "Tangente" is populated with the list of ChoixTangente but when I choose a value the field "type_modele" stays empty instead of displaying a list of corresponding choices.
see form screenshot for the users
First of all where is your views?
Try to post more complete question with files for better understanding.
Where is the model Appareil in the models.py you are refering to in forms.py?
And your fields should be in list [].
Your forms.py should look like:
from django import forms
from .models import Modele
class AppareilForm(forms.ModelForm):
class Meta:
model = Modele
fields =['tangente', 'modele']
You don't need to write javascript.
Just remember to include url(r'^chaining/', include('smart_selects.urls')) to your urls.py
in your view call the AppareilForm Read about forms in views for details.
And in the template just use {{form.as_p}} and {{ form.media.js }} before to load javascript and make sure to load static in your template. {% load static % }
Your template should look something like this
{% load static % }
<form action="your url that points to your view" method="POST">
{% csrf_token %}
{{ form.media.js }}
{{ form.as_p}}
<input type="submit" value="Submit">
</form>
Read the django-selects description carefully.

Django: Add & delete extra input field using class view at a click of a button

What I am trying to do is the following: User will have a production (also known as podcast episode) already created with the necessary info until this point (production_id would be the id for this query). The idea is, when user arrives to ChapterMark template, he would be able to create several timestamps to point out certain topics he/she is talking throughout his/her episode. chaptermark_id is created since it would be a One-To-Many and with this id I can add as much timestamps as I want within that episode. With this in mind, which is the best approach for this type of situation and how I can implement it in my form, class view and template?
Thanks in advance
Here is my views.py:
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.views.generic import View, RedirectView, TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms.client_setup import ClientSetupForm
from .forms.podcast_setup import PodcastSetupForm
from .forms.episode_info import EpisodeInfoForm
from .forms.image_files import EpisodeImageFilesForm
from .forms.wordpress_info import EpisodeWordpressInfoForm
from .forms.chapter_marks import EpisodeChapterMarksForm
from .forms.show_links import ShowLinksForm
from .forms.tweetables import TweetablesForm
from .forms.clicktotweet import ClickToTweetForm
from .forms.schedule import ScheduleForm
from .forms.wordpress_account import WordpressAccountForm
from .forms.wordpress_account_setup import WordpressAccountSetupForm
from .forms.wordpress_account_sortable import WordpressAccountSortableForm
from .forms.soundcloud_account import SoundcloudAccountForm
from .forms.twitter_account import TwitterAccountForm
from producer.helpers import get_podfunnel_client_and_podcast_for_user
from producer.helpers.soundcloud_api import SoundcloudAPI
from producer.helpers.twitter import TwitterAPI
from django.conf import settings
from producer.models import Client, Production, ChapterMark, ProductionLink, ProductionTweet, Podcast, WordpressConfig, Credentials, WordPressSortableSection, \
TwitterConfig, SoundcloudConfig
from django.core.urlresolvers import reverse
from producer.tasks.auphonic import update_or_create_preset_for_podcast
class EpisodeChapterMarksView(LoginRequiredMixin, View):
form_class = EpisodeChapterMarksForm
template_name = 'fc/forms_chapter_marks.html'
def get(self, request, *args, **kwargs):
initial_values = {}
user = request.user
# Lets get client and podcast for the user already. if not existent raise 404
client, podcast = get_fc_client_and_podcast_for_user(user)
if client is None or podcast is None:
raise Http404
# The production_id or the chaptermark_id must be passed on teh KWargs
production_id = kwargs.get('production_id', None)
chaptermark_id = kwargs.get('chaptermark_id', None)
if chaptermark_id:
chaptermark = get_object_or_404(ChapterMark, id=chaptermark_id)
production = chaptermark.production
elif production_id:
production = get_object_or_404(Production, id=production_id)
chaptermark = None
initial_values['production_id'] = production.id
if chaptermark is not None:
initial_values['chaptermark_id'] = chaptermark_id
initial_values['start_time'] = chaptermark.start_time
initial_values['title'] = chaptermark.title
form = self.form_class(initial=initial_values)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# lets get the data
production_id = form.cleaned_data.get('production_id')
chaptermark_id = form.cleaned_data.get('chaptermark_id')
start_time = form.cleaned_data.get('start_time')
title = form.cleaned_data.get('title')
# Get production
production = get_object_or_404(Production, id=production_id)
# if a chaptermark existed, we update, if not we create
if chaptermark_id is not None:
chaptermark = ChapterMark.objects.get(id=chaptermark_id)
else:
chaptermark = ChapterMark()
chaptermark.start_time = start_time
chaptermark.title = title
chaptermark.production = production
chaptermark.save()
return HttpResponseRedirect(reverse('fc:episodeshowlinks'))
return render(request, self.template_name, {'form': form})
chaptermark.py form:
from django import forms
class EpisodeChapterMarksForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
chaptermark_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
start_time = forms.TimeField(required=False)
title = forms.CharField(max_length=200)
chaptermark template:
{% extends "fc/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-success active" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%">
<span class="sr-only">50% Complete</span>
</div>
</div>
<div class="panel panel-default box-shadow--16dp col-sm-6 col-sm-offset-3">
<div class="panel-body">
<div class='row'>
<div class='col-sm-12'>
{% if title %}
<h1 class='{% if title_align_center %}text-align-center{% endif %}'>{{ title }}<!-- : {{ get.clientsetup.company_name }} --></h1>
{% endif %}
{% if subtitle %}
<h3 class='{% if subtitle_align_center %}text-align-center{% endif %}'>{{ subtitle }}</h4>
{% endif %}
<h5>Chapter Marks</h5>
<form method='POST' action=''>{% csrf_token %}
{{ form|crispy }}
<hr/>
<button type="submit" class="btn btn-primary box-shadow--6dp"><i class="fa fa-chevron-right pull-right"></i> Continue
</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
----------------------UPDATE-------------------------
Was in views.py:
#login_required
def episodechaptermarks(request):
title = 'Podcast'
title_align_center = True
subtitle = 'Setup | Add Episode'
subtitle_align_center = True
form = ChapterMarksForm(request.POST or None)
context = {
"title": title,
"subtitle": subtitle,
"form": form
}
if form.is_valid():
instance = form.save(commit=False)
start_time = form.cleaned_data.get("start_time")
title = form.cleaned_data.get("title")
instance.start_time = start_time
instance.title = title
instance.user = request.user
instance.save()
return render(request, "pod_funnel/forms_chapter_marks.html", context)
else:
return render(request, "pod_funnel/forms_chapter_marks.html", context)
ModelForm:
from django import forms
from producer.models import ChapterMark
class ChapterMarksForm(forms.ModelForm):
class Meta:
model = ChapterMark
fields = ['start_time', 'title']
def clean_start_time(self):
start_time = self.cleaned_data.get('start_time')
return start_time
def clean_title(self):
title = self.cleaned_data.get('title')
return title
In essence, your production object has a series of timestamps that relate back via a FK. You need a set of views for CRUD at the production level. Let's assume your models are already created. There's a few things from my experience I want to point out that I think will point you in the right direction.
Unless absolutely necessary never use a Form class when creating a form object that mirrors a model; you are introducing a need for unnecessary complexity and opening the door for errors. Use a ModelForm, which can save objects to the DB straight from the view and help you manage cleaning, validation, and more. In addition, these can easily mesh with generic views of all sorts.
For this sort of relation (a model object with a varying number of model objects of a given type relating back that object) Django provides the powerful but difficult inlineformset_factory. This creates a series of inline forms as needed for a relation such as this.
So you have a model (production) and another related back to that (timestamp). You need to save these at the same time, possibly perform cleaning or validation, and really provide CRUD functionality for this relationship as a whole. For this, you could create a complex view from scratch or you could use django-extra-views and their generic CBVs for models with inlines. You can subclass CreateWithInlinesView, UpdateWithInlinesView. Why? Most Django devs would agree formsets are difficult to implement.
So, to give you a simplified version of how you can do this
from extra_views.advanced import CreateWithInlinesView, InlineFormSet, UpdateWithInlinesView
class TimeStampsInline(InlineFormSet):
model = models.TimeStamp
form = TimeStampForm # If you haven't created a custom ModelForm, can also specify "fields= ['field_1','field_2',...] and the CBV will create a ModelForm
extra = 0
class ProductionCreate(CreateWithInlinesView):
model=models.Production
inlines = [TimeStampsInline]
success_url = reverse('production-list') # the url to return to on successful create
exclude = ['created_by'] # render all fields except this in form
template_name = 'myapp/update.html'
class ProductionUpdate(UpdateWithInlinesView):
model=models.Production
inlines = [TimeStampsInline]
success_url = reverse('production-list')
exclude = ['created_by']
template_name = 'myapp/update.html'
Your template(s) will have to be built in specification with formsets; there's documentation and tutorials all over for that.
That's already a lot to digest, but you probably get the general idea. Don't build a horse from scratch ;)

passing value into a custom function? django noob

I have a function, that if i run from django shell, it populates my db succesfully.
I have three classes.
Class League(models.Model):
LeagueName = models.CharField()
#class League explained below
Class Fixture(models.Model):
League = models.ForeignKey(League)
home_team = models.ForeginKey(Team)
away_team = models.ForeginKey(Team)
Class Teams(models.Model):
League = models.ForeignKey(League)
I want the functionality to able to calculate the fixture table with respect to only one league. Here is what I am doing now. which at the moment it is not doing. How to?
class League(models.Model):
LeagueName = models.CharField(max_length=200)
FixturesGenerated = models.BooleanField(default=False)
def __unicode__(self):
return self.LeagueName
def CreateFixtures(self, print_only=True):
if self.FixturesGenerated==True:
return
from dateutil import rrule
from dateutil.relativedelta import *
from League.models import Team, Fixture
import itertools
import datetime
import random
"""
Instead of your array I will use actual objects from the Teams model
"""
teams = Team.objects.all()
fixcombos = list(itertools.combinations(teams,2))
random.shuffle(fixcombos)
nofixtures = len(fixcombos)
datestart = datetime.date.today()
dateend = datestart + datetime.timedelta(days=125)
#calculate possible fixture dates,
fixdays = list(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA,rrule.SU), dtstart=datestart, until=dateend))
nofmatchdays = len(fixdays)
# perday = perday matches, and then moved it into array for for loop of dates available.
perday = nofixtures/nofmatchdays +1
perday = range(0,perday)
#for loop to extend the fixture days array to repeat dates.
for x in perday:
fixdays = fixdays + fixdays
fixarray = range(0, nofixtures)
# for loop for printing the possible functions
# this for loop number will give the database entry id number of a particular name. we still have to do some manipulation.
result = ''
for y in fixarray:
printline = 'Date: ' + str(fixdays[y]) + ': Teams Involved: ' + str(fixcombos[y])
result += printline
# now the print array functionality needs to be replaced with p.save() functionality in the final program.
"""
Code to actually save the fixture if print_only is not True
"""
if not print_only:
f = Fixture()
f.league = self
f.fixture_date = fixdays[y]
f.team_one = fixcombos[y][0]
f.team_two = fixcombos[y][1]
f.save()
self.FixturesGenerated = True
self.save()
[EDIT] To furthur elaborate, here is my admin.py
from League.models import League
from League.models import Team
from League.models import Fixture
from django.contrib import admin
from django.http import HttpResponseRedirect
class ButtonableModelAdmin(admin.ModelAdmin):
buttons=()
def change_view(self, request, object_id, extra_context={}):
extra_context['buttons']=self.buttons
return super(ButtonableModelAdmin, self).change_view(request, object_id, extra_context)
def button_view_dispatcher(self, request, object_id, command):
obj = self.model._default_manager.get(pk=object_id)
return getattr(self, command)(request, obj) \
or HttpResponseRedirect(request.META['HTTP_REFERER'])
def get_urls(self):
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
return patterns('',
*(url(r'^(\d+)/(%s)/$' % but[0], wrap(self.button_view_dispatcher)) for but in self.buttons)
) + super(ButtonableModelAdmin, self).get_urls()
class TeamsInLeague(admin.StackedInline):
model = Team
extra = 1
class FixturesInLeague(admin.TabularInline):
model = Fixture
extra = 0
class LeagueAdmin(ButtonableModelAdmin):
fields = ['LeagueName', 'FixturesGenerated']
inlines = [TeamsInLeague, FixturesInLeague, ]
def gen_fixtures(self, request, obj):
obj.CreateFixtures(print_only=False)
gen_fixtures.short_description = 'Generate Fixtures'
gen_fixtures.url = "gen_fixtures"
buttons = [ (gen_fixtures.func_name, gen_fixtures.short_description) ]
admin.site.register(League,LeagueAdmin)
admin.site.register(Team)
admin.site.register(Fixture)
and here it is from my templates/../change_form.html.
{% extends "admin/change_form.html" %}
{% block object-tools %}
{% if change %}{% if not is_popup %}
<ul class="object-tools">
{% for button in buttons %}
<li>{{ button.1 }}</li>
{% endfor %}
<li>History ala bala</li>
{% if has_absolute_url %}<li>View on site</li>{% endif%}
</ul>
{% endif %}{% endif %}
{% endblock %}
thankyou.
//mouse
My suggestion (after doing my best to understand what you are trying to do) is to make your anchors use a get parameter of your team id.
{% for button in buttons %}
<li>{{ button.1 }}</li>
{% endfor %}
And then in your view you could pull off the team ID from the request and call CreateFixtures.
team = request.get('team_id')
league.CreateFixtures(team, print_only=False)
Thats the best I can do based on the code you pasted. I strongly suggest you rework some of it to be more readable.