how to use get_queryset in my code

194 views
Skip to first unread message

Nebros

unread,
Nov 19, 2012, 5:38:24 AM11/19/12
to django...@googlegroups.com
Good morning
I tryed to use a form to give a variable "x" to my filter... what i have:
startig page Portal-----------------------------------------
{% include "header.html" %}
<title>Kunde</title>
{% include "header2.html" %}
<h1>Kunde</h1>
{% block content %}<p>Zeit der Aktualisierung {{ current_date }}</p>{% endblock %}
<form method="post" action="/kundendaten/">
    {% csrf_token %}
        <p>Bitte Kundennamen eingeben</p>
        <label>
            <input type="text" name="kunde" size="30" required="required">
        </label>
        <br>
        <br>
        <input type="submit" name="senden" value="Senden" href="kundendaten">

</form>
{% include "footer.html" %}
--------------------------------------------------------------
 
this part run perfect...
at next the page kundendaten will called...
Kundendaten--------------------------------------------
{% include "header.html" %}
<title>Kundendaten</title>
{% include "header2.html" %}
<h1>Portal</h1>
<h2>Ausgabe Kundendaten</h2>
{% block content1 %}<p>Zeit der Aktualisierung {{ current_date }}</p>{% endblock %}
{% block content2 %}<p>Kundendaten {{ row }}.</p>{% endblock %}
<table border="1">
    <tr>
        <th>Name</th>
        <th>E-Mail</th>
    </tr>
    {% for t_name in row %}
    <tr>
        <td>{{ row.t_name }}</td>
        <td>{{ row.t_mail }}</td>
    </tr>
    {% endfor %}
 

</table>
{% include "footer.html" %}
-------------------------------------------------------
 
there is the problem, that my testlane "{% block content2 %}<p>Kundendaten {{ row }}.</p>{% endblock %}" give out correct data (if i give the variable x manually), but my table doesent work. it have no data.
next, i give you my views and urls...
 
views-------------------------------------------------
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_protect
import datetime
import pyodbc
@csrf_protect
def portal(request):
    now = datetime.datetime.now()
    return render_to_response('portal.html', {'current_date': now}, context_instance=RequestContext(request))
def kundendaten(request):
    def get_queryset(self):
        kunde = self.request.GET.get("kunde", False)
        if kunde == "all":
            kunde = False
        if kunde:
            variable = kunde
        return get_queryset(variable)
    variable ="x"
    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MAURITIUS;DATABASE=baan5c;UID=***;PWD=*****')
    cursor = cnxn.cursor()
    cursor.execute("SELECT x.t_name, y.t_mail FROM tttaad200000 as x, tttcmf200000 as y WHERE (x.t_name = y.t_name) AND (x.t_user = %r)" %x)
    row = cursor.fetchall()
    now = datetime.datetime.now()
 
    return render_to_response("kundendaten.html", { 'row': row,'current_date': now}, context_instance=RequestContext(request))
-------------------------------------------------------------
 
urls--------------------------------------------------------
from django.conf.urls import patterns
from klasse.views import portal, kundendaten
urlpatterns = patterns('',
    (r'^portal/$', portal),
    (r'^kundendaten/$', kundendaten),
)
------------------------------------------------------------
 
thats it, pls can anyone help me to fix the table and the correct code using for my variable x, given from page one?
thx for help...

Nebros

