Unable to save checkbox data - django

i am really exhausted i didn't find any solution for this till now. I was trying to create a table to view all the data save by the user. The problem is that all the inputs in the models.py are saved excluding the parameters with checkbox. I don't know what is the problem. All these parameters in models.py are saved in the database.
This is my Models.py :
class Parameters(models.Model):
user = models.ForeignKey(User)
title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest")
#input characteristics
price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
stocks_num_2_min = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)])
stocks_num_2_max = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),])
limit_3 = models.FloatField('3. Last price to upper straight, %', default=20, validators=[MinValueValidator(-200),])
learning_days_4_min = models.IntegerField('4. Number of Learning days, min', default=1, validators=[MinValueValidator(1),MaxValueValidator(30)])
learning_days_4_max = models.IntegerField('4. Number of Learning days, max', default=10, validators=[MinValueValidator(1),MaxValueValidator(30)])
evaluation_days_5 = models.IntegerField('5. Number of Evaluation days', default=10, validators=[MinValueValidator(1),MaxValueValidator(10)])
delay_days_6 = models.IntegerField('6. Number of “no quarterly reports” days (N)', default=10, validators=[MinValueValidator(0),MaxValueValidator(20)])
minimum_gain_7 = models.FloatField('7. Minimum gains for winners', default=0, validators=[MinValueValidator(0),MaxValueValidator(100)])
minimum_loss_8 = models.FloatField('8. Minimum losses for losers', default=0, validators=[MinValueValidator(-100),MaxValueValidator(0)])
total_gain_min_9 = models.FloatField('9. Minimum total gain', default=0, validators=[MinValueValidator(0),MaxValueValidator(100)])
winning_stock_percentage_min_10 = models.FloatField('10. Minimum percentage of winning stocks', default=60, validators=[MinValueValidator(0),MaxValueValidator(100)])
#input characteristics
period_start = models.DateField('period, start', default=datetime.date(2013, 9, 25))
period_end = models.DateField('end', default=datetime.datetime.today().date() - datetime.timedelta(days=16))
inital_capital = models.IntegerField('Total initial capital, USD', default=100000, validators=[MinValueValidator(10000),])
fraction_to_invest = models.FloatField('Percentage of the available capital to (re)invest', default=50, validators=[MinValueValidator(10), MaxValueValidator(90)])
minimum_cash = models.IntegerField('Minimum cash to invest, %', default=5, validators=[MinValueValidator(1), MaxValueValidator(50)])
trades_fees = models.FloatField('Trade fees, USD', default=8, validators=[MinValueValidator(0),])
stop_loss = models.FloatField('Stop-Loss, %', default=-2, validators=[MinValueValidator(-50), MaxValueValidator(-1)])
target_gain = models.FloatField('Target gain, %', default=5, validators=[MinValueValidator(1),])
created_at = models.DateTimeField(u'created', auto_now_add=True)
updated_at = models.DateTimeField(u'updated', auto_now=True)
This is the forms.py: All the inputs with multiplechoice field are empty after save
class BacktestForm(forms.ModelForm):
period_start = forms.DateField(initial=datetime.datetime.today().date() - datetime.timedelta(days=365+16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
period_end = forms.DateField(initial=datetime.datetime.today().date() - datetime.timedelta(days=16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
market = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices=MARKET_CHOICES)
sector = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices= MEDIA_CHOICES)
class Meta:
model = Parameters
exclude = [
'user',
'type',
'created_at',
'updated_at',
]
widgets={
'title': forms.TextInput(attrs={'placeholder':'for ex. highLimitLowPrice'}),
}
The function of save in view.py:
def backtest(request, pk=None):
if pk is not None:
param = get_object_or_404(Parameters, pk=pk, user=request.user)
form = BacktestForm(request.POST or None, instance=param)
else:
form = BacktestForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
if 'save' in request.POST:
obj = form.save(commit= False)
obj.user = request.user
obj.type = "backtest"
obj.save()
messages.info(request, 'Saved!')
return redirect(obj.get_backtest_url())
else:
messages.info(request, 'Please check entered data')
data = {
'active_page': 'backtest',
'form': form,}

In models.py
class Parameters(models.Model):
...
MARKET = (
(1,'First'),
(2,'Second')
)
SECTOR= (
(1,'First'),
(2,'Second')
)
market = models.CharField('Market', max_length=30, null=True)
sector= models.CharField('Sector', max_length=30, null=True)
def display_sector_label(self)
sectors= [(str(dict(self.SECTOR)[value])) for value in self.sector]
return ", ".join(sectors)
def display_market_label(self)
markets = [(str(dict(self.MARKET)[value])) for value in self.market]
return ", ".join(markets)
In forms.py
class BacktestForm(forms.ModelForm):
market = forms.MultipleChoiceField(
label='Market',
choices=Parameters.MARKET,
widget=forms.CheckboxSelectMultiple
)
sector = forms.MultipleChoiceField(
label='Sector',
choices=Parameters.SECTOR,
widget=forms.CheckboxSelectMultiple
)

Related

How to calculate the points based on the price of the total purchase in django models?

I am trying to create points earned by users after buying something and placed an order from the frontend. Also, I need to save the points on the database because users later use that points to buy something.
The points system looks like this.
Point System for % of the total purchase
Upto 10,000 = 1 %
10k to 50k =2.75%
50K plus = 5%
I haven't saved the price in DB, I just used it as a property so that it remains safe and cant be changed by anyone. It calculates whenever the get or post API is called.
class Order(models.Model):
ORDER_STATUS = (
('To_Ship', 'To Ship',),
('Shipped', 'Shipped',),
('Delivered', 'Delivered',),
('Cancelled', 'Cancelled',),
)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship')
ordered_date = models.DateTimeField(auto_now_add=True)
ordered = models.BooleanField(default=False)
#property
def total_price(self):
# abc = sum([_.price for _ in self.order_items.all()])
# print(abc)
return sum([_.price for _ in self.order_items.all()])
def __str__(self):
return self.user.email
class Meta:
verbose_name_plural = "Orders"
ordering = ('-id',)
class OrderItem(models.Model):
orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator)
order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items')
item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True)
order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True)
quantity = models.IntegerField(default=1)
ORDER_STATUS = (
('To_Ship', 'To Ship',),
('Shipped', 'Shipped',),
('Delivered', 'Delivered',),
('Cancelled', 'Cancelled',),
)
order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship')
#property
def price(self):
total_item_price = self.quantity * self.order_variants.price
return total_item_price
Updated Code:
class Points(models.Model):
order = models.OneToOneField(Order,on_delete=models.CASCADE,blank=True,null=True)
points_gained = models.IntegerField(default=0)
def collect_points(sender,instance,created,**kwargs):
if created:
if instance.total_price <= 10000:
abc = 0.01* (instance.total_price)
else:
abc = 0.75 * (instance.total_price)
return abc
post_save.connect(collect_points,sender=Order)
def save(self,*args,**kwargs):
self.points_gained = self.collect_points()
super(Points, self).save(*args, **kwargs)
I tried using Django signals and overwrite save function to create points. But when I check db, there are no rows in points table although order is made.
OrderCreate API
class OrderSerializer(serializers.ModelSerializer):
billing_details = BillingDetailsSerializer()
order_items = OrderItemSerializer(many=True)
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
#total_price = serializers.SerializerMethodField(source='get_total_price')
class Meta:
model = Order
fields = ['id','user','ordered_date','order_status', 'ordered', 'order_items', 'total_price', 'billing_details']
# depth = 1
def create(self, validated_data):
user = self.context['request'].user
if not user.is_seller:
order_items = validated_data.pop('order_items')
billing_details = validated_data.pop('billing_details')
order = Order.objects.create(user=user,**validated_data)
BillingDetails.objects.create(user=user,order=order,**billing_details)
for order_items in order_items:
OrderItem.objects.create(order=order,**order_items)
order.save()
return order
else:
raise serializers.ValidationError("This is not a customer account.Please login as customer.")
This answer is based on the comments and updated code.
I would have a relationship between the user and the points model, as the points belong to a user and not an order. Also this enables you to update the points whenever the same user orders again.
This results in the following model and post save signal:
def update_points(sender, instance, created, **kwargs):
if created:
if instance.total_price <= 10000:
points_gained = 0.01 * instance.total_price
else:
points_gained = 0.75 * instance.total_price
try:
# Check if user already has points and update if so
points = Points.objects.get(user=instance.user)
points.points_gained = points_gained
points.save(update_fields=['points_gained'])
except Points.DoesNotExist:
# User does not have points yet, create points
Points.objects.create(user=instance.user,
points_gained=points_gained)
post_save.connect(update_points, sender=Order)
class Points(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False, null=False)
points_gained = models.IntegerField(default=0)

How do I modify the ManyToMany submission form from "hold ctrl to select multiple"

I'm making a medication tracking site in Django and am having trouble assigning multiple times to a medication. Currently I have a model for the Medication:
class Medication(models.Model):
UNDEFINED = ''
MILIGRAMS = 'mg'
MILIEQUIVILENT = 'MEQ'
MILILITERS = 'ml'
MEASUREMENT_CHOICES = [
(UNDEFINED, ' '),
(MILIGRAMS, 'mg'),
(MILIEQUIVILENT, 'MEQ'),
(MILILITERS, 'ml'),
]
ORAL = 'orally'
OPTICALLY = 'optically'
NASALLY = 'nasally'
OTTICALLY = 'per ear'
SUBLINGUAL = 'sublingual'
SUBCUTANEOUS = 'subcutaneous'
PER_RECTUM = 'per rectum'
TOPICAL = 'topical'
INHALATION = 'inhalation'
ROUTE_CHOICES = [
(ORAL, 'orally'),
(OPTICALLY, 'optically'),
(NASALLY, 'nasally'),
(OTTICALLY, 'per ear'),
(SUBLINGUAL, 'sublingual'),
(SUBCUTANEOUS, 'subcutaneous'),
(PER_RECTUM, 'per rectum'),
(TOPICAL, 'topical'),
(INHALATION, 'inhalation'),
]
AS_NEEDED = "PRN"
EVERY = "every"
EVERY_TWO = "every two"
EVERY_THREE = "every three"
EVERY_FOUR = "every four"
EVERY_FIVE = "every five"
EVERY_SIX = "six"
EVERY_SEVEN = "seven"
EVERY_EIGHT = "eight"
EVERY_NINE = "nine"
FREQUENCY_NUM = [
(AS_NEEDED, "PRN"),
(EVERY, "every"),
(EVERY_TWO, "every two"),
(EVERY_THREE, "every three"),
(EVERY_FOUR, "every four"),
(EVERY_FIVE, "every five"),
(EVERY_SIX, "six"),
(EVERY_SEVEN, "seven"),
(EVERY_EIGHT, "eight"),
(EVERY_NINE, "nine"),
]
MINUTE = 'minute'
HOUR = "hour"
DAY = "day"
WEEK = 'week'
MONTH = "month"
FREQUENCY_MEASUREMENT = [
(MINUTE, 'minute'),
(HOUR, "hour"),
(DAY, "day"),
(WEEK, 'week'),
(MONTH, "month"),
]
ONE_TAB = 'tab'
MULTIPLE_TABS = 'tabs'
HALF_TAB = 'half of a tab'
THIRD_TAB = 'third of a tab'
QUARTER_TAB = 'quarter of a tab'
ONE_DROP = 'drop'
MULTIPLE_DROPS = 'drops'
FORM_FACTORS = [
(ONE_TAB, 'tab'),
(MULTIPLE_TABS, 'tabs'),
(HALF_TAB, 'half of a tab'),
(THIRD_TAB, 'third of a tab'),
(QUARTER_TAB, 'quarter of a tab'),
(ONE_DROP, 'drop'),
(MULTIPLE_DROPS, 'drops')
]
client = models.ForeignKey(
Client_Medlist,
blank=True,
default=None,
on_delete=models.CASCADE)
name = models.CharField(max_length=255)
drug_class = models.CharField(max_length=255)
dosage = models.FloatField(default=10)
measurement = models.CharField(
max_length=3,
choices=MEASUREMENT_CHOICES,
default=MILIGRAMS,)
number_of_form = models.IntegerField(default=1)
drug_form_factor = models.CharField(
max_length=255,
choices=FORM_FACTORS,
default=ONE_TAB,
)
route = models.CharField(
max_length=255,
choices=ROUTE_CHOICES,
default=ORAL,)
frequency_num = models.CharField(
max_length=255,
choices=FREQUENCY_NUM,
default=EVERY,)
frequency_measurement = models.CharField(
max_length=255,
choices=FREQUENCY_MEASUREMENT,
default=DAY,)
times_taken = models.ManyToManyField(Medication_Times)
start_date = models.DateField(default=timezone.now)
is_med_active = models.BooleanField(default=True)
transcription_author = models.ForeignKey(User, on_delete=models.PROTECT)
transcription_date = models.DateField(default=timezone.now)
def __str__(self):
return self.name
This model has a 'ManyToMany' relation to the medication times model:
class Medication_Times(models.Model):
times_taken = models.TimeField(default=timezone.now, auto_now=False, auto_now_add=False)
display_name = models.CharField(default='Scheduled Time', max_length=255)
def __str__(self):
return self.times_taken.strftime('%I:%M %p')
For the view leading to this page I am using LoginRequiredMixin and CreateView:
class MedicationNew(LoginRequiredMixin, CreateView):
model = Medication
template_name = 'client_profile/new_med.html'
context_object_name = 'posts'
fields = ['client', 'name', 'start_date', 'drug_class', 'dosage', 'measurement', 'route', 'frequency_num', 'frequency_measurement', 'times_taken']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
This all works well, but where the maximum value between times is fifteen minutes, when the user is creating a new medication to add to a client's chart, the times are displayed in a long scrolling list with only ctrl+click to select multiple.
Where this needs to be as user friendly as possible, I was thinking that selecting a time, then adding it to a box displayed below the scrolling selection might be a better approach. This way if a user selects the wrong thing, it would be in the box for easy removal, and would be easy to scroll back and select the correct time(s). Then after the correct time(s) are chosen, the whole form could be submitted.
Is there a straightforward way to do this in Django? I have been looking everywhere for a manner to do so, but have yet to come up with anything. Any help would be greatly appreciated.

