简体   繁体   中英

Passing FormView data from CBV to another CBV

This is my model:

class DataEm(models.Model):
    title = models.CharField(max_length=255, blank=True)

and this is my basic search form:

from django import forms


class SearchForm(forms.Form):
    App_title = forms.CharField(max_length=256)

and this is how my views.py in this area look like:

class ResultsView(generic.ListView):
    model = DataEm
    template_name = 'explorer/results.html'
    context_object_name = 'apps'


class SearchView(generic.FormView):
    template_name = 'explorer/search.html'
    form_class = sf.SearchForm
    success_url = '/explorer/results/'


def get_data(form):
    name = form.cleaned_data['App_title']
    apps = DataEm.objects.filter(title__contains=name)
    return apps

and these are my search.html and results.html templates (respectively):

<form action="" method='post'>{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Search' />
</form>

and:

<table>
    {% for app in apps %}
        <tr>
            <td>{{ app.title }}</td>
            <td>{{ app.price }}</td>
        </tr>
    {% endfor %}
</table>

When the user submits the form, I want to run get_data() method to get the results of his search based on his keyword and redirects the page to results.html page where it would show the results of the search.

obviously there's no connection what so ever between the first form and the second view, and I've been attempting to solve this by calling redirect() shortcut or render_to_response right from the SearchView.form_valid() but it doesn't work. and what happens now is that after submission, the success_url is called and the results.html loads with the whole things in the database.

the only solution that would seem to work is by hacking into the form_valid() and calling get_data() and writing the results in a separate table in the database, which the ResultsView is directed at. but that's just stupid in my opinion. I'm sure there's a more professional way to pass data between Class-based views.

Why not use the same view and simply override the get_queryset method?

edit: as I see you have a separate SearchView, this way you should simply change the form's action from empty to {% url "name.of.your.resultsview" %} and override the SearchView's get_queryset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM