Getting dropdown value from template django - django

I am facing an issue working with django ( using shopcart ). I want to add a select options field to change dynamically an item suscription in the cart, but I am not getting the value selected from the template.
In my template where I display the cart I have :
<form action="" method="GET">{%csrf_token%}
<select name="suscr" title="suscr">
<option value="" selected>Suscribe</option>
<option value="1" name="suscr" >Weekly</option>
<option value="2" name="suscr">Monthly</option>
</select>
</form>
I want to select an option and then, if I press 'Checkout' to have the cart updated.
Appart from that, I believe its missing a method modifying the item in cart.py.
Any ideas would help.
Thanks
The above form is inside a loop
{% for item in cart %}

What i propose you to do is not python-oriented but all javascript for the most part as, from the description, we assume that what you are dealing with is going all at the client-side.
As you are dealing with a shopping cart, what i'd do is storing what the user is checking in a sessionStorage so that the information would persist while the user navigates through your website even with multiple tabs. As the user might just be "walking around" you shopping website, there's no need to push things to the database without even knowing if the user wants that. Just remove the form and keep with the select, then you get what the user selected appending an attribute to select: <select onchange=my_function(this.value)>...</select> and then, inside my_functionin a script change whatever you want to the page.
When the user enters the shopping cart page you show him what he selected so far getting the items from the sessionStorageand then, if he/she confirms that wants to buy, then submit a form to the server-side, update the database and proccess that as your workflow states.
tl;dr: store the options in sessionStorage, just post to the server at the end.
For help on the server-side update your question with more info about the cart.py

Related

django redirect after post with post parameters after update