Saving formset when a compulsory field was not supplied?

I get an error "NOT NULL constraint failed" when I try to save a formset in an update view and the formset has had new forms added. I think the reason is that the database has a required field (journal_entry) that isn't part of the Formset ModelForm. So when the formset is attempted to be saved lineitem_formset.save() I get the error.
How can I add this required field value before saving the formset?
View.py
#login_required
def entries_update(request, pk):
journal_entry = get_object_or_404(JournalEntry, pk=pk)
journal_entry.date = journal_entry.date.strftime('%Y-%m-%d') #Convert date format to be suitable for Datepicker input.
journal_entry_form = JournalEntryForm(instance=journal_entry)
LineItemFormSet = modelformset_factory(LineItem, fields=('ledger','description','project','cr','dr'), extra=2)
line_items = LineItem.objects.filter(journal_entry=journal_entry)
lineitem_formset = LineItemFormSet(queryset=line_items)
if request.method == 'POST':
lineitem_formset = LineItemFormSet(request.POST)
journal_entry_form = JournalEntryForm(request.POST, instance=journal_entry)
if lineitem_formset.is_valid() and journal_entry_form.is_valid:
lineitem_formset.save() <-- ERROR HAPPENS HERE
journal_entry_form.save()
messages.success(request, "Journal entry successfully updated.")
return HttpResponseRedirect(reverse('journal:entries_show_detail', kwargs={'pk': journal_entry.id}) )
Models.py
class JournalEntry(models.Model):
# User needs to be set back to compulsory !!!
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
date = models.DateField(null=False, blank=False)
TYPE = (
('BP', 'Bank Payment'),
('YE', 'Year End'),
('JE', 'Journal Entry')
)
type = models.CharField(
max_length=2,
choices=TYPE,
blank=True,
default='0'
)
description = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
if self.description:
return self.description
else:
return 'Journal Entry' + str(self.id)
class Meta(object):
ordering = ['id']
verbose_name_plural = 'Journal entries'
class LineItem(models.Model):
journal_entry = models.ForeignKey(JournalEntry, on_delete=models.CASCADE) <--- This is the field that needs to be set.
ledger = models.ForeignKey(Ledger, on_delete=models.PROTECT)
description = models.CharField(max_length=255, null=True, blank=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, blank=True)
cr = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
dr = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
STATUS = (
('0', 'Not reconciled'),
('1', 'Draft'),
)
status = models.CharField(
max_length=1,
choices=STATUS,
default='0'
)
reconciliation_date = models.DateField(null=True, blank=True)
#def __str__(self):
# return self.description
class Meta(object):
ordering = ['id']
forms.py
class JournalEntryForm(ModelForm):
def clean_date(self):
data = self.cleaned_data['date']
#Check date is not more than 30d future
if data > (datetime.date.today() + datetime.timedelta(30)):
raise ValidationError('Date cannot be more than 30d future')
if data < (datetime.date.today() - datetime.timedelta(90)):
raise ValidationError('Date cannot be more than 90d past')
return data
class Meta:
model = JournalEntry
fields = ['date','description']
widgets = {'date': DateTypeInput()}
class LineItemForm(ModelForm):
class Meta:
model = LineItem
fields = ['ledger','description','project','cr','dr']
# This init disallows empty formsets
def __init__(self, *arg, **kwarg):
super(LineItemForm, self).__init__(*arg, **kwarg)
self.empty_permitted = False
def clean(self):
cr = self.cleaned_data['cr']
dr = self.cleaned_data['dr']
if cr == None and dr == None:
raise ValidationError('You must enter a CR or DR.')
if cr and dr:
raise ValidationError('You must enter a CR or DR, not both.')
Thanks to #Iain Shelvington again. Edited the following lines to use inline_formset and now works:
LineItemFormSet = inlineformset_factory(JournalEntry, LineItem, fields=('ledger','description','project','cr','dr'), extra=2)
and:
lineitem_formset = LineItemFormSet(request.POST, instance=journal_entry)

