表单输入到模板

时间:2018-06-12 05:42:23

标签: django django-templates

预期输出

假设用户在Form

中输入“anaconda”
Hashtag Search Results

You searched for: anaconda

实际输出

Hashtag Search Results

    1) You searched for: <QuerySet [<Hashtag: >, <Hashtag: anaconda>]>

CODE

models.py

from django.db import models


class Location(models.Model):
    """ Model representing a Location, attached to Hashtag objects through a
    M2M relationship """

    name = models.CharField(max_length=1400)

    def __str__(self):
        return self.name

class Hashtag(models.Model):
    """ Model representing a specific Hashtag serch by user """ 

    search_text = models.CharField(max_length=140, primary_key=True)
    locations = models.ManyToManyField(Location, blank=True)

    def __str__(self):
        """ String for representing the Model object (search_text) """
        return self.search_text

    def display_locations(self):
        """ Creates a list of the locations """
        # Return a list of location names attached to the Hashtag model
        return self.locations.values_list('name', flat=True).all()

forms.py

from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _

from .models import Location, Hashtag


class SearchHashtagForm(ModelForm):
    """ ModelForm for user to search by hashtag """

    def clean_hashtag(self):
        data = self.cleaned_data['search_text']
        # Check search_query doesn't include '#'. If so, remove it.
        if data[0] == '#':
            data = data[1:]
        # return the cleaned data
        return data

    class Meta:
        model = Hashtag
        fields = ['search_text',]
        labels = {'search_text':_('Hashtag Search'), }
        help_texts = { 'search_text': _('Enter a hashtag to search.'), }

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Location, Hashtag
from .forms import SearchHashtagForm


def hashtag_search_index(request):
    """ View function for user to enter search query """

    # If POST, process Form data
    if request.method == 'POST':
        # Create a form instance and populate it with data from request (binding):
        form = SearchHashtagForm(request.POST)
        # Check if form is valid
        if form.is_valid():
            search_text = form.cleaned_data['search_text']
            form.save()
            # redirect to a new URL
            return HttpResponseRedirect(reverse('mapping_twitter:results'))

    # If GET (or any other method), create the default form
    else:
        form = SearchHashtagForm()

context = {'form':form, 'search_text':Hashtag.search_text}
return render(request, 'mapping_twitter/hashtag_search_index.html', context)


class SearchResultsView(generic.ListView):
    """ Generic class-based view listing search results of locations """
    model = Hashtag
    template_name = 'mapping_twitter/results.html'

    def get_queryset(self, **kwargs):
        qs = super(SearchResultsView, self).get_queryset()
        return qs

    def get_context_data(self, **kwargs):
        context = super(SearchResultsView, self).get_context_data(**kwargs)
        context['search_text'] = Hashtag.objects.all()
        return context

results.html

<h1>Hashtag Search Results</h1>

<p>1) You searched for: {{ search_text }}</p>

{% for obj in queryset %}
    <p>2) You searched for: {{ obj.search_text }}</p>
{% endfor %}

2 个答案:

答案 0 :(得分:1)

这是我的猜测,如果我错了,请纠正我。 要使模板显示某些内容,您必须将上下文或数据发送到该模板进行打印,如果您不发送任何内容,它如何打印内容。所以,

context.update({
        'hashtag': //value you want to send.
})

答案 1 :(得分:1)

我认为你应该传递Model HashTag的查询集,因为你需要渲染hashtag.search_text,它是该模型的一个元素。

因此,您可以在视图中传递查询集并循环遍历它并打印所有search_text或单独传递对象并渲染其search_text。

context = { &#39; queryset&#39;:qs }

{% for obj in queryset %}
   <p>{{ obj.search_text }}</p>
{% endfor %}