How to execute rawSql in Yesod - yesod

I am new to Yesod and I am having trouble executing simple rawSql statement in Scaffolded site.
module Handler.RawSQL where
import Import
getRawSQLR :: Handler Html
getRawSQLR = do
users <- runDB $ rawSql "SELECT ident, password FROM user" []
defaultLayout $(widgetFile "rawsql")
I am getting error:
Handler/RawSQL.hs:7:22: Not in scope: ‘rawSql’
What am I doing wrong and how do I show "users" in hamlet template?

You may just need to import the rawSql function:
import Database.Persist.Sql (rawSql)

Related

Get View associated with a URL [duplicate]

Given a uri like /home/ I want to find the view function that this corresponds to, preferably in a form like app.views.home or just <app_label>.<view_func>. Is there a function that will give me this?
You can use the resolve method provided by django to get the function. You can use the __module__ attribute of the function returned to get the app label. This will return a string like project.app.views. So something like this:
from django.urls import resolve
myfunc, myargs, mykwargs = resolve("/hello_world/")
mymodule = myfunc.__module__
In case one needs the class of the view since a class based view is being used one can access the view_class of the returned function:
view_class = myfunc.view_class
From Django 2.0 onward django.core.urlresolvers module has been moved to django.urls.
You will need to do this:
from django.urls import resolve
myfunc, myargs, mykwargs = resolve("/hello_world/")
mymodule = myfunc.__module__
Since Django 1.3 (March 2011) the resolve function in the urlresolvers module returns a ResolverMatch object. Which provides access to all attributes of the resolved URL match, including the view callable path.
>>> from django.core.urlresolvers import resolve
>>> match = resolve('/')
>>> match.func
<function apps.core.views.HomeView>
>>> match._func_path
'apps.core.views.HomeView'
1. Generate a text file with all URLs with corresponding view functions
./manage.py show_urls --format pretty-json --settings=<path-to-settings> > urls.txt
example
./manage.py show_urls --format pretty-json --settings=settings2.testing > urls.txt
2. Look for your URL in the output file urls.txt
{
"url": "/v3/affiliate/commission/",
"module": "api.views.affiliate.CommissionView",
"name": "affiliate-commission",
},
All the others focus on just the module or string representation of the view. However, if you want to directly access the view object for some reason, this could be handy
resolve('the_path/').func.cls
This gives the view object itself, this works on class based view, I haven't tested it on a function based view though.
Based on KillianDS's answer, here's my solution:
from django.core.urlresolvers import resolve
def response(request, template=None, vars={}):
if template is None:
view_func = resolve(request.META['REQUEST_URI'])[0]
app_label = view_func.__module__.rsplit('.', 1)[1]
view_name = view_func.__name__
template = '%s.html' % os.path.join(app_label, view_name)
return render_to_response(template, vars, context_instance=RequestContext(request))
Now you can just call return response(request) at the end of your view funcs and it will automatically load up app/view.html as the template and pass in the request context.

Use SQL VIEWS in Django

Is there any way to use the SQL Command CREATE VIEW in Django?
If I Try To use regular syntax, or use
from django.db import connection
...
with connection.cursor()
...
I get the Error:
Incorrect syntax near the keyword 'VIEW'.
as usual creating view in sql is look like below:
create view in SQL named Test:
from django.db import connection
...
...
def createView(self):
with connection.cursor() as cursor:
cursor.execute('DROP VIEW IF EXISTS dbo.Test')
cursor.execute("CREATE VIEW Test AS \
SELECT column1, column2, column3, ...\
FROM some_table_name \
WHERE condition")
Check your syntax with mine, if still has problem please place your whole code here.

Django guardian user.has_perm false for existing data

