I have a view:
def PeopleView(request):
...
parameters = copy.deepcopy(request.GET)
for parameter in request.GET:
if not request.GET.get(parameter):
del parameters[parameter]
people = Person.objects.filter(**parameters)
search_form = PersonSearchForm()
return render(request, 'persons/people.html', {
'people': people,
'search_form': search_form,
...
})
PersonSearchForm:
class PersonSearchForm(forms.Form):
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
second_name = forms.CharField(required=False)
country = forms.CharField(required=False)
city = forms.CharField(required=False)
gender = forms.CharField(widget=forms.Select, required=False)
birthday = forms.DateField(required=False)
school = forms.CharField(required=False)
university = forms.CharField(required=False)
profession = forms.CharField(required=False)
Person model has fields from PersonSearchForm with the same name. And this form is sent by user as GET request.
GET request and print of parameters variable:
However filter always has no results. What's wrong?
SOLUTION
I solved the problem. The solution is a transformation of querydict parameters to dict object. It looks like:
...
filter_parameters = {}
for parameter in parameters:
filter_parameters[parameter] = parameters[parameter]
people = Person.objects.filter(**filter_parameters)
...
And it works.
Related
I have two Models, (Doctor & Patient), the Doctor model is the parent model, How can I make the Service_doctor field an instance of the Doctor's model so that I can get the Doctor's name into the Patient's model using for loop in the HTML Template. This is what am trying to mean;
models.py
class Doctor(models.Model):
Doctor_Name = models.CharField(max_length=200)
def __str__(self):
return self.Doctor_Name
class Patient(models.Model):
Name = models.CharField(max_length=200)
Telephone = models.CharField(max_length=100, unique=True)
Service_doctor = models.ForeignKey(Doctor, on_delete=CASCADE)
def __str__(self):
return self.Doctor_Name
views.py
def Newpatient(request):
if request.method == 'POST':
Name = request.POST.get('Name')
Telephone = request.POST.get('Telephone')
Service_doctor = request.POST.get('Service_doctor')
formdata = Patient(Name=Name, Telephone=Telephone, Service_doctor=Service_doctor)
formdata.save()
return render(request, 'Adm.html')
Any help is appreciated.
This will create a new record under patient:
dr = Doctor.object.filter(id = pk)
patient = Patient(
name = 'John Doe'
telephone = '123456786'
service_doctor = dr
)
You can achieve this by using the request.user to set the Service_doctor as the one that is currently in instance:
def Newpatient(request):
if request.method == 'POST':
Name = request.POST.get('Name')
Telephone = request.POST.get('Telephone')
Service_doctor = request.user
formdata = Patient(Name=Name, Telephone=Telephone, Service_doctor=Service_doctor)
formdata.save()
return render(request, 'Adm.html')
I have been trying to make boat reservation system.
# models.py
class Boat(models.Model):
name = models.CharField (max_length=10, unique=True, blank=False)
type = models.CharField (max_length=10, blank=False)
class Booking(models.Model):
date_from = models.DateField(auto_now=False, auto_now_add=False)
date_to = models.DateField(auto_now=False, auto_now_add=False)
rent = models.DecimalField(max_digits=7, decimal_places=2)
boat = models.ForeignKey(Boat, on_delete=models.CASCADE)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
A new boat is registered through this form:
class newBoatform(forms.Form):
name = forms.CharField(label='Name of the boat: ', max_length=15)
type = forms.CharField(label='Type of the boat: ', max_length=15)
class Meta:
model = Boat
fields = ('name','type',)
A boat is booked through this form:
class bookform(forms.Form):
boat =forms.CharField(label='Select boat',max_length=15)
date_from=forms.DateField(label='Date from', initial=date.today)
date_to=forms.DateField(label='Date to')
rent = forms.DecimalField(label='Pay $ ')
class Meta:
model = Booking
fields = ('date_from','date_to','rent','boat','person',)
To book a boat through the bookform, I am inserting an existing boat name and other field information. Then I am getting the error:
Cannot assign "'Emma'": "Booking.boat" must be a "Boat" instance.
The view function of the bookform:
def bookBoat(request):
if request.method == 'POST':
form = bookform(request.POST)
if form.is_valid():
obj = Booking()
obj.boat = form.cleaned_data['boat']
obj.date_from = form.cleaned_data['date_from']
obj.date_to = form.cleaned_data['date_to']
obj.rent = form.cleaned_data['rent']
obj.save()
return HttpResponseRedirect('/thanks/')
else:
form = bookform()
return render(request, 'booking.html', {'form': form})
I can't understand what is wrong. Other answers on this same error are going over my head.
As I can't comment here's my suggestion: obj.boat = Boat.objects.get(name=form.cleaned_data['boat'])
That should do the job.
I am getting this at every attempt.
Cannot assign "u''": "Company.parent" must be a "Company" instance.
I do not know what else to do.
The view code is still half baked, sorry for that.
Am I passing wrong parameters to the form?
I have the following model:
models.py
class Company(AL_Node):
parent = models.ForeignKey('self',
related_name='children_set',
null=True,
db_index=True)
node_order_by = ['id', 'company_name']
id = models.AutoField(primary_key=True)
company_name = models.CharField(max_length=100L, db_column='company_name') # Field name made lowercase.
next_billing_date = models.DateTimeField()
last_billing_date = models.DateTimeField(null=True)
weekly = 'we'
twice_a_month = '2m'
every_two_weeks = '2w'
monthly = 'mo'
billing_period_choices = (
(weekly, 'Weekly'),
(every_two_weeks, 'Every two weeks'),
(twice_a_month, 'Every two weeks'),
(monthly, 'Monthly'),
)
billing_period = models.CharField(max_length=2,
choices=billing_period_choices,
default=weekly)
objects = CompanyManager()
The following forms.py:
class newCompany(ModelForm):
company_name = forms.CharField(label='Company Name',
widget=forms.TextInput(attrs={'class': 'oversize expand input-text'}))
billing_period = forms.ModelChoiceField
next_billing_date = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-text small', 'id': 'datepicker'}))
parent = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Company
fields = ["company_name", "parent", "billing_period", "next_billing_date"]
The following view:
def create_company(request):
userid = User.objects.get(username=request.user).id
my_company_id = CompanyUsers.objects.get(user_id=userid).company_id
my_company_name = Company.objects.get(id=my_company_id).company_name
machines = Title.objects.raw(
'select machines.id, title.name, machines.moneyin, machines.moneyout, moneyin - moneyout as profit, machines.lastmoneyinoutupdate, (select auth_user.username from auth_user where machines.operator = auth_user.id) as operator, (select auth_user.username from auth_user where machines.readers = auth_user.id) as readers from machines, title where machines.title = title.id and machines.company_id =%s',
[my_company_id])
if request.method == 'POST':
form_company = newCompany(request.POST)
if form_company.is_valid():
new_company = form_company.save(commit=False)
new_company.parent = my_company_id
if request.POST.get('select_machine'):
selected_machine = request.POST.getlist('select_machine')
percentage = request.POST.get('percentage')
if not Beneficiary.objects.check_assign_machine(my_company_id, selected_machine, percentage):
target_company_name = new_company.company_name
target_company_id = Company.objects.get(company_name=target_company_name).id
new_company.save()
Machines.objects.assign_machine(target_company_id, selected_machine)
Beneficiary.objects.create_beneficiary(percentage, target_company_name, my_company_id, selected_machine)
else:
invalid_machines = Beneficiary.objects.check_assign_machine(my_company_id, selected_machine, percentage)
return render(request, 'lhmes/createcompany.html',
{'form_company': form_company, 'machines': machines, 'my_company_name': my_company_name, 'invalid_machines' : invalid_machines})
else:
new_company.save()
else:
form_company = newCompany()
return render(request, 'lhmes/createcompany.html',
{'form_company': form_company, 'machines': machines, 'my_company_name': my_company_name})
The error message says you are trying to set a relationship with a string but Django expects the value to be an instance of the Company model. You should assign the foreign key fields with a real model instance instead of only the primary key.
I've spotted a few places in the code where you are assigning a PK:
new_company.parent = my_company_id
Where the model expects it to be an instance:
new_company.parent = Company.objects.get(id=my_company_id)
I really don't remember if this works, but you can try:
new_company.parent_id = int(my_company_id)
This would spare a trip to the database.
this is my model :
class Member(models.Model):
profile = models.OneToOneField(Profile, editable=False, null=True)
title = models.CharField(max_length=4, choices=TITLE_TYPES, null=True)
name = models.CharField(max_length=100, null=True, verbose_name='Name')
lastname = models.CharField(max_length=100, null=True, verbose_name='LastName')
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, verbose_name='Gender')
dob = models.DateField('dob')
redressno = models.CharField(max_length=100, null=True, verbose_name='RedressNo')
this is my form
class MemberForm(ModelForm):
dob = forms.DateField(required=False, input_formats=('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y'))
class Meta:
model = Member
exclude = ('profile',)
this is my view :
members = Member.objects.filter(profile=profiles)
data1 = serializers.serialize( "python", members)
print data1[0]['fields']
memarr=[]
for index, a in enumerate(data1):
memarr.append(a['fields'])
print memarr
MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet)
member_formset = MemberFormSet(initial=memarr)
#here setting intial array of mem
mdata['form-TOTAL_FORMS']=u'2'
mdata['form-INITIAL_FORMS']=u'0'
mdata['form-MAX_NUM_FORMS']=u''
member_formset = MemberFormSet(mdata)
memberform = MemberForm(mdata)
c = {'form': form, 'memberform': memberform, 'member_formset': member_formset}
c.update(csrf(request))
return render_to_response('edit_profile.html', c, RequestContext(request))
m passing the initial data but still the initial data is not being shown in the form?
Here's your problem:
member_formset = MemberFormSet(initial=memarr)
...
member_formset = MemberFormSet(mdata)
You're setting the initial data on one FormSet instance, and then throwing away that instance with the initial data and overwriting with another new FormSet instance.
You can simplify your view to this:
# If you are not using csrf middleware, use this decorator instead of ghetto magic
#csrf_protect
#render_to('edit_profile.html') # handy decorator from django-annoying
def profile_members_edit(request.profile):
members = Member.objects.filter(profile=profiles)
# iterate over the ValuesQuerySet gives a list of dicts for initial data
member_data = list(members.values())
# setting extra=<> and max_num=<> is easier than setting internal form data
MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet, extra=2)
member_formset = MemberFormSet(initial=member_data)
return {'member_formset': member_formset }
I have a model that looks like this
class RSVP (models.Model):
def __unicode__(self):
return self.firstName + " " + self.lastName
firstName = models.CharField(max_length=30)
lastName = models.CharField(max_length=30)
rsvpID = models.CharField(max_length=9, unique = True)
allowedAdults = models.IntegerField(default = 2)
allowedChildren = models.IntegerField(default = 0)
adultsAttending = models.IntegerField(default = 0)
childrenAttending = models.IntegerField(default = 0)
and I have a ModelForm that looks like this
class RsvpForm(ModelForm):
class Meta:
model = RSVP
exclude= ('firstName', 'lastName', 'allowedAdults', 'allowedChildren')
What I would like to happen is that instead of a text field for the adultsAttending, a dropdown box with the values 0 to allowedAdults shows up. This is for a wedding rsvp site and I'd like to set the max number of +1's an invitee can bring on an individual basis
Any thoughts on how to go about this?
I'm thinking you want to fork the allowed children/ adults as well as the name to another model:
models.py
class Invited(models.Model):
f_name = models.CharField()
l_name = models.CharField()
allowed_adults = models.IntegerField()
allowed_children = models.IntegerField()
class RSVP(models.Model):
invited = models.ForeignKey(Invited)
adults_attending = models.IntegerField()
children_attending = models.IntegerField()
Then you would create the invited objects and assign the allowed adults and children. And the RSVP form would take those number into account when generating the choices for your drop down box.
The drop down can be implemented by overriding the IntegerField widget with a ChoiceField
forms.py
class InvitedForm(forms.ModelForm):
class Meta:
model = Invited
class RSVPForm(forms.ModelForm):
class Meta:
model = RSVP
exclude = ['invited',]
def __init__(self, *args, **kwargs):
max_adults = kwargs.pop('max_adults',2) #default to 2 if no max set
max_children = kwargs.pop('max_children',2) #default to 2 if no max set
super(RSVPForm, self).__init__(*args, **kwargs)
adult_choices = ( (x,str(x)) for x in range(max_adults+1)) )
children_choices = ( (x,str(x)) for x in range(max_children+1)) )
self.fields['adults_attending'] = forms.ChoiceField(choices = adult_choices)
self.fields['children_attending'] = forms.ChoiceField(choices = children_choices)
views.py
def rsvp_view(request, invited_id):
invited = get_object_or_404(Invited, pk=invited_id)
if request.method=='POST':
form = RSVPForm(request.POST, max_adults=invited.allowed_adults,
max_children=invited.allowed_children)
if form.is_valid():
rsvp = form.save(commit=False)
rsvp.invited = invited
rsvp.save()
return HttpResponse("Success")
else:
form = RSVPForm(max_adults=invited.allowed_adults, max_children=invited.allowed_children)
context = { 'form':form,
'invited':invited }
return render_to_response('rsvp.html', context,
context_instance=RequestContext(request))