why are there =\r\n characters coming from my textarea? - python

In my form i have:
<textarea id="styled" name="content"></textarea>
before submitting the form i cut and paste the following into the text area:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
When I retrieve the value on google app engine:
ImageUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
content_i = self.request.get("content", None)
#content_i is:
u'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\r\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\r\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\r\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\r\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\r\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=\r\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'

This is because of this bug. Though this might solve your problem -> #AndreBrossards Middleware Fix

Related

Folium - Django: How to make a folium marker a link to another page

I'm generating a map using Folium with Django like so:
views.py:
def viz(request):
dg_map= folium.Map(location=[50.38175,6.2787],
tiles= 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png?api_key=<MY_API_KEY>',
attr= '© Stadia Maps, © OpenMapTiles © OpenStreetMap contributors',
zoom_start=10)
map_details = fetch_data("SELECT id, firstname, lat, long FROM map_details") #helper func to query the DB
for item in map_details:
location = [item[2], item[3]]
popup = f"{item[1]}'s Garden"
marker = folium.Marker(
location = location,
popup = popup,
icon=folium.Icon(color='darkgreen', icon="heart", prefix='fa'))
marker.add_to(dg_map);
m = dg_map._repr_html_()
context = {'map': m}
return render(request, 'accounts/viz.html', context)
This is working as expected.
However, I'd like each marker to redirect towards another page on-click. To make matters worse, I'd need to use the id that's queried in the SELECT statement and include it in the destination link, because the urlpattern of the destination pages is this:
urls.py:
path('garden/<str:id>/', views.garden, name="garden").
What I found out so far:
I found several suggestions on how to add an href to the pop-up (e.g. here) but this is not what I want as it requires the user to click twice.
Some ideas on how to add custom js to Folium's output are mentioned here, but I think it's not implemented yet.
I also found instructions on how this can be done in Leaflet. It seems pretty straight forward, but I'd like to stick with Python/Folium code and keep the logic in my views.py rather than starting js scripting.
Any idea how this can be achieved? Thanks a lot!

React / Apollo: Displaying Error of GraphQL mutation (useMutation hook)

I am having a hard time trying to figure out why I can't show the error of my mutation.
I have implemented error codes in my mutation:
if location_lat < 0.1 and location_lon < 0.1:
raise GraphQLError('E_CF_002')
now on the client-side, I call the following mutation, which is called onSubmit of a form and I purposefully trigger the error.
const [
createEvent,
{ data: createData, loading: createLoading, error: createError}
] = useMutation(CREATE_EVENT);
The error code is successfully returned as seen in my network tab:
{"errors": [{"message": "E_CF_002", "locations": [{"line":
However, when I try to show the error in a dialogue box
{createError && (
<div>
<Dialog open={openDialog} onClose={handleClose}>
<h3>Sorry, an error occured while creating the event.</h3>
<h3>Plese try again later. {JSON.stringify(createError)} </h3>
<DialogActions>
<Button onClick={handleClose} color="primary">
Okay
</Button>
</DialogActions>
</Dialog>
</div>
)}
I only see:
Sorry, an error occured while creating the event.
Plese try again later. {}
Can anyone help me understand why my error variable does not hold the message etc.?
I first tried directly printing createError.message or createError[0].message or even createError.errors and even createError.errors[0] however later on I saw that even the entire JSON is empty by printing JSON.stringify(createError).
I haven't been able to find this specific issue (or it's solution) on StackOverflow or elsewhere.
Thank you in advance!

How to make only 1 refresh on multiple clicks python/django

I have a site using GCP python API, which is quite slow at making pull requests. So I have cached the area of the template using this data, and in the view I check if the cache is still active before making any more requests (not a copy n pasted code so if theres any typos ignore em :) )
def gcpProjectsView(request):
gcpprojects = None
cached_time = None
if cache.get(make_template_fragment_key('gcp')) is None:
cached_time=timezone.now()
gcpprojects = get_gcp_projects()
return render (request , 'gcp/gcpprojects.html', {'gcpprojects':gcpprojects,'last_update':cache_time})
To manually update the data, I have a refresh button that points to this view:
def refresh_gcp(request):
cache.delete(make_template_fragment_key('gcp'))
return redirect('gcpProjectsView')
The problem is that if the user clicks the refresh button 5 times the view makes 5 GCP Api calls, it needs to only do 1. How do I resolve this issue?
My suggestion would be to use a simple form with a button. Buttons can be disabled using simple javascript when clicked.
Because you're redirecting back to the same template in the view the button should be re-enabled again once it has 'refreshed'.
In this example snippet replace the action with whatever url routes to refresh_gcp.
<form method="GET" action="<url that points to refresh_gcp>">
<button type="submit" onclick="this.disabled = true;">Refresh</button>
</form>
This was the simplest solution I could think of that didn't involve implementing some sort of token validation for requests.
Use django session :
def refresh_gcp(request):
clicked = request.session.get("click")
if clicked:
return render(request,"your_html",{"disable":True})
# Set Button disable or not in your html by using context...
else:
request.session["click"]="user_click"
cache.delete(make_template_fragment_key('gcp'))
return render(request,"your_html",{"disable":False})

How to save a file to a custom repository?

I am using python-docx to save a word file and I have set a specific path but since path aren't the same for every user I would like to have a dialogue when the user clicks on download so he can choose exactly in which local repository to save the file.
What I have now:
#app.route('/download_file')
def save_doc():
filename = 'test.docx'
filepath = os.path.join(r'C:\Users\Joe\Desktop', filename)
document.save(filepath)
return 'meh'
Implementing the logic you described requires work on the front-end. Let's simplify the problem by assuming that the user manually types in the download target directory. (In practice, it would make more sense for there to be a pop-up window allowing the user to browse the directory on a file explorer.)
<form action="/download" method="post">
<input type="text" value="" name="dir">
<input type="submit" value="Download">
</form>
Then, in Flask, you might specify the following:
from flask import Flask, request
#app.route('/download', methods=['GET', 'POST'])
def save_doc():
if request.method=='POST':
download_dir = request.form['dir'] # Access user input from backend
filename = 'test.docx'
filepath = os.path.join(download_dir, filename)
document.save(filepath)
return 'Download complete'
else:
pass # Whatever implementation you want for 'GET' method
This is incomplete code that I wrote without knowledge of the structure of your project, and so may not work if it is simply copied and pasted into your source code. The implementation is also quite basic, so consider it a baseline model to help you get started on baking the user interactive dialogue system.
I'd be happy to answer any questions you might have.

Is it possible to get an object by its primary key in django-nonrel / Google App Engine?

I'm trying to retrieve a model object like the code below:
(r'^album/(?P<album_id>\w+)/$', 'core.views.album'),
def album(request, album_id):
album = Album.objects.get(pk=album_id)
The problem is that the PK is not an integer:
>>> a = Album.objects.all()[0]
>>> a.pk
46L
The error I'm getting when I run the view:
ValueError at /album/46L/
invalid literal for int() with base 10: '46L'
Ideas? Thanks.
46L is a long integer, not a string, so you should treat it as a number and not a word in urls.py:
(r'^album/(?P<album_id>\d+)/$', 'core.views.album'),
then the url /album/46/ will end up calling:
def album(request, album_id):
#album = Album.objects.get(pk=46L)
album = Album.objects.get(pk=album_id)
Or if you need to keep the 'L' in the url for some reason, cast it as a long before using it:
album = Album.objects.get(pk=long(album_id))
The problem was unrelated with the urls / views. Everytime I executed "runserver" my local datastore was being erased. So the data I was able to retrieve when using "shell" was not synced correctly.
This happened because, for some weird reason, I commented this line (and forgot about it) on settings.py:
AUTOLOAD_SITECONF = 'indexes'

Categories

Resources