保存Django表单数据

时间:2018-06-05 04:46:01

标签: python django django-forms

我正在学习Django表单并且正在尝试保存表单数据。我有一个工作表单,但我不知道在表单上输入的数据“做”任何事情。具体来说,我正在尝试做以下两件事:

首先,一旦用户提交表单,请加载一个新页面,其中指出:“您搜索了'X'”。

第二,让表单数据与现有数据库进行交互。具体来说,我有一个名为'Hashtag'的模型,它有两个属性:'search_text'和'locations'。我认为该过程将如下工作:

  • 将X发送到模型('Hashtag'),
  • 如果X等于数据库中现有的hashtag.search_text对象,则返回一个页面:“以下是'X'的位置:'Y'
  • 如果X不等于数据库中现有的hashtag.search_text对象,则返回一个页面:“以下是'X'的位置:找不到位置”。

其中,

X =用户输入的表格数据

列表中的Y = hashtag.locations.all()

到目前为止,我有以下内容:

models.py

from django.db import models


class Hashtag(models.Model):
    """
    Model representing a specific hashtag search. The model contains two attributes:
        1) a search_text (eg 'trump') for which there will be only one for database entry (the row),
        2) a list of locations (eg ['LA, CA', 'LA, CA', 'NY, NYC', 'London, UK', 'London, United Kingdom']) for which there may be 0+ per search_text.
    """

    search_text = models.CharField(max_length=140, primary_key=True)
    locations = models.TextField()

    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 """
        # ISSUE: insert correct code, something like: return '[, ]'.join(hastagsearch.location_list for location in self.location.all())
        pass

forms.py

from django import forms
from django.forms import ModelForm

from .models import 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 hastag 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 .models import Hashtag
from .forms import SearchHashtagForm


def hashtag_search_index(request):
    """ View for index page for user to input search query """
    hashtag_search = get_object_or_404(Hashtag)

    # 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():
            # process the form data in form.cleaned_data as required
            hashtag_search.search_text = form.cleaned_data['search_text']
            # the reason we can use .save() is because we associated the form with the model as a ModelForm
            hashtag_search.save()
            # redirect to a new URL
            return HttpResponseRedirect(reverse('mapping_twitter:hashtag_search_query'))
    # If GET (or any other method), create the default form
    else:
        form = SearchHashtagForm()

    context = {'hashtag_search':hashtag_search, 'form':form}
    return render(request, 'mapping_twitter/hashtag_search_query.html', context)

我正在考虑实现这一目标的一种潜在方法是创建另一个模型并在那里保存用户输入的表单数据。我想知道这是否正确,以及如何使用该解决方案来实现上述第二所述目标:)

如果我的解释是混乱/明显的错误,请提前表示感谢和道歉:/

修改

以下编辑进行了以下更改:

  • 根据@Wiggy A.的回答
  • 更新了 models.py
  • 更新 views.py 以包含def results()
  • 在GitHub上包含指向回购的链接。

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=140)

    def __str__(self):
        return self.name

class Hashtag(models.Model):
    """ Model representing a specific Hashtag serch, containing two attributes:
        1) A `search_text` (fe 'trump'), for which there will be only one per
        database entry,
        2) A list of `locations` (fe ['LA, CA', 'NY, NYC']), for which there
        may be any number of per `search_text` """

    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()

views.py

...
def results(request):
    """ View for search results for `locations` associated with user-inputted `search_text` """

    search_text = hashtag_search
    location_list = Hashtag.display_locations()

    context = {'search_text':search_text, 'location_list':location_list}

    return render(request, 'mapping_twitter/results.html')

完整的回购可以在这里找到:https://github.com/darcyprice/Mapping-Data

编辑2

以下编辑进行了以下更改:

  • 更新了 views.py 以包含@Wiggy A.对def results()
  • 的建议修订
  • 包含因更新更改而收到的ERROR消息的副本。

虽然我是直接从Mozilla教程(https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms)复制的,但我怀疑行hashtag_search.search_text = form.cleaned_data['search_text']没有正确存储hashtag_search

错误

NameError at /search_query/
name 'hashtag_search' is not defined
Request Method: POST
Request URL:    http://ozxlitwi.apps.lair.io/search_query/
Django Version: 2.0
Exception Type: NameError
Exception Value:    
name 'hashtag_search' is not defined
Exception Location: /mnt/project/mapping_twitter/views.py in hashtag_search_index, line 24
Python Executable:  /mnt/data/.python-3.6/bin/python
Python Version: 3.6.5
Python Path:    
['/mnt/project',
 '/mnt/data/.python-3.6/lib/python36.zip',
 '/mnt/data/.python-3.6/lib/python3.6',
 '/mnt/data/.python-3.6/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6',
 '/mnt/data/.python-3.6/lib/python3.6/site-packages']

views.py

def hashtag_search_index(request):
    """ View for index page for user to input 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():
            hashtag_search.search_text = form.cleaned_data['search_text']
            hashtag_search.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 = {'hashtag_search':hashtag_search, 'form':form}
    return render(request, 'mapping_twitter/hashtag_search_index.html', context)


def results(request):
    """ View for search results for `locations` associated with user-inputted `search_text` """

    search_text = hashtag_search
    location = get_object_or_404(Hashtag, search_text=search_text)
    location_list = location.display_locations()

    context = {'search_text':search_text, 'location_list':location_list}

    return render(request, 'mapping_twitter/results.html', context)

1 个答案:

答案 0 :(得分:1)

locations属性转换为M2M字段。这听起来像你需要的东西。请记住,这是未经测试的代码。

<强> models.py

from django.db import models


class Location(models.Model):
    """ A model representing a Location, attached to Hashtag objects through a Many2Many relationship """
    name = models.CharField(max_length=140)

    def __str__(self):
        return self.name


class Hashtag(models.Model):
    """
    Model representing a specific hashtag search. The model contains two attributes:
        1) a search_text (eg 'trump') for which there will be only one for database entry (the row),
        2) a list of locations (eg ['LA, CA', 'LA, CA', 'NY, NYC', 'London, UK', 'London, United Kingdom']) for which there may be 0+ per search_text.
    """

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

    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 """
        # This will return a list of location names attached to the Hashtag model
        return self.locations.values_list('name', flat=True).all()

<强> views.py

...
def results(request):
    """ View for search results for `locations` associated with user-inputted `search_text` """

    search_text = hashtag_search
    location = get_object_or_404(Hashtag, search_text=search_text)
    location_list = location.display_locations()

    context = {'search_text':search_text, 'location_list':location_list}

    return render(request, 'mapping_twitter/results.html')