If Else in Djnago Views

I'm making a LMS.
Where a User applies for a leave and the admin accepts or rejects it.
Right now I am stuck in a problem where I want the user to apply for a leave through the Django form by selecting a leave type (casual, sick, half pay etc), if the admin accepts it then the default values in the database changes or gets deducted from the Employee model and when the counter reaches 0 an error is generated that you don't have any leaves,contact the admin.
I'm unable to understand how to make the logic for it.
I tried Applying if else statement in the views and even in the models.
views.py
The function name is "Reject" as I am trying to make changes to the accept function.
def reject_leave(request, id):
# employee_item = Employee.objects.get(id=id)
all_item = Leave.objects.get(id=id)
all = Employee.objects.get(id=id)
context = {'all': all,'all_item': all_item}
'''
if the leave_type (choice field of the leaves from the django form) equals to a leave type like Annual leave
The the program deducts 1 or the amount entered from the total value of Annual leave from the Model Employee
'''
*Sorry for the poor writing I'm not experienced in Django*
***This code is saying that in an illogical way.***
if leave_type.id is "Annual_leave":
Annual_leave - 1
else:
subject = "Leave Rejected" # email subject
email_from = "settings.EMAIL_HOST_USER" # email from
to_email = ['someemail#something.com'] # email to
with open(...) as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from, to=to_email)
html_template = get_template(...).render()
msg.attach_alternative(html_template, "text/html")
msg.send()
return render(request, 'projectfiles/rejectemail.html',context)
forms.py
class Leave_Form(forms.ModelForm):
to_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder': ' Month/Date/Year'}))
from_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder':' Month/Date/Year'}))
class Meta:
model = Leave
fields = ['leave_Type', 'description',
'from_date', 'to_date', 'leave_qty']
exclude = ['employee_leaves', 'submit_date']
leave_type_choice = (
("Annual_leave", "Annual leave"),
("Sick_leave", "Sick leave"),
("Casual_leave", "Casual leave"),
("Emergency_leave", "Emergency leave"),
("Half_pay","Half Pay")
)
widgets = {
'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
'description': forms.Textarea(
attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}
models.py
class Employee(models.Model):
employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
employee_designation = models.CharField(max_length = 20)
employee_department = models.CharField(max_length = 35)
Annual_leave = models.PositiveSmallIntegerField(default=10)
Sick_leave = models.PositiveSmallIntegerField(default=3)
Casual_leave = models.PositiveSmallIntegerField(default=3)
Half_pay = models.PositiveSmallIntegerField(default=4)
Emergency_leave = models.PositiveSmallIntegerField(default=3)
allowed = models.BooleanField(default=False)
def __str__(self):
return self.employee_name.username
class Meta:
verbose_name_plural = "Employee"
class Leave(models.Model):
employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
leave_Type = models.CharField(max_length=25)
leave_qty = models.PositiveSmallIntegerField(default=0)
description = models.CharField(max_length=75, blank=True, null=True)
submit_date = models.DateTimeField(auto_now_add=True)
from_date = models.DateField(auto_now=False, auto_now_add=False)
to_date = models.DateField(auto_now=False, auto_now_add=False)
class Meta:
verbose_name_plural = "Leave"
def __str__(self):
return self.leave_Type + " by " + str(self.employee_leaves)
When the Admin accepts (or in this case rejects) a leave.
e.g.
Sick leave I want 1 or entered amount of leaves to be deducted from the total of the allocated sick leaves.
def reject_leave(request, id): # overwriting built-in id is not a good idea
all_item = Leave.objects.get(id=id) # This is a single item, not all items
all = Employee.objects.get(id=id) # this again is a single item, not all items
context = {'all': all, 'all_item': all_item}
if leave_type.id is "Annual_leave":
# What is leave_type?
Annual_leave - 1
# What is Annual_leave? What does -1 supposed to do?
# Maybe you meant
# employee = Employee.objects.get(id=id)
# leave = employee.employee_leaves_set.last()
# if leave.leave_Type == 'Annual_leave':
# employee.Annual_leave -= 1
# employee.save()
else:
subject = "Leave Rejected"
email_from = "settings.EMAIL_HOST_USER"
to_email = ['talhamurtaza#clickmail.info']
with open('...') as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from, to=to_email)
html_template = get_template(
"...").render()
msg.attach_alternative(html_template, "text/html")
msg.send()
return render(request, 'projectfiles/rejectemail.html', context)
There is so many things wrong with this that I can confidently say you haven't taken a python tutorial, read pep-8 nor taken a django tutorial. So please start from the first one and work your way up.