I was looking for help but couldn't find any suitable solution.
I would like to ask about redirect after POST.
Situation looks as below step by step:
Simple search form with POST with parameter called 'find' within form. Search form appears on every site and if i call search on site with devices i'm checking referrer and i'm doing query for device model fields and results go to devices.html template. Same situation is when I search within localization site, checking for referrer and querying for model fields of localization model and returning query result in localization.html template.
When I try to update device i'm opening new edit device template with url '/edit/device/dev_id' when every field of this model is shown so i can update some fields manually.
After commiting changes on edit site device 'post' goes to url 'update/device/dev_id' and changes to device are saved properly.
The problem is how can I redirect after updating device to step number one where are the results of search view for devices?
If i redirect after update ('update/device/dev_id') device to 'request.META.get('HTTP_REFERER')' i'm getting 'edit/device/dev_id' url ?
Worth to mention is that method POST for search form sends text search input to action="/search" and then after checking referrer shows results, so there is nothing like 'action="search/find".
I know that in web browser we can do few times previous click to show search results incuding POST parameters but it is not the point.
If you have any ideas how to redirect to search results (method POST, 1 point) after updating please let me know.
Regards AD
I will try to simplify the question ( too much code to paste ):
Given search below in template:
<form class="navbar-form navbar-left" action="/search" method="post">{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name="find" placeholder="Search">
</div>
<button type="submit" class="btn btn-default" >Search</button>
</form>
in views.py:
def search_dev(request):
to_find=request.POST.get('find')
(..)
<--query updating_fields in instance considering only 1 search result-->
redirect ? (to search query with POST )
Is it possible to go back to search results after some changes to instance ( for example update ) considering only 1 search result ?

amp-form session based backend and 3rd party cookies

Trying to grok this e-commerce scenario...
I build an amp product page in amp that has the new amp-form
The add to cart button is an XHR to my backend (that is session based, using
cookies by default)
User searches for product and results take them
to my amp product page, but they've never been to my site
They submit the add to cart form
the CORS preflight makes it's way to my backend, and i set all the correct allows as per https://github.com/ampproject/amphtml/blob/master/spec/amp-cors-requests.md
Now the actual request is made... backend initializes a session,
returns session identifier as a cookie, but since user never went to
my site...just the google amp cache it's treated as a 3rd party
cookie and browser discards it (cause user disables 3rd party cookies)
users session is lost, as is their add to cart action
So the question is, how do i keep the session around and the item in the cart?
Am i missing something? is there a trick i'm not seeing?
appreciate any insights.
Associating the shopping cart with the CLIENT_ID would be the best way to solve this problem. Unfortunately, transferring the CLIENT_ID via forms is not yet supported in AMP. It's currently being implemented, you can watch this issue for the current status.
Here is an approach that works right now: the idea is to encode the shopping cart content into a string that is returned in the form result. This way we can generate "View Cart" and "Checkout" links including the shopping cart content. Once the user clicks on one of those links, you can create the actual shopping cart in your backend and store the user id in a cookie.
For example:
<form action-xhr="/add-to-cart" method="POST">
<input type="hidden" name="itemId" value="headphones-123">
<!-- Hide after form submit success -->
<input type="submit" name="add" value="Add to Cart">
<div submit-success>
<template type="amp-mustache">
<!-- shopping cart contents, e.g headphones-123 -->
{#shoppingCartContent}
View In Cart
Checkout
{/shoppingCartContent}
</template>
</div>
<div submit-error>
<template type="amp-mustache">
{{message}} <!-- e.g. Only 2 Headphones are left. -->
</template>
</div>
</form>
The disadvantage of this approach is that the shopping cart will be lost when the user leaves the page without viewing the cart first. This will be solved once the CLIENT_ID can be passed via amp-form.
I also know very limited info about AMP pages but I suggest that you please read through the use of User identification and try using an AMP-generated client ID. As mentioned in the documentation:
By default, AMP will manage the provision of a client ID whether the page is accessed from the publisher's original website or through a cache.
Likewise, learn more about client ID substitution, including how to add an optional user notification ID, in Variables supported in AMP analytics.
Hope that helps!

Django redirect page does not update the view

I'm using the Django Framework on Google App Engine.
I have multiple forms on the same view, to submit to different URL.
Trouble is after I get a form submitted: even if the called method update the datastore and some data, the previous page (where the forms are put in) is not refreshed, showing the updated data.
I could solve this problem using jQuery or some javascrip framework, appending dinamically content returned by the server but, how to avoid it?
Suggestions?
Am I wrong somewhere?
A part of "secure.html" template
<form action="/addMatch" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Matches:
<br />
{% for m in matches%}
{{m.description}} ---> {{m.reward}}
{% endfor%}
the "/addMatch" URL view:
def addMatch(request):
form = MatchForm(request.POST)
if form.is_valid():
user = User.all().filter('facebookId =', int(request.session["pbusr"]))
m = Match(user=user.get(),description =form.cleaned_data["description"],reward=form.cleaned_data["reward"])
m.save()
return HttpResponseRedirect("/secure/")
else:
logging.info("Not valid")
return HttpResponseRedirect("/secure")
The view method whose seems not working:
#auth_check_is_admin
def secure(request):
model={}
user = User.all().filter('facebookId =', int(request.session["pbusr"]))
u = user.get()
if (u.facebookFanPageId is not None and not u.facebookFanPageId == ""):
model["fanPageName"] = u.facebookFanPageName
model["form"] = MatchForm()
model["matches"] = u.matches
else:
....
return render(request,"secure.html",model)
Francesco
Based on what you posted, it seems like you're redirecting properly and are having database consistency issues. One way to test this would be to look at the network tab in the Google Chrome developer tools:
Click on the menu icon in the upper right
Click on "Tools"
Click on "Developer Tools"
Click on "Network" in the thing that opened up at the bottom of the screen.
Now, there will be a new entry in the network tab for every request that your browser sends and every response it receives. If you click on a request, you can see the data that was sent and received. If you need to see requests across different pages, you might want to check the "Preserve log" box.
With the network tab open, go to your page and submit the form. By looking at the network tab, you should be able to tell whether or not your browser issued a new GET request to the same URL. If there is a new request for the same page but that request has the old content, then you have a datastore consistency issue. If there was NOT a new request that yielded a response with the data for the page, then you have a redirect issue.
If it turns out that you have a datastore consistency issue, then what's happening is the data is being stored, but the next request for that data might still get the old data. To make sure that doesn't happen, you need what's called "strong consistency."
In a normal App Engine project, you get strong consistency by putting entities in the same entity-group and using ancestor queries. I'm not certain of what database/datastore you're using for Django and how the different database layers interact with App Engine's consistency, so this could be wrong, but if you can give your users the right key and then fetch them from that key directly (rather than getting all users and filtering them by key), you might get strong consistency.

How i can create user alerts in Django?

Subj
Several limitations:
Warnings should be specific to each user.
Alerts can also contain links and HTML form (the simplest form
with empty action ="").
Table of Contents Alerts should be dynamic, since it must be
current at all times.
Types of alerts can be extensible.
It remains only to consider how to store it in a database, and generate and transmit to the template.
Examples of alerts:
User <a href="/accounts/64/profile/"> Vlad </ a> commented on your
forum <a href="/forum/topic/54/"> Topic </ a>.
User <a href="/accounts/64/profile/"> Vlad </ a> added to your account to your favorites.
User <a href="/accounts/64/profile/"> Vlad </ a> asks if you add to your favorites.
<form action="" method="POST">
<input type="submit" value="Ok">
<input type="submit" value="No">
</ form>
Anybody can explain how to store it in a database, and generate and transmit to the template?
Sorry for my Engl
You could use, or build on, the Django Messages Framework.
I think you will need to create one more table, where you will keep data about the user who will recieve alert, user who will send alert and template name, where you will keep alert (so you will need to include it in your main template). Also, you will need one or more boolean fields for flagging this alerts.
So, every time user log in or change page you will check this table and show alerts. If there any, you'll display alert block and put flag into False. So, I think you will need more flags, because one flag will check views of this alert, other will check user answer (like last one form) and so on.
I think you should use django-alerts library for Send alerts, notifications, and messages based on events (signals) in your django application
installation of alerts
pip install django-alert
for more information about alert you can try this link DJANGO-ALERTS
for storing it into the database you can create seperate table/collection and there you can generate schema like user recived , user logged in etc.

Django: How do I position a page when using Django templates

I have a web page where the user enters some data and then clicks a submit button. I process the data and then use the same Django template to display the original data, the submit button, and the results. When I am using the Django template to display results, I would like the page to be automatically scrolled down to the part of the page where the results begin. This allows the user to scroll back up the page if she wants to change her original data and click submit again. Hopefully, there's some simple way of doing this that I can't see at the moment.
It should already work if you provide a fragment identifier in the action method of the form:
<form method="post" action="/your/url#results">
<!-- ... -->
</form>
and somewhere below the form, where you want to show the results:
<div id="results">
<!-- your results here -->
</div>
This should make the page jump to the <div> with ID results.
It is complete client site and does not involve Django, JavaScript or similar.
You need to wrap your data into something like this:
<div id="some-id">YOUR DATA TO BE DISPLAYED</div>
and if you make redirect in your view you need to redirect to url: /some-url/#some-id
if you don't make redirect you need to scroll to the bottom using javascript (but note that redirect is preffered way to use in view after saving data).