I was trying to give permission using Django guardian. when I try to give permission for existing data its show me a false message but when I create a new object its show me true. what I'm doing wrong?
My code :
>>>from django.contrib.auth.models import User
>>>from print.models import *
>>>from guardian.shortcuts import assign_perm
>>>user = User.objects.create(username='tanvir',password='antu')
>>>excel = ExcelData.objects.all()
>>>assign_perm('delete_exceldata', user, excel)
>>>user.has_perm('delete_exceldata', excel)
>>>False
But If I do
>>>from django.contrib.auth.models import User
>>>from print.models import *
>>>from guardian.shortcuts import assign_perm
>>>user = User.objects.create(username='tanvir',password='antu')
>>>excel = ExcelData.objects.create(order_number='01245632145214')
>>>assign_perm('delete_exceldata', user, excel)
>>>user.has_perm('delete_exceldata', excel)
>>>True
excel = ExcelData.objects.all()
will give you a queryset and
excel=ExcelData.objects.create(order_number='1245632145214')
will give you an object..
You can only assign permission to an object
if you want to assign permission for a queryset do it inside a loop
user = User.objects.create(username='tanvir',password='antu')
excel = ExcelData.objects.all()
for obj in excel:
assign_perm('delete_exceldata', user, obj)
user.has_perm('delete_exceldata', obj) # this will give you status for each obj

django CMS cant see my toolbar

Hello I have a common problem in Django like Django can't see ..
OK this time Django can't see my beautiful toolbar.
Terminal doesn't show any error.
This is my cms_toolbar.py placed in my "aktualnosci" folder
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from cms.utils.urlutils import admin_reverse
from .models import *
#toolbar_pool.register
class PollToolbar(CMSToolbar):
supported_apps = (
'aktualnosci',
)
watch_models = [Aktualnosci]
def populate(self):
if not self.is_current_app:
return
menu = self.toolbar.get_or_create_menu('poll-app', _('Aktualnosci'))
menu.add_sideframe_item(
name=_('Lista aktualnosci'),
url=admin_reverse('aktualnosci_aktualnosci_changelist'),
)
menu.add_modal_item(
name=_('Dodaj aktualnosc'),
url=admin_reverse('aktualnosci_aktualnosci_add'),
)
Of course Django can't see it and ignore it.
My question is - how to force Django to see it.
Screaming doesnt help!
If you're using django CMS >= 3.2, the file should be called cms_toolbars.py instead of cms_toolbar.py

Mechanize control name "None"

I'm trying to set the controls on a form from disabled readonly to something usable. But the problem is the control has no name. I saw a previous post where someone else solved this problem. But I have been unable to implement their solution correctly. Since I am new to python, I was hoping someone could shed some light on what I'm doing wrong.
Previous post:
Use mechanize to submit form without control name
Here is my code:
import urllib2
from bs4 import BeautifulSoup
import cookielib
import urllib
import requests
import mechanize
# Log-in to wsj.com
cj = mechanize.CookieJar()
br = mechanize.Browser()
br.set_cookiejar(cj)
br.set_handle_robots(False)
# The site we will navigate into, handling it's session
br.open('https://id.wsj.com/access/pages/wsj/us/login_standalone.html?mg=id-wsj')
# Select the first (index zero) form
br.select_form(nr=0)
# Returns None
forms = [f for f in br.forms()]
print forms[0].controls[6].name
# Returns set_value not defined
set_value(value,
name=None, type=None, kind=None, id=None, nr=None,
by_label=False, # by_label is deprecated
label=None)
forms[0].set_value("LOOK!!!! I SET THE VALUE OF THIS UNNAMED CONTROL!",
nr=6)
control.readonly = False
control.disabled = True
The control which value you are trying to set is actually a button, submit button:
print [(control.name, control.type) for control in forms[0].controls]
prints:
[('landing_page', 'hidden'),
('login_realm', 'hidden'),
('login_template', 'hidden'),
('username', 'text'),
('password', 'password'),
('savelogin', 'checkbox'),
(None, 'submit')]
And, you cannot use set_value() for a submit button:
submit_button = forms[0].controls[6]
print submit_button.set_value('test')
results into:
AttributeError: SubmitControl instance has no attribute 'set_value'
Hope that helps.