我正在学习Django表单,并尝试保存表单数据。我有一个可以工作的表单,但是我不知道如何处理表单中输入的数据。具体地说,我尝试做以下两件事:
在第一个中,一旦用户提交了表单,就加载一个新页面,其中显示:"You searched 'X'“。
第二个,让表单数据与现有数据库交互。具体地说,我有一个名为'Hashtag‘的模型,它有两个属性:'search_text’和'locations‘。我认为这个过程的工作原理如下:
哪里,
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)
我正在考虑实现这一点的一种潜在方法是创建另一个模型,并将用户输入的表单数据保存在那里。我想知道这是否正确,以及如何使用该解决方案来实现上面提到的Second目标:)
如果我的解释一团糟/完全错了,谢谢并提前道歉:/
编辑
下面的编辑进行了以下更改:
根据@ def results()
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')
完整的repo可以在这里找到:https://github.com/darcyprice/Mapping-Data
编辑2个
下面的编辑进行了以下更改:
def results()
尽管我直接复制了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)
发布于 2018-06-05 16:49:33
将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')
https://stackoverflow.com/questions/50692214
复制相似问题