I am trying to get third button to work on a simple app I am making. I set up if statements to detect the value of the request for two buttons, but I am getting stuck on how to configure the logic statement to get a third parameter through.
My issue is that I need to have the form filled with any data before the subscriptions button will work properly. When the form is blank the app will indicate the form needs to be filled out. I am not familiar with javascript to have the buttons run from that. My hope is that I can learn how to configure the if statement to have the subscriptions call work without the form being filled out.
Below is the UI as and the views.py def. The Amount and Delete functions work fine. It is just the subscription button that won't work until I put literally any data into the two text fields fields.
def usage(request):
if request.method == 'POST':
form = UsageForm(request.POST)
if form.is_valid():
if request.POST.get('subscription') == 'Subscription':
dt = datetime.today()
month = dt.month
year = dt.year
day = calendar.monthrange(year, month)[1]
eom = str(month) + "/" + str(day) + "/" + str(year)
anchor = int(time.mktime(datetime.strptime(eom, "%m/%d/%Y").timetuple()) + 68400)
cust_list = json.loads(str(stripe.Customer.list(limit=100)))
for item in cust_list['data']:
try:
print(item['subscriptions']['data'][0]['id'], item['email'], item['id'])
except:
stripe.Subscription.create(
customer=item['id'],
items=[{'plan': 'plan_DFnNVzXKJ2w0Ad'}],
billing_cycle_anchor=anchor,
)
if request.POST.get('delete') == 'Delete':
cust_info = custinfo.objects.all()
cust_info.delete()
all_custinfo_items = custinfo.objects.all()
else:
Sub_ID = form.cleaned_data['Sub_ID']
amount = form.cleaned_data['amount']
stripe_data = stripe.SubscriptionItem.list(subscription=Sub_ID)
sub_item = stripe_data["data"][0]["id"]
stripe.UsageRecord.create(
quantity=amount,
timestamp=int(time.time()),
subscription_item=sub_item,
action='increment')
form.save()
print("Last Ran: ", Sub_ID, amount)
all_custinfo_items = custinfo.objects.all()
return render(request, 'form.html', {'form': form, 'custinfo_items': all_custinfo_items})
else:
form = UsageForm()
# all_subid_items = custinfo.objects.filter(Sub_ID__startswith='sub')
return render(request, 'form.html', {'form': form})
Related
Peace be upon all, I just started Django last month. I needed help running concurrency tests in Django, so what I've done is tried to write code that will prevent issues that arise due to lack of concurrency but what I don't know is how to verify and test the code to see that it meets my expectations. What I want is to send multiple requests at the same time to see if the code works as expected.
The target function in views.py
def buy_animal(request):
context = {}
if request.method == 'POST':
form = buys_animal(request.POST)
if form.is_valid() == True or form.is_valid() == False:
#return HttpResponse('asdasd')
nm = request.POST['an_name']
b = Animal.objects.filter(an_name = nm)
#return HttpResponse("yo ")
#nm = request.POST['an_name']
qt = int(request.POST['qty'])
if b.count() <= 0:
return HttpResponse(str(b.count()) + " Sorry we're out of animals")
else:
try:
with transaction.atomic():
b.select_for_update()
b = b[0]
#b.an_name = 'asd'
#b.save()
with transaction.atomic():
Quality.objects.filter( animal = Animal.objects.filter(an_name = 'ringneck')[0] ).select_for_update()
c = Quality.objects.filter( animal = Animal.objects.filter(an_name = 'ringneck')[0] )[0]
c.rating = 'niece'
c.save()
except:
return HttpResponse('Database Error')
if b.qty - qt < 0:
return HttpResponse("Sorry we don't have enough animals")
else:
b.qty = b.qty - qt
b.save()
a = Buy_animal( an_name = nm, qty = qt,
buyer = MyUser.objects.filter(username = request.user.username)[0] )
a.save()
return HttpResponse('animal bought')
else :
form = buys_animal()
context = {}
context = {'form' : form}
return render(request, "buy_animal_form.html", context)
else :
form = buys_animal()
context = {}
context = {'form' : form}
return render(request, "buy_animal_form.html", context)
My models.py code can be found in the below repository
https://bitbucket.org/mab_786/django_models_code/src/master/models.py
`
Kindly ignore any stupid errors on my part as I just started with django.
Thanks in advance. I would really appreciate if someone could share the tests.py code to test such a situation. I didn't write this code as part of any project but to clear up my concepts
i am trying to set the form initials for the sender field as the logged in user, and it does not show. i removed the if request method statement and adjusted the indentaion and the initials showed. I am stuck, i believe the form is supposed to have that request method statement. i've gone through the documentation and it says the post method binds the data and submits, but there isn't any data when the page is refreshed or newly loaded. what could be wrong?
views.py
def transfer(request):
profile = Profile.objects.get(user=request.user)
if request.method == "POST":
form = TransferForm(request.POST,initial={"sender": profile})
if form.is_valid():
print(form)
form.save()
sender = models.sendcoins.objects.get(sender=request.user.profile)
profile2 = Profile.objects.get(username=receiver)
user_wallet = wallet.objects.get(owner=profile)
print(receiver)
temp = sender # NOTE: Delete this instance once money transfer is done
receiver = models.wallet.objects.get(owner=profile2) # FIELD 1
transfer_amount = sender.amount # FIELD 2
sender = models.wallet.objects.get(owner=profile) # FIELD 3
# Now transfer the money!
sender.balance = sender.balance - transfer_amount
receiver.balance = receiver.balance + transfer_amount
# Save the changes before redirecting
sender.save()
receiver.save()
temp.delete() # NOTE: Now deleting the instance for future money transactions
else:
return(HttpResponse("form is not valid"))
else:
form = TransferForm()
return render(request, "sendcoins.html", {"form": form})
I am trying to increment my DB by 1 if a user has not visited that unique item.pk before. At the moment it will only increment by 1 for all items in my DB, id like to to increment by 1 for each item.pk in the DB.
The view is to Create a view that returns a single bug object based on the bug ID (pk) and render it to the bug_detail.html template or return 404 error if object is not found Also handles commenting on the bug as well as regulating the amount of views attributed to the bug.
def bug_detail(request, pk):
bug = get_object_or_404(Bug, pk=pk)
if request.method == "POST":
form = BugCommentForm(request.POST)
if form.is_valid():
bugComment = form.save(commit=False)
bugComment.bug = bug
bugComment.author = request.user
bug.comment_number += 1
bug.save()
bugComment.save()
return redirect(reverse('bug_detail', kwargs={'pk': pk}))
else:
messages.error(
request,
"Looks like your comment is empty!",
extra_tags="alert-danger")
form = BugCommentForm(instance=bug)
return redirect(reverse('bug_detail', kwargs={'pk': pk}))
else:
form = BugCommentForm()
comments = BugComment.objects.filter(bug__pk=bug.pk)
comments_total = len(comments)
response = render(request,
'bug_detail.html',
{'bug': bug,
'comments': comments,
'comments_total': comments_total,
'form': form})
if 'last_visit' in request.COOKIES and 'bugg' in request.COOKIES:
last_visit = request.COOKIES['last_visit']
# the cookie is a string - convert back to a datetime type
last_visit_time = datetime.strptime(
last_visit[:-7], "%Y-%m-%d %H:%M:%S")
curr_time = datetime.now()
if (curr_time - last_visit_time).days > 0:
# if at least one day has gone by then inc the views count.
response.set_cookie('last_visit', datetime.now())
bug.views += 1
bug.save()
elif 'bugg' not in request.COOKIES:
response.set_cookie('last_visit', datetime.now())
response.set_cookie('bugg', bug.pk)
bug.views += 1
bug.save()
else:
response.set_cookie('last_visit', datetime.now())
response.set_cookie('bugg', bug.pk)
bug.views += 1
bug.save()
return response
I'm trying to create a confirmation page. User can create orders on one page, then the create_order view validates the forms and send a request with context to another view which is called confirm_order. I think that I would work correct but there is one problem. The first time confirm_order gets request and context which contains data from forms. But when User clicks on confirm in this page, the confirm_view is called without this context so I'm getting error:
> ValidationError at /create-job/ [u'ManagementForm data is missing or
> has been tampered with']
Do you guys know how to send the context second time?
Here are those two views:
def create_order(request):
LanguageLevelFormSet = formset_factory(LanguageLevelForm, extra=5, max_num=5)
language_level_formset = LanguageLevelFormSet(request.POST or None)
job_creation_form = JobCreationForm(request.POST or None, request.FILES or None)
context = {'job_creation_form': job_creation_form,
'formset': language_level_formset}
if request.method == 'POST':
if job_creation_form.is_valid() and language_level_formset.is_valid():
cleaned_data_job_creation_form = job_creation_form.cleaned_data
cleaned_data_language_level_formset = language_level_formset.cleaned_data
context = {
'cleaned_data_job_creation_form': cleaned_data_job_creation_form,
"cleaned_data_language_level_formset": cleaned_data_language_level_formset,
}
mutable = request.POST._mutable # I'm adding parameter 'review' to be able to differ between two different posts in confirm_order view
request.POST._mutable = True
request.POST['review'] = True
request.POST._mutable = mutable
return confirm_order(request, context)
else:
return render(request, 'auth/jobs/create-job.html', context=context)
return render(request, 'auth/jobs/create-job.html', context=context)
def confirm_order(request, context):
print context
cleaned_data_job_creation_form = context['cleaned_data_job_creation_form']
cleaned_data_language_level_formset = context['cleaned_data_language_level_formset']
print request.POST['review']
if request.method == 'POST' and request.POST['review'] == True:
file = cleaned_data_job_creation_form['file']
count = 5 #simplified multiple rows
jobs = []
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
d = {}
d['language_from'] = cleaned_data_job_creation_form['language_from'].name
d['language_to'] = language
d['number_of_characters'] = count
d['price_per_sign'] = 1
d['estimated_price'] = count * d['price_per_sign']
jobs.append(d)
table = CreatedOrdersTable(jobs)
context = {'table': table,
'cleaned_data_job_creation_form': cleaned_data_job_creation_form,
'cleaned_data_language_level_formset': cleaned_data_language_level_formset}
return render(request, 'auth/jobs/confirm-order.html', context=context)
else:
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
Job.objects.create(
customer=request.user,
text_to_translate=cleaned_data_job_creation_form['text_to_translate'],
file=cleaned_data_job_creation_form['file'],
short_description=cleaned_data_job_creation_form['short_description'],
notes=cleaned_data_job_creation_form['notes'],
language_from=cleaned_data_job_creation_form['language_from'],
language_to=language,
level=level,
)
return HttpResponseRedirect('/order-success')
You are returning a template render on your first view. So, the request doesn't end on your confirm_order view.
If you want, you can redirect to reverse('confirm_order') and add the data on session.
In your confirm_order view you will pop the data from session and continue with your flow.
I have the following view:
def process(request):
if request.method == 'POST':
data = request.POST
results = Specs.objects.filter(screenGroup = data['screen_user'], storage = data['storage_user'], mSystem = data['system_user'] )
context = {'results' : results}
return render(request, 'process.html', context)
When the user inputs the three values it filters correctly, but when it just inputs one or two (or nothing), then it filters passing the value None. Is there any way to ignore the filter if it's not set?
Thanks!
EDIT:
The following code is working, but it's obviously a very unefficient way:
def process(request):
if request.method == 'POST':
data = request.POST
if(data['screen_user'] != None):
results = Specs.objects.filter(screenGroup = data['screen_user'])
elif (data['storage_user'] != None):
results = Specs.objects.filter(storage = data['storage_user'])
else:
results = Specs.objects.all()
#plus all the other options...
context = {'results' : results}
return render(request, 'process.html', context)
You can build the filter beforehand:
def process(request):
if request.method == 'POST':
data = request.POST
spec_filter = {}
for attribute in ['screenGroup', 'storage', 'mSystem']:
if attribute in data and data[attribute]:
spec_filter[attribute] = data[attribute]
results = Specs.objects.filter(**spec_filter)
context = {'results' : results}
return render(request, 'process.html', context)
NB: To use this verbatim you would have to change the names of the variables being passed in the request.POST to match those in the Specs model. I did this just to illustrate, but you can easily use the same principle with your variable names. In that case you'll have to be a bit more verbose.
It's called validating your form.. There are two ways of doing this:
create a django form and use myform.is_valid(). You can read about it in the docs
validate it yourself with a few 'if' statements (either on server side or with javascript before sending the ajax call)