John Eipe
John Eipe

Reputation: 11228

correct approach for storing and display a state specific to Users

I have a page that lists questions (in C programming :-) ) that are completed by users. Say, there are 10 and every logged in user has access to these.

page to be displayed is something like this:

<table>
<tr>
<th>Test desc</th>
<th>Test state</th>
</tr>
{% for t in test%}
<tr>
<td>{{ t.desc }}</td>
<td>'display a image  if it is completed else another image'</td>
</tr>
{% endfor %}
</table>

User is forwarded to this page from views.py

def test(request):
    cProblems = Problems_c.objects.all()
    return render_to_response('subject/test.html', {'list':cProblems})

I need to know 2 things.

  1. How to store this additional User specific information in django.
  2. How to display them in webpage

Upvotes: 0

Views: 49

Answers (1)

jpic
jpic

Reputation: 33410

First, please use render() rather than render_to_response(). This will save you from common gotchas.

How to store this additional User specific information in django

See the documentation about storing additional user information.

How to display them in webpage

You can use the generic DetailView:

  1. Import DetailView in urls.py, i.e. from django.views import generic

  2. Import the User model in urls.py, i.e. from django.contrib.auth.models import User

  3. Add an url for that in urls.py, i.e. url(r'^/user/(?P<pk>\d+)/$', views.DetailView.as_view({'model': user, 'context_object_name': 'object'}))

  4. Create the template, in templates/auth/user_detail.html

  5. Open url /user/1/ to see the rendered template

Your template can look like this:

<h1>This is the page of {{ object.username }}</h1>

<p>Additional info: {{ object.get_profile.your_extra_field }}</p>

Of course, you should have a base template say templates/base.html that would look like this:

<html>
    <head>
        <title>{% block head_title %}{% endblock %} - your website</title>
    </head>
    <body>
        {% block body %}
        {% endblock %}
    </body>
</html>

And your user_detail.html template should use it, see template inheritance:

{% extends 'templates/base.html' %}

{% block head_title %}Details of {{ object.username }}{% endblock %}

{% block body %}
<h1>This is the page of {{ object.username }}</h1>

<p>Additional info: {{ object.get_profile.your_extra_field }}</p>
{% endblock %}

As you're new to Django, I highly recommend that you install admindoc which provides autogenerated documentation based on your project.

Upvotes: 1

Related Questions