while processing a many to many field my views.py is giving me error

i have pasted my code along with stack trace at .. https://gist.github.com/2199510
my models.py
class Roles(models.Model):
role = models.CharField(max_length=32)
def __unicode__(self):
return self.role
class Player(models.Model):
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
#name = models.CharField(max_length=32)
team = models.ForeignKey(Team)
role = models.ManyToManyField(Roles)
preffered_position = models.IntegerField(max_length=3,choices=zip(range(1,12),range(1,12)) , default=1)
status = models.BooleanField(default=True)
#career statistics
best_batting = models.IntegerField(max_length=6, default=0)
best_bowling = models.CharField(max_length=6, default=0)
#total batting statistics
score = models.IntegerField(max_length=6, default=0)
balls = models.IntegerField(max_length=6, default=0)
#total bowling statistics
overs = models.IntegerField(max_length=6, default=0)
wickets = models.IntegerField(max_length=6, default=0)
#total fielding statistics
catches = models.IntegerField(max_length=6, default=0)
def __unicode__(self):
return "%s %s" % (self.first_name, self.last_name)
my forms.py
class PlayerForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
role = forms.ModelMultipleChoiceField(
Roles.objects.all(),
widget=CheckboxSelectMultiple
)
my views.py
def add_player(request, team_id):
template = get_template('cricket/addplayer.html')
loggedinuser = request.user
userteam = Team.objects.get(owner=loggedinuser)
currentteam = Team.objects.get(id=team_id)
#now on to permissions .. if userteam = currentteam, the display form, otherwise display error "Permission denied"
if userteam == currentteam:
if request.method == 'POST':
form = PlayerForm(request.POST)
if form.is_valid():
Player.objects.create(
first_name = form.cleaned_data['first_name'],
last_name = form.cleaned_data['last_name'],
team = Team.objects.get(id=team_id),
role = form.cleaned_data['role'],
)
return HttpResponseRedirect('/team/%s/' % team_id)
else:
form = PlayerForm
page_vars = Context({
'form': form,
'loggedinuser': loggedinuser,
'team': userteam,
})
crsfcontext = RequestContext(request, page_vars)
output = template.render(crsfcontext)
return HttpResponse(output)
else:
error = "Permission Denied: You cannot add player to " + str(currentteam.name)
page_vars = Context({
'loggedinuser': loggedinuser,
'error': error,
})
crsfcontext = RequestContext(request, page_vars)
output = template.render(crsfcontext)
return HttpResponse(output)
if somebody could tell me where and what i am doing wrong, that would be of great help.
//yousuf
As the error message states, you can't pass role (or any ManyToMany field) as a keyword in the model instantiation call. You need to instantiate and save your model first, then add one or more roles with player.roles.add(my_role).