user9330449
user9330449

Reputation:

Form input to a template

EXPECTED OUTPUT

Assuming that the user enters "anaconda" in the Form:

Hashtag Search Results

You searched for: anaconda

ACTUAL OUTPUT

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 %}

Upvotes: 0

Views: 94

Answers (2)

user7552123
user7552123

Reputation:

I think you should pass the queryset of the Model HashTag as you need to render out hashtag.search_text which is an element of that model.

So you can pass the queryset in the view and for loop through it and print all the search_text or pass the object alone and render out its search_text.

context = { 'queryset': qs }

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

Upvotes: 1

Joseph
Joseph

Reputation: 97

This is my guess, correct me if I am wrong. For a template to display something, you have to send context or data to that template to print, how can it print something when you don't send anything. So,

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

Upvotes: 1

Related Questions