unread,
Nov 19, 2012, 9:28:59 AM11/19/12
to django...@googlegroups.com
It will be very helpful, if anyone can help me. I need it for my work and I cant find the solution... :(

Nebros

unread,
Nov 20, 2012, 2:25:55 AM11/20/12
to django...@googlegroups.com
I can really need your help, i don't have found the solution till now. :( 

Daniel Roseman

unread,
Nov 20, 2012, 5:10:06 AM11/20/12
to django...@googlegroups.com
On Tuesday, 20 November 2012 07:25:55 UTC, Nebros wrote:
I can really need your help, i don't have found the solution till now. :( 

You've had no replies because no-one can understand what you're asking. Something about querysets, but you seem to be using raw SQL in your code, for no apparent reason. And your code is totally unclear: what is that nested function doing, and why does it refer to `self`? And why is it calling itself?

Please post a *minimal* example that shows the problem, and describe exactly what you want to achieve and exactly what is going wrong, including any errors you receive.
--
DR.

Nebros

unread,
Nov 20, 2012, 8:24:25 AM11/20/12
to django...@googlegroups.com
Ok, what is my task...
I have my first page called "Portal". i can give there in a variable, and can send the value with this form to the next page. I tryed now to use this value as a variable you can see here:
 
AND (x.t_user = %r)" %x
 
this %x have to be my value of page one, i have given. I know this code:
 
 cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MAURITIUS;DATABASE=baan5c;UID=***;PWD=*****')
cursor = cnxn.cursor()
cursor.execute("SELECT x.t_name, y.t_mail FROM tttaad200000 as x, tttcmf200000 as y WHERE (x.t_name = y.t_name) AND (x.t_user = %r)" %x)
row = cursor.fetchall()
 
give me out data like this:
 
[('Ackermann Marcel (THA) ', ***@***.ch '), ('Adami Renate (HEI) ', ***@***.ch '), ('Ammann Cornelia (HEI) ', '***@***.ch '), ('Ausbildung A. Schwaller (HEI) ', '***@***.ch '),
 
And now the two questtions:
1. How can i set my value of the form as the variable %x?
and
2. How can i give out my data as a table to my page "Kundendaten"?
 
Ignore my fails like:
-----------------------
def kundendaten(request):
def get_queryset(self):
kunde = self.request.GET.get("kunde", False)
----------------------
i was trying something, cause i dont know how... ^^

Martin J. Laubach

unread,
Nov 20, 2012, 8:39:07 AM11/20/12
to django...@googlegroups.com
  Okay. You seem to be rather confused about the django approach to things I'm afraid.

  (a) You use raw sql instead of django's ORM mapper. That's okayish, but then you're on your own for building your queries and have to manually do validation and escaping and whatnot, which is, as you noticed, a pain in the behind.

  (b) You chose to manually build and parse the form. That's okayish, but then you're on your own validating user input.

  I strongly suggest you read up on django models (https://docs.djangoproject.com/en/1.4/topics/db/models/) and django forms (https://docs.djangoproject.com/en/1.4/topics/forms/), which will do most of what you want without you reimplementing everything from scratch. What you've shown looks more like some converted php code than a native django application.

Nebros

unread,
Nov 20, 2012, 9:07:24 AM11/20/12
to django...@googlegroups.com
I tryed first this part with db models. but mssql doesnt work on it... i cant generate the model by themself. thats why i made it by my own. in addition, the next part of my program is to implements lotus notes db... i can do it on the same way, thats why i try to do this.
And yes, i create my own, but its not like php. :)
so pls just help me by this problem, cause i do not know everything about programming with django.

Tom Evans

unread,
Nov 20, 2012, 10:00:51 AM11/20/12
to django...@googlegroups.com
On Tue, Nov 20, 2012 at 2:07 PM, Nebros <markusch...@gmail.com> wrote:
> so pls just help me by this problem, cause i do not know everything about
> programming with django.

The problem is that there is a lot going wrong in your code than just
not knowing Django.

I would recommend some python training, or a good book on python in
your native language. I'd also repeat what Martin told you, you are
using Django without using the features in Django that make it
worthwhile using Django. This will make life very hard for yourself,
as you are seeing.

Anyhow, to your code:

> def kundendaten(request):
> def get_queryset(self):
> kunde = self.request.GET.get("kunde", False)
> if kunde == "all":
> kunde = False
> if kunde:
> variable = kunde
> return get_queryset(variable)

What is this function - get_queryset() - supposed to do? It has an
argument of 'self', but this is not inside a class, so using self is
misleading. You never call this function, which is a good thing as it
never returns anything and recurses into itself. Calling this function
in python would lead to python crashing with a RuntimeError for
reaching maximum recursion depth.

> variable ="x"
> cnxn = pyodbc.connect('DRIVER={SQL
> Server};SERVER=MAURITIUS;DATABASE=baan5c;UID=***;PWD=*****')
> cursor = cnxn.cursor()
> cursor.execute("SELECT x.t_name, y.t_mail FROM tttaad200000 as x,
> tttcmf200000 as y WHERE (x.t_name = y.t_name) AND (x.t_user = %r)" %x)

C'mon. This code doesn't even run does it? It should blow up at this
point with a NameError - you have a variable called 'variable' that
has a value of 'x', but you have no variable called 'x'.

Forgetting that. you've got a cursor there. Cursors all behave
according to the Python DB API, which has methods of specifying
arguments you want inserted into the query:

http://wiki.python.org/moin/DbApiFaq

The reason we use an API, is that they do some of the hard bits of
using a database for you. By manually constructing the SQL string, you
are allowing the opportunity for SQL injection. This is something the
DB API would handle for you. It's also handled if you were using
Django's ORM (which we use as it does ALL the hard bits for us).

Using the DB API seems quite challenging, even if experienced, which
is why we use Django's ORM. You would be better spent getting the ORM
to work with your setup than hacking in bits like this. If you are
going to continue to write your own SQL, it might also be worth
looking up what a JOIN is.

> row = cursor.fetchall()

As I understand it 'row' is in fact multiple rows. It makes sense to
use plural names when appropriate.

> now = datetime.datetime.now()
>
> return render_to_response("kundendaten.html", { 'row':
> row,'current_date': now}, context_instance=RequestContext(request))


Now the template:

> {% include "header.html" %}
> <title>Kundendaten</title>
> {% include "header2.html" %}
> <h1>Portal</h1>
> <h2>Ausgabe Kundendaten</h2>
> {% block content1 %}<p>Zeit der Aktualisierung {{ current_date }}</p>{%
> endblock %}

{% block %} allows you to define parts of a template that get replaced
by a template that inherits from this one. Typically, rather than
include multiple header and footer templates, you would instead define
one base template, that has blocks for your title, your content, etc.

The template each view renders is then an derived version of this base
template, and the named blocks in the parent template are replaced by
the same named blocks in the child template.

If you aren't using template inheritance, then the block tag is
irrelevant and has no meaning.

> {% block content2 %}<p>Kundendaten {{ row }}.</p>{% endblock %}
> <table border="1">
> <tr>
> <th>Name</th>
> <th>E-Mail</th>
> </tr>
> {% for t_name in row %}
> <tr>
> <td>{{ row.t_name }}</td>
> <td>{{ row.t_mail }}</td>
> </tr>
> {% endfor %}

"for val in list" iterates through 'list' yielding a context variable
named 'val' in each iteration of the loop. Your list is called 'row',
which is a list of tuples, which you extracted from the database, and
you call the per-loop variable 't_name'. Yet inside the loop, you
never refer to 't_name' and instead try to lookup attributes from your
list of rows called 'row'. This is not going to work.

Remember when I said use plural names for plural objects? If your list
of rows was called 'rows', that line would read 'for row in rows',
which makes a lot more sense.


So, apart from all the bugs, is what you are trying to do is add a
parameter specified in the GET parameters in the request into that SQL
query?

kunde = request.GET.get("kunde", 'your default "kunde"')
sql = """
SELECT x.t_name, y.t_mail
FROM tttaad200000 as x, tttcmf200000 as y
WHERE (x.t_name = y.t_name)
AND (x.t_user = ?)
"""
cursor.execute(sql, kunde)

Even if your project means you cannot use Django's ORM, I would still
setup a simple full-stack Django project, do the tutorial and
experiment a bit, in order to give you a bit of experience actually
using Django and understanding how everything fits together.

Cheers

Tom

Martin J. Laubach

unread,
Nov 20, 2012, 1:35:36 PM11/20/12
to django...@googlegroups.com
I tryed first this part with db models. but mssql doesnt work on it...

  BTW, why? I see there's a django-mssql, that should allow you to connect to the database. Doesn't it work with your version? I've never tried it though, I just googled around a bit...

 

Nebros

unread,
Nov 21, 2012, 1:53:59 AM11/21/12
to django...@googlegroups.com
Its not a problem of the version, my pycharm gave no error, but it was not possible to generate the model... by generating there was always an error, like it cant find an class or something else.

?manu*

unread,
Nov 21, 2012, 6:02:09 AM11/21/12
to django...@googlegroups.com
On Wednesday, November 21, 2012 7:53:59 AM UTC+1, Nebros wrote:
Its not a problem of the version, my pycharm gave no error, but it was not possible to generate the model... by generating there was always an error, like it cant find an class or something else

Are you sure the problem is on the db API and not in your code?

Nebros

unread,
Nov 21, 2012, 10:14:47 AM11/21/12
to django...@googlegroups.com
yes, i copied all data in the correct folder, but it didnt work. but thats not more my problem...
 
i changed
row = cursor.fetchall()
into
row = cursor.fetchone()
 
this give me out the correct data into the correct column of my table. my next problem there is, why it doesent work with fetchall or fatchmany, and why he give me out something like this:
 
Open Orders BAAN
NameE-Mail
Ackermann Marcel (THA) marcel.ackermann@***.ch
Ackermann Marcel (THA)  

marcel.ackermann@***.ch                       

i mean, why it give me out 2 times the same...?
 
to use my formular data as a filter is another and maybe the biger problem...
Reply all
Reply to author
Forward
0 new messages