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.
Related
Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.
In Django, I want to build a form that collects shipping addresses from users! Then save them to database
There is views.py starts with defining a function "is_valid_form(values)"
def is_valid_form(values):
valid = True
for field in values:
if field == '':
valid = False
return valid
class EnCheckoutView(View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
form = CheckoutForm()
context = {
'form': form,
'couponform': CouponForm(),
'order': order,
'DISPLAY_COUPON_FORM': True
}
shipping_address_qs = Address.objects.filter(user=self.request.user, address_type='S', default=True)
if shipping_address_qs.exists():
context.update({
'default_shipping_address': shipping_address_qs[0]
})
return render(self.request, 'en-checkout-page.html', context)
except ObjectDoesNotExist:
messages.info(self.request, 'You do not have an active order.')
return redirect('core:en-checkout')
def post(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
except ObjectDoesNotExist:
messages.warning(self.request, 'You do not have an active order')
return redirect('core:en-order-summary')
form = CheckoutForm(self.request.POST or None)
if form.is_valid():
use_default_shipping = form.cleaned_data.get("use_default_shipping")
if use_default_shipping:
print('Using the default shipping address')
address_qs = Address.objects.filter(user=self.request.user, default=True)
if address_qs.exists():
shipping_address = address_qs[0]
order.shipping_address = shipping_address
order.save()
else:
messages.info(self.request, 'No default shipping address available')
return redirect('core:en-checkout')
else:
print('User is entering a new shipping address')
customer_name = form.cleaned_data.get('customer_name')
phone = form.cleaned_data.get('phone')
email = form.cleaned_data.get('email')
shipping_address1 = form.cleaned_data.get('shipping_address1')
shipping_address2 = form.cleaned_data.get('shipping_address2')
en_shipping_country = form.cleaned_data.get('en_shipping_country')
shipping_zip = form.cleaned_data.get("shipping_zip")
if is_valid_form([customer_name, phone, shipping_address1]):
shipping_address = Address(
user=self.request.user,
customer_name=customer_name,
phone=phone,
email=email,
street_address=shipping_address1,
apartment_address=shipping_address2,
country=en_shipping_country,
zip=shipping_zip,
address_type='S'
)
shipping_address.save()
order.shipping_address = shipping_address
order.save()
set_default_shipping = form.cleaned_data.get('set_default_shipping')
if set_default_shipping:
shipping_address.default = True
shipping_address.save()
else:
messages.info(self.request, 'Please ***fill in the required shipping address fields')
en_payment_option = form.cleaned_data.get('en_payment_option')
if en_payment_option == 'S':
return redirect('core:en-payment', en_payment_option='Pay with credit card')
elif en_payment_option == 'P':
return redirect('core:ar-delivery', en_payment_option='Cash on delivery')
else:
messages.warning(self.request, 'Invalid payment option selected')
return redirect('core:en/checkout')
Why this form does not save the address to the database?
I could have posted forms.py, html template, and models.py, but I guess that will explain the problem.
forms.py
EN_PAYMENT_CHOICES = (
('S', 'Pay with credit card'),
('P', 'Cash on delivery')
)
class CheckoutForm(forms.Form):
customer_name = forms.CharField(max_length=100, required=True)
phone = forms.IntegerField(required=True)
email = forms.EmailField()
shipping_address1 = forms.CharField(required=True)
shipping_address2 = forms.CharField(required=False)
ar_shipping_country = CountryField(blank_label='(اختار البلد)').formfield(
required=False,
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100',
}))
en_shipping_country = CountryField(blank_label='(Choose a country)').formfield(
required=False,
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100',
}))
shipping_zip = forms.CharField(required=False)
set_default_shipping = forms.BooleanField(required=False)
use_default_shipping = forms.BooleanField(required=False)
payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=PAYMENT_CHOICES)
en_payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=EN_PAYMENT_CHOICES)
models.py
class Address(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
customer_name = models.CharField(max_length=100, null=True)
phone = models.IntegerField(null=True)
email = models.EmailField(null=True)
street_address = models.CharField(max_length=250)
apartment_address = models.CharField(max_length=250)
country = CountryField(multiple=False, null=True)
zip = models.CharField(max_length=100)
address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES)
default = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural = 'Addresses'
I try to fill empty fields when I save model form, but unfortunately, it doesn't work properly.
this is my view:
def bylaw_save(request):
form = BylawForm(initial={'who_created': request.user.username})
if request.method == 'POST':
form = BylawForm(request.POST)
if form.is_valid():
gdn = GlobalDocNumber.objects.get(pk=1)
gdn.gdn += 1
gdn.save()
raspr_num = form.cleaned_data['raspr_num'][:]
raspr_num = raspr_num.split('/')
bylaw = form.save(commit=False)
bylaw.district = 'unfilled'
bylaw.department = 'unfilled'
bylaw.performer = 'unfilled'
bylaw.check_type = 'unfilled'
bylaw.save()
return bylaw_form(request, msg='test')
else:
return bylaw_form(request, msg='test')
return render(request, 'bylaw/bylaw_form.html', {'form': form})
this is fraction of my form:
district = ModelChoiceField(required=False, queryset=DistrictsMenu.objects.all(), to_field_name="district",
widget=Select(attrs={'id': "district", 'class': 'form-control col-6'}))
department = ModelChoiceField(required=False, queryset=DepartmentsMenu.objects.all(), to_field_name="department",
widget=Select(attrs={'id':"department", 'class': "form-control col-6"}))
UPDATE: This is my model with default='Unfilled', according to Arthur M and Rohan suggestions (But it also doesn't work, it gives me a "NOT NULL constraint failed: bylaw_bylawmodel.department" error, in this case I don't fill department field):
class BylawModel(models.Model):
raspr_date = models.DateField()
district = models.CharField(max_length=255, default='Unfilled')
department = models.CharField(max_length=255, default='Unfilled')
organization = models.CharField(max_length=255, default='Unfilled')
inn = models.IntegerField()
performer = models.CharField(max_length=255, default='Unfilled')
check_type = models.CharField(max_length=255)
date_proved = models.DateField()
raspr_num = models.CharField(max_length=255, unique=True)
who_created = models.CharField(max_length=255)
when I save this from, it always fills with 'unfilled'. How can I fill empty values only if they are really empty?
By doing
bylaw.fieldName = 'unfilled' you're overwriting the value sent from your form.
If you don't want to add a default value in your model (which I would recommend) you can add a simple :
if not bylaw.fieldName:
bylaw.fieldName = 'unfilled'
For every one of your fields.
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
)
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).