Let's say I have a form for a booking system based on a one-to-many relations with the visitors table..as in the attached image, I'm trying to implement a "Find" function linked to the visitor passport table so we don't need to re-enter the visitors data again. abasically we can enter the passport number and run a query so if his data is there it will come back and fil the form, otherwise we have to reenter it manually using a different form.
The following JS function will query the visitor table by passport # and bring back data correctly. However I don't know how to fill out the booking form with the new data so it can be saved, because the data I get is in html format as a table. In my real case, I need to save two fields only from the returned data including the passport number in the booking form, so how I extract the passport # from the returned data, or maybe there is a better way to do so.
function visitor_details(pass_num){
url = 'booking_vis_details'
$.ajax({
type: "GET",
url : url,
data: {
num: pass_num,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function(data) {
$('#table_details').html(data);
}
})
}
View:
def booking_vis_details(request):
num = request.GET.get('num')
data = Visitor.objects.get(passport_num=num)
if not data: data = []
return render(request, 'booking_form/booking_vis_details.html', {'form': data})
Related
I have a django app where users can save their contacts. I am not building a flow to allow users to download their contacts locally.
To do so, I built a CTA ("download") that if clicked
Gets the id of the contact selected
Triggers an Ajax request to my views
In the view I get the contact id, retrieve the data from my DB and create a VCF card out of it. (A contact card - basically a text file)
Now I would like to have such file downloaded on the client's machine but I don't know how to do it.
I managed to do it if I redirect to a new url where the view does exactly what my view below does, I want to allow users to download the file without being redirected to a new page. Also, trying to avoid storing the contact ids in the URL.
That's why I am trying to use ajax but I think that's creating problems because and Ajax request waits JsonReponse from the view.
I tried both a GET or POST but it's not working.
This is my view currently:
def get(self, request, *args, **kwargs):
#Get the ids
ids = request.GET.getlist('contact_ids[]')
# Get contqacts associated with ids
contacts = Contact.objects.filter(id__in=ids)
# Transform contacts into long text
text = Vcard().GroupVcards(contacts)
#Create file on the fly and attach it to the response (is this correct actually?)
response = HttpResponse(content_type='text/plain')
response['Content-Disposition'] = 'attachment;filename=ven.vcf'
response.writelines(text)
#return
return response
This is the Jquery triggering the ajax
$('.Vcard').on('click', function(e) {
let id = $(this).data('contact_id')
$.ajax({
type: "GET",
url: Urls['action:DownloadContact'](),
data: {
csrfmiddlewaretoken: csrftoken,
'contact_ids': [id],
},
error: function(response){
console.log(response)
console.log('error')
},
success: function(response) {
console.log(response)
console.log('success')
}
});
})
I'm trying to achieve following tasks in Django:
First page: User fills a large Job application form and that data is
sent to Second page
Second page: User reviews his previously filled data and proceeds to third page
Third page: User pays the amount(came from Second page) and once paid, then only all this data is saved to DB.
I've done First page work of filling form and then sending that data to Second page.
Here's my views.py
def applyJob(request,id=None):
job = get_object_or_404(AddJob, id=id)
if request.method == 'POST':
context = {
'jobName': job.jobName,
'jobID' : job.pk,
'cfName' : request.POST.get('candidateFirstName'),
'cmName' : request.POST.get('candidateMiddleName'),
'clName' : request.POST.get('candidateLastName'),
......
return render(request,'reviewAppliedJob.html',context)
else:
context ={
"jobName": job.jobName,
"id": id,
}
return render(request,'applyJob.html',context)
Since I'm sending the context data using return render(request,'reviewAppliedJob.html',context), URL is not changing and so it's not going to my reviewAppliedJob views and so I cannot write code to go to Third page.
def reviewAppliedJob(request):
return HttpResponse('done....')
For that, I can use HttpResponseRedirect('/reviewAppliedJob') instead of render in applyJob() but it will not send my context data. Django allows sending context either using render(), messages framework, url params or session. But since I have large amount of data, I don't know which one to use and will work perfectly.
What's the best way to achieve this task efficiently and securely?
Thanks in advance.
I suggest you use sessions instead. Instead of writing three individual views you can write one. After user fills the data, save them in a session key with a phase key temporarily. In this way, when the view is processed you can access to data and phase of the user.
I'm trying to integrate Stripe Checkout to have the customer pay when submitting the form. This integration redirects the customer to Stripe's page to do the payment. How can I make Django remember the input values from the Form after the payment is submitted on the redirected page? Can I create a custom URL that remembers the values?
Also their script requires a payment ID which I serve through a variable but this variable is first created once the form is submitted. I can't change a javascript variable dynamically once the page is rendered, right?
Javascript
<script>
stripe.redirectToCheckout({
sessionId: "{{context}}",
}).then(function (result) {
// Diplay result.error.message to your customer
});
</script>
Python code to create the payment which is called after form submission
stripeUID = str(uuid.uuid4())
payment = stripe.checkout.Session.create(
success_url="https://mypage.com/succes",
cancel_url="https://mypage.com/error",
payment_method_types=["card"],
client_reference_id= stripeUID,
line_items=[
{
"amount": 2000242,
"quantity": 1,
"name": "Blender rendering",
"currency": "usd",
}
]
)
context = payment.id
For the payment ID, use AJAX. Submit the form with Javascript, and in the AJAX response serve the payment ID. then you can use it in the redirect. As for the redirect, you will need to create a model to store the form value against stripe session ID, so when your customer gets redirect back to your website, u can query the table with the session ID to get their original form values.
AJAX calls can be done by using fetch, XMLHttpRequest, jQuery.ajax
I have a working python code on my desktop that prints and makes PDFs perfectly. All I want to do is use that code and use Django to allow users to enter a value.
My code uses docusign API to call data. I use postman which needs a key and other parameters to use the API. The value entered by my user will determine what data they get.
What I think I have to do is rewrite my code, put it somewhere, then turn it into a view. The view will be sent to template.
Edit -
My code:
# Get Envelope Data- use account ID from above
# Get Todays Date, Daily Setting
day = datetime.datetime.today().strftime('%Y-%m-%d')
url = "https://demo.docusign.net/restapi/v2/accounts/" + accountId + "/envelopes"
# if Envelope is completed
querystring = {"from_date": Date, "status": "completed"}
headers = {
'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}",
'Content-Type': "application/json",
'Cache-Control': "no-cache",
'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211"
}
response = requests.request("GET", url, headers=headers, params=querystring)
envelopes = response.text
Sorry, let me try again. I currently have a python3 program on my desktop. I run it with idle and everything is how I want it.
What I want to do with Django is use this code to print its outputs on a webpage and have the user download it’s additional csv file output. I have managed to make a Django localhost and I am stuck at that point. I do not know how to use my python3 code to run to webpage.
The code is made up of API calls, I use postman to help me with sending the right parameters. I will add a picture of code. All I want is for user to enter value such as accountID so that the API can complete the request and give them data for their own request.
I'll try to give you a overview of how this could work with Django.
You could have a form to obtain the users account_id.
class AccountForm(forms.Form):
account_id = forms.IntegerField()
You could display this form through a generic FormView (see also this):
class AccountView(views.FormView):
form_class = AccountForm
template_name = 'account.html'
def form_valid(self, form):
# here you make your request to the external API
account_id = form.cleaned_data['account_id']
url = "https://demo.docusign.net/restapi/v2/accounts/" + account_id + "/envelopes"
headers = ...
querystring = ...
resp = requests.request("GET", url, headers=headers, params=querystring)
ctx = {
'result': resp.text,
}
return render(self.request, 'result.html', ctx)
I don't show the template account.html here. You will have to figure that one out yourself; the links I provided should point you in the right direction.
Now, what remains to be determined is what exactly the method form_valid should return. The code I showed renders a template with the API call response in the context, so in your template result.html you could display the result data any way you like.
You mentioned downloading a CSV file as well. That could be a different view, probably triggered by a link or button in result.html.
I simply don't know how to do it.
I have an html linked with a knew url, with two buttons.
imagine that url is only shared with two persons/users.
each person have to push the button signed their name.
I tried using request, but I couldn't figure out how to know if more than one user is active in that view.
The another point is:
One person reach the url first, how to make an "refresh" in their browser, when the second one appear?
You'd have to store who's at what view in some model.
class UsersInURL(models.Model):
users = models.ManyToManyField(User)
url = models.CharField()
# you'd probably want to use a through table and set up some expiration logic
Then remember to modify this model every time a logged in user views a page; middleware sounds perfect for this.
class UserTrackerMiddleware(object):
def process_view(self, request, *args, **kwargs):
UsersInURL.users.through.filter(user=request.user).delete()
users_in_url, created = UsersInURL.objects.get_or_create(url=request.path)
users_in_url.users.add(request.user)
Then to refresh their page, you'd need to set some kind of communication between the server and the browser which pings this model and refreshes if it detects some change.
var lastCheckedUsers = undefined;
function checkForNewUsers() {
$.get('/some-ajaxy-url/', { url: document.URL }, success: function(data) {
// you'd have to set up a view that returns active users # url
if (lastCheckedUsers != data.users && lastCheckedUsers != undefined) {
window.location.href = window.location.href;
};
lastCheckedUsers = data.users; // store last state; refresh if modified.
})
};
setInterval(checkForNewUsers, 1000);
I'm sure that should get some ideas flowing.