我正在尝试使用从用户搜索中从第三方api收集的数据填充表单字段。我希望当他们单击“添加艺术家”时将表单数据保存到用户的数据库中。目前只是尝试传递搜索到的艺术家的名字。
<form action="{% url 'add_artist' %}" method="post">
{% csrf_token %}
<input type="hidden" name="name" value="{{ artist.name }}">
<input type="submit" class="btn" value="Add Artist">
</form>
因为我没有使用CBV,所以我无法保存到数据库,因为我没有内置的表单/模型关系。我想知道是否有一种方法可以在Django中对非CBV表单提交使用表单方法。理想情况下,视图函数应如下所示:
def add_artist(request, artist_id):
form = request.POST
if form.is_valid():
new_artist = form.save(commit=False)
new_artist.user = request.user
new_artist.save()
return render(request, 'artists/index.html', {
'artists': new_artist
})
这是模型:
class Artist(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('detail', kwargs={'artist_id': self.id})
这是api调用:
def show(request):
searched_artist = request.POST['name_field']
appKey = os.environ['APP_ID']
req = requests.get(f"http://rest.bandsintown.com/artists/{searched_artist}?app_id={appKey}")
req = req.json()
events = requests.get(f"http://rest.bandsintown.com/artists/{searched_artist}/events?app_id={appKey}")
events = events.json()
return render(request, 'detail.html',{
'artist': req,
'events': events,
})
答案 0 :(得分:0)
如果我正确阅读了您的问题,则希望前端显示随表格一起提交的艺术家。如果是这样的话。 (是的,您可以在基于类的视图之外使用form.is_valid()...
def add_artist(request, artist_id):
form = NameOfYourForm(request.POST, request.FILES)
name = None #Or call to database (Artist.objects.filter(id=artist_id) if you want the form populated before submission
if form.is_valid():
user = request.user
name = form.cleaned_data.get("name")
foo = Artist(user = user, name=name)
foo.save()
return render(request, 'artists/index.html', {'artists': name})