Tema: Url en Html
Ver Mensaje Individual
  #1 (permalink)  
Antiguo 28/02/2013, 20:14
djmkmix
 
Fecha de Ingreso: abril-2011
Ubicación: Baja California sur
Mensajes: 39
Antigüedad: 13 años, 7 meses
Puntos: 0
Url en Html

Hola que tal buenas noches, me preguntaba si pudiesen ayudarme con el siguiente código

models.py

Código:
from django.db import models
    from django.contrib import auth
    
    class Post(models.Model):
        title = models.CharField(max_length=255)
        machine_name = models.SlugField(max_length=255, primary_key=True)
        content = models.TextField(blank=True)
        publication_date = models.DateTimeField(auto_now_add=True)
        owner = models.ForeignKey(auth.models.User)
    
        def __unicode__(self):
            return self.title
    
        def briefing(self):
            return self.content[:300] + '...'
    
        class Meta:
            ordering = ['-publication_date']
    
    class Commentary(models.Model):
        post = models.ForeignKey(Post)
        content = models.TextField()
        publication_date = models.DateTimeField(auto_now_add=True)
        owner = models.CharField(max_length=50, default='El hombre invisible')
    
        def __unicode__(self):
            return self.owner + '@' + unicode(self.post)
    
        class Meta:
            verbose_name_plural = 'commentaries'
            ordering = ['-publication_date']


views.py

Código:
# Create your views here.
    from django.views.generic import ListView, TemplateView
    from posts.models import Post
    from django.db.models import Q
    
    class PostList(ListView):
        template_name="postlist.html"
        model = Post
    
    class SearchResults(ListView):
        template_name = "searchresults.html"
    
    def get_queryset(self):
        if self.request.method == 'GET':
            form = SearchForm(self.request.GET)
        if form.is_valid():
            query = form.cleaned_data['query']
            words = query.split(' ')
            qobjects = [Q(content__icontains=w) | Q(title__icontains=w) for w in words]
            condition = reduce(lambda x,y:x&y, qobjects)
            results = Post.objects.filter(condition)
        return results
    
        return Post.objects.none()
    
    class PostDetails(TemplateView):
        template_name='postdetails.html'
    
        def get_post(self, slug):
            return Post.objects.get(pk=slug)
    
        def get_form(self, post):
            if self.request.method == 'POST':
                form = AddCommentaryForm(self.request.POST)
                if form.is_valid():
                    post.commentary_set.add(form.save(commit=False))
                form = AddCommentaryForm()
    
            else:
                form = AddCommentaryForm()
    
            return form
    
        def get_context_data(self, **kwargs):
            context = super(PostDetails, self).get_context_data(**kwargs)
    
            post = self.get_post(kwargs['slug'])
            form = self.get_form(post)
    
            context.update({'form':form, 'post':post})
    
            return context
    
    def post(self, request, *args, **kwargs):
             context = self.get_context_data(**kwargs)
             return self.render_to_response(context)

url.py

Código:
from posts.views import PostList, PostDetails, SearchResults
    from django.conf.urls.defaults import patterns, include, url
    
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'djangoblog.views.home', name='home'),
    # url(r'^djangoblog/', include('djangoblog.foo.urls')),
    
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    
    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls), name='adminpage'),
    
    url(r'^$', PostList.as_view(), name='mainpage'),
    url(r'^posts/', PostList.as_view(), name='postlist'),
    url(r'^post/(?P<slug>[a-zA-Z0-9_-]+)/', PostDetails.as_view(), name='postdetails'),
    url(r'^search/', SearchResults.as_view(), name='searchresults'),
    )

en la carpeta templates tengo un archivo base.html y el error que tengo es que no aparece nada en:

"{% url searchresults %}"

"{% url mainpage %}"


base.html

Código HTML:
{% load static %}
    {% get_static_prefix as STATIC_URL %}
    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Mi blog | {% block title %}Un título genérico{% endblock %}</title>
            <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}style.css">
        </head>
    
        <body>
            <form action="{% url searchresults %}" method="GET">
                <p>{{ searchform.query.errors }}</p>
                <label>Buscar: {{ searchform.query }}<input type="submit" value="Buscar"></label>
            </form>
            <header>
                <h1><a href="{% url mainpage %}">Mi blog</a></h1>
            </header>
            {% block content %}Un contenido genérico{% endblock %}
        </body>
    </html> 

y el siguiente error entre en post.html ya que no me da el resultado y cuando borro estos 4 problemas se ve la pagina

"{% url postdetails post.machine_name %}"

"{% url postdetails post.machine_name %}#commentaries"

post.html

Código HTML:
<article>
        <header>
            <h2><a href="{% url postdetails post.machine_name %}">{{ post.title }}</a></h2>
        </header>
        <section>
        {{ post.content|safe }}
        </section>
        <aside>
        {% with comcount=post.commentary_set.all.count %}
            <p><a href="{% url postdetails post.machine_name %}#commentaries">{{ comcount }} comentario{{comcount|pluralize}}</a></p>
        {% endwith %}
        <p>Fecha de publicación: {{ post.publication_date|date:"r" }}</p>
        </aside>
    </article>