I am working on a Django Project where I want to collect payment in Dollars from Applicants on the portal, and I don't know how to go about it. Though I have been following an online tutorial that shows how to do it but the result I am having is different with the recent error which says 'module' object is not callable.
Remember that I have tested my configured environment and also imported it into my views on top of the page.
Profile model code:
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=16, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
def __str__(self):
return f'{self.applicant.username}-Profile'
Education/Referee Model code:
class Education(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
qualification = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
instition = models.CharField(max_length=40, null=True)
reasons = models.CharField(max_length=100, null=True)
matnumber = models.CharField(max_length=255, null=True)
reference = models.CharField(max_length=100, null=True)
refphone = models.CharField(max_length=100, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return f'{self.applicant}-Education'
Submitted Model code:
class Submitted(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
approved = models.CharField(max_length=20, null=True)
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
Scholarship Model code:
class Scholarship(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
name = models.CharField(max_length=100, null = True)
description = models.CharField(max_length=200, null = True)
category = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
amount = models.FloatField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'WASU Scholarship: {self.name}-{self.name}'
My View for printing slip:
def AppSlip(request):
check_submited = Submitted.objects.get(applicant=request.user)
check_education = Education.objects.get(applicant = request.user)
candidate_edu = check_education.qualification
scholarship = Scholarship.objects.get(category=candidate_edu)
context = {
'candidate_edu':candidate_edu,
'scholarship':scholarship,
}
return render(request, 'user/slip.html', context)
My view for applicant to fill form for payment which I want their Profile captured automatically in the form:
def scholarship_detail(request, pk):
data = Scholarship.objects.get(id=pk)
if request.method=='POST':
form = PaymentForm(request.POST)
if form.is_valid():
user = Profile.objects.get(applicant=request.user)
name= user.surname
email = form.cleaned_data['email']
amount = form.cleaned_data['amount']
phone = form.cleaned_data['phone']
context = {'applicant':name, 'email':email, 'amount':amount, 'phone':phone}
return process_payment(request, context)
else:
form = PaymentForm()
ctx={
'form':form,
'product':data,
}
return render(request, 'user/scholarship.html', ctx)
My form code for Payment: How can query logged in user profile and fill into name, email, phone, amount from Scholarship Model into amount form filled.
class PaymentForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField()
phone=forms.CharField(max_length=15)
amount = forms.FloatField()
View code for processing Payment (Where I am suspecting the error). Though I have configured my env using django-dotenv with the Flutterwave Secret Key in it.
#login_required(login_url='user-login')
def process_payment(request, newContext={}):
auth_token= dotenv('SECRET_KEY')
hed = {'Authorization': 'Bearer ' + auth_token}
data = {
"tx_ref":''+str(math.floor(1000000 + random.random()*9000000)),
"amount":amount,
"currency":"KES",
"redirect_url":"http://localhost:8000/callback",
"payment_options":"card",
"meta":{
"consumer_id":23,
"consumer_mac":"92a3-912ba-1192a"
},
"customer":{
"email":email,
"phonenumber":phone,
"name":name
},
"customizations":{
"title":"WASU Scholarship 2022",
"description":"Best store in town",
"logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg"
}
}
url = ' https://api.flutterwave.com/v3/payments'
response = requests.post(url, json=data, headers=hed)
response=response.json()
link=response['data']['link']
return link
My payment Response View:
#require_http_methods(['GET', 'POST'])
def payment_response(request):
status=request.GET.get('status', None)
tx_ref=request.GET.get('tx_ref', None)
print(status)
print(tx_ref)
return HttpResponse('Finished')
Anticipating your prompt answers. Thanks
Related
I have a django project for student marks.
Models.py
class Registration(CMTracking):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE)
school = models.ForeignKey(School, on_delete=models.CASCADE)
grade = models.CharField(max_length=5, choices=Grade.choices)
school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True)
last_year_result = models.PositiveSmallIntegerField(choices=RESULT.choices, blank=True, null=True)
last_grade = models.CharField(max_length=5, choices=Grade.choices, null=True)
date_of_join = models.DateField(null=True, blank=True)
type_of_registration = models.PositiveSmallIntegerField(choices=TypeOfRegistration.choices, default=0, null=True)
type_of_attendance = models.PositiveSmallIntegerField(choices=TypeOfAttendance.choices, null=True)
transfer_from = models.PositiveSmallIntegerField(choices=TransferFrom.choices, blank=True, default=1)
status = models.PositiveSmallIntegerField(choices=RequestStatus.choices, default=0)
class Exam(CMTracking):
fa_name = models.CharField(max_length=70, null=False)
en_name = models.CharField(max_length=70, null=False)
ar_name = models.CharField(max_length=70, null=False)
total_mark = models.DecimalField(max_digits=5, decimal_places=2, default=0)
exam_type = models.PositiveSmallIntegerField(choices=ExamType.choices)
academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE)
class ExamSubject(CMTracking):
exam = models.ForeignKey(to=Exam, on_delete=models.CASCADE)
subject = models.ForeignKey(to=SubjectMaster, on_delete=models.CASCADE)
teacher = models.ForeignKey(Staff, related_name='ExamSubjectList', on_delete=models.CASCADE) # Namavar
school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True)
min = models.PositiveSmallIntegerField(null=True)
max = models.PositiveSmallIntegerField(null=True)
class MarkDescriptive(CMTracking):
subject = models.ForeignKey(ExamSubject, on_delete=models.CASCADE)
student = models.ForeignKey(Registration, related_name='mark_list_descriptive', on_delete=models.CASCADE)
goal = models.ForeignKey(to=SubjectGoalsMaster, on_delete=models.CASCADE)
point = models.FloatField(null=True, blank=True)
t2point = models.FloatField(null=True, blank=True)
forms.py:
class MarkDescriptiveModelForm2(forms.ModelForm):
student = forms.ModelChoiceField(queryset=Registration.objects.all().select_related('student__person').filter(school_id=106), required=False)
# student = forms.IntegerField() # only shows the id
goal = forms.ModelChoiceField(queryset=SubjectGoalsMaster.objects.all(), required=False)
point = forms.ChoiceField(choices=DescriptivePoint5.choices)
t2point = forms.ChoiceField(choices=DescriptivePoint5.choices)
class Meta:
model = MarkDescriptive
fields = ['id', 'student', 'point', 't2point']
Views.py:
#login_required()
#require_http_methods(['POST', 'GET', 'PUT'])
def mark_descriptive_update(request, exam_subject_id=None, goal_id=None):
subject = get_object_or_404(ExamSubject, id=exam_subject_id)
goal = get_object_or_404(SubjectGoalsMaster, id=goal_id)
MarkFormset = modelformset_factory(MarkDescriptive, form=MarkDescriptiveModelForm2, extra=0)
marks = subject.markdescriptive_set.all().select_related('subject__exam') \
.select_related('student__academic_year') \
.select_related('student__student__person') \
.select_related('goal').select_related('subject__subject').filter(goal=goal)
formset = MarkFormset(request.POST or None, queryset=marks)
add_url = reverse('add-class')
template = 'school/loaders/load_form.html'
form_template = 'school/pages/exam/mark_descriptive/formset.html'
context = {
# 'form': form,
'records': marks,
'subject': subject,
'goal': goal,
'formset': formset,
'template': template, 'form_template': form_template, 'add_url': add_url}
# if request.method == 'PUT':
if request.method == 'POST':
print(f'\n\n\nrequest is {request.method}\n')
print(f'formset data:{formset.data}')
if formset.is_valid():
print('formset is valid')
for form in formset:
updated_mark = form.save(commit=False)
updated_mark.subject = subject
updated_mark.goal = goal
updated_mark.modified_by = request.user
updated_mark.last_modified = datetime.now()
updated_mark.save()
print('*** \n Marks added succefully !\n***')
else:
print(' form not valid', formset.errors)
return render(request, form_template, context)
issue ::
student = forms.ModelChoiceField(queryset=Registration.objects.all().select_related('student__person').filter(school_id=106), required=False)
Takes too long to load student details I tried to override the form to get only students that are in the same exam but couldn't do that. and overall I do not need at all the student field to be as selection. a normal label of student name is totally enough as the data already populated and teacher will only enter the point.
I am trying to integrate a payment system in my Django project and I models for profile, and submitted.
The issue is that I want a situation where when a user clicks on pay button the system should check whether he/she has submitted application and if so; grab the username, email, phone, amount and pass them as arguments into my process_payment view where the payment is going to be done.
here is code for Profile model:
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=16, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
here is code for Scholarship model:
class Submitted(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
approved = models.CharField(max_length=20, null=True)
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
Here is my view code:
#login_required(login_url='user-login')
def scholarship_detail(request, pk):
data = Scholarship.objects.get(id=pk)
if request.method=='POST':
applicant= request.user
email = 'henry#gmail.com'
amount = 2
phone = 8034567
return redirect(str(process_payment(applicant,email,amount,phone)))
else:
form = PaymentForm()
ctx={
'scholarship':data
}
return render(request, 'user/scholarship.html', ctx)
How can this logic be implemented efficiently because my trial is saying process_payment() missing 3 required positional arguments: 'email', 'amount', and 'phone'. Thanks for your answer
You should add the process_payment parameters to a dictionary(context) and return process_payment. then all other operations will happen inside process_payment
#login_required(login_url='user-login')
def scholarship_detail(request, pk):
data = Scholarship.objects.get(id=pk)
if request.method=='POST':
applicant= request.user
email = 'henry#gmail.com'
amount = 2
phone = 8034567
context = {'applicant':applicant, 'email':email, 'amount':amount, phone} # Add to context. this will grab all the details into `process_payment` view
return process_payment(request, context)
else:
form = PaymentForm()
ctx={
'scholarship':data
}
return render(request, 'user/scholarship.html', ctx)
process_payment view or function will look similar to:
def process_payment(request, newContext={}):
print(newContext)
# Process the payment here
return render(request, 'payment.html', newContext)
This should do the trick, but let me know if you have more questions
I am work on a Django Project where I have Profile and submited_apps models. The profile model holds details such as applicant, nation, state, phone etc whereas the submited_apps models only records the users whose application were submitted successfully with a applicant field, Universal Unique International Id and date.
How do I have a dependent search form for nation and state and be able to search submited_apps model for selected nation, state and display the result in pagination.
Profile Model Code below
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=11, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
Submitted Model Code below"
class submited_apps(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
ModelForm code below:
class Applicant_Search_Form(forms.ModelForm):
class Meta:
model = submited_apps
fields = ['applicant']
Here is my view for the search
def SearchApplicants(request):
context = {}
searchForm = Applicant_Search_Form(request.POST or None)
if searchForm:
list_applicants = submited_apps.objects.filter(applicant__iexact=[searchForm['applicant'].value()])
else:
list_applicants= submited_apps.objects.all()
paginator = Paginator(list_applicants, 5)
page = request.GET.get('page')
paged_listApps = paginator.get_page(page)
context.update({
'list_applicants':paged_listApps,
'searchForm':searchForm,
})
return render(request, 'user/search_applicants_nation.html',context)
My problem is that I am getting this error message upon load of the plage.
Related Field got invalid lookup: icontains
I'm have been struggling on this for 2 days, really. I want to populate Timesheet form field from Employees model as a select field / dropdown list.
Here are my files and I tried so far.
MODEL.PY
class Employees(models.Model):
# MONTHLY = 'MONTHLY'
# SEMIMONTHLY = 'SEMIMONTHLY'
# BIWKEEKLY = 'BIWKEEKLY'
# WEEKLY = 'WEEKLY'
# DAILY = 'DAILY'
PAY_PERIODS = [
('Monthly', 'Monthly'),
('Bi-weekly', 'Bi-weekly'),
('Weekly', 'Weekly'),
('Daily', 'Daily'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
is_active = models.BooleanField(default=True, verbose_name='Employee is actives')
first_name = models.CharField(max_length=50, verbose_name='First Name.', null=True, blank=False)
middle_name = models.CharField(max_length=50, verbose_name='Middle Name or Initials.', null=True, blank=True)
last_name = models.CharField(max_length=50, verbose_name='Last Name.', null=True, blank=False)
full_name = models.CharField(max_length=50, null=True, blank=True)
phone = PhoneField(blank=True, null=True)
email = models.EmailField(max_length=150, blank=True, null=True)
state = USStateField(null=True, blank=True)
street_address = models.CharField(max_length=150, blank=True, null=True, verbose_name='Street Address.')
zip_code = models.CharField(max_length=50, blank=True, null=True, verbose_name='Zip Code.')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
pay_frequency = models.CharField(max_length=100, choices=PAY_PERIODS, blank=True)
hire_date = models.TimeField(auto_now_add=True)
def __str__(self):
return self.full_name
def save( self, *args, **kwargs ):
self.full_name = f'{self.first_name} {self.middle_name} {self.last_name}'
super().save( *args, **kwargs )
class Timesheet(models.Model):
"""A timesheet is used to collet the clock-ins/outs for a particular day
"""
employer = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
full_name = models.ForeignKey(Employees, on_delete=models.CASCADE, null=True, blank=False, verbose_name='Select YOUR Name')
start_date = models.DateField(auto_now_add=True, null=True)
end_date = models.DateField(null=True, blank=False)
time_worked = models.DateField(null=True, blank=False)
def __str__(self):
return self.full_name
VIEWS.PY # I tried both function and class based views
class TimesheetView(CreateView):
model = Timesheet
fields = ('full_name', )
# form_class = TimesheetFrom
# queryset = Employees.objects.filter()
# print(queryset)
template_name = 'users/timesheet.html'
success_url = reverse_lazy('timesheet')
#login_required
def timesheet_view(request):
if request.method == 'POST':
form = TimesheetFrom(request.POST)
if form.is_valid():
emp = form.save(commit=False)
emp.user_id = request.user.pk
emp.save()
return redirect('dashboard')
else:
form = TimesheetFrom()
context = {
'form': TimesheetFrom(),
}
return render(request, 'users/timesheet.html', context)
FORM.PY
class TimesheetFrom(forms.Form):
class Meta:
model = Timesheet
fields = '__all__'
exclude = ('employer', )
#This is the current state of the form but I did tried many approaches.
I did search extensively here (Stackoverflow) but no use case for me. Any help will be greatly appreciated with a cup of coffee.
I have a Django 'add business' view which adds a new business with an inline 'business_contact' form.
The form works fine, but I'm wondering how to write up the unit test - specifically, the 'postdata' to send to self.client.post(settings.BUSINESS_ADD_URL, postdata)
I've inspected the fields in my browser and tried adding post data with corresponding names, but I still get a 'ManagementForm data is missing or has been tampered with' error when run.
Anyone know of any resources for figuring out how to post inline data?
Relevant models, views & forms below if it helps. Lotsa thanks.
MODEL:
class Contact(models.Model):
""" Contact details for the representatives of each business """
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
business = models.ForeignKey('Business')
slug = models.SlugField(max_length=150, unique=True, help_text=settings.SLUG_HELPER_TEXT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
phone = models.CharField(max_length=100, null=True, blank=True)
mobile_phone = models.CharField(max_length=100, null=True, blank=True)
email = models.EmailField(null=True)
deleted = models.BooleanField(default=False)
class Meta:
db_table='business_contact'
def __unicode__(self):
return '%s %s' % (self.first_name, self.surname)
#models.permalink
def get_absolute_url(self):
return('business_contact', (), {'contact_slug': self.slug })
class Business(models.Model):
""" The business clients who you are selling products/services to """
business = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=100, unique=True, help_text=settings.SLUG_HELPER_TEXT)
description = models.TextField(null=True, blank=True)
primary_contact = models.ForeignKey('Contact', null=True, blank=True, related_name='primary_contact')
business_type = models.ForeignKey('BusinessType')
deleted = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
address_1 = models.CharField(max_length=255, null=True, blank=True)
address_2 = models.CharField(max_length=255, null=True, blank=True)
suburb = models.CharField(max_length=255, null=True, blank=True)
city = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=40, null=True, blank=True)
website = models.URLField(null=True, blank=True)
class Meta:
db_table = 'business'
def __unicode__(self):
return self.business
def get_absolute_url(self):
return '%s%s/' % (settings.BUSINESS_URL, self.slug)
VIEWS:
def business_add(request):
template_name = 'business/business_add.html'
if request.method == 'POST':
form = AddBusinessForm(request.POST)
if form.is_valid():
business = form.save(commit=False)
contact_formset = AddBusinessFormSet(request.POST, instance=business)
if contact_formset.is_valid():
business.save()
contact_formset.save()
contact = Contact.objects.get(id=business.id)
business.primary_contact = contact
business.save()
#return HttpResponse(help(contact))
#business.primary = contact.id
return HttpResponseRedirect(settings.BUSINESS_URL)
else:
contact_formset = AddBusinessFormSet(request.POST)
else:
form = AddBusinessForm()
contact_formset = AddBusinessFormSet(instance=Business())
return render_to_response(
template_name,
{
'form': form,
'contact_formset': contact_formset,
},
context_instance=RequestContext(request)
)
FORMS:
class AddBusinessForm(ModelForm):
class Meta:
model = Business
exclude = ['deleted','primary_contact',]
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ['deleted',]
AddBusinessFormSet = inlineformset_factory(Business,
Contact,
can_delete=False,
extra=1,
form=AddBusinessForm,
)
The problem is you have not included the management form in your data. You need to include form-TOTAL_FORMS (total number of forms in the formset, default is 2), form-INITIAL_FORMS (the initial number of forms in the formset, default is 0) and form-MAX_NUM_FORMS (the maximum number of forms in the formset, default is '').
See the Formset documentation for more information on the management form.