【发布时间】:2022-01-07 10:27:57
【问题描述】:
我有一个功能正常的下拉菜单,其中包含来自数据库的一些对象。当用户选择一个时,他们应该被引导到相应的对象页面。每个对象都是一个“锻炼”,每个锻炼都有“练习”。它正在工作,但是,我正在努力从用户选择的对象中获取适当的“id”。下面我将提供视图、模板、url和表单。
view.py
@login_required
def routines(request):
"""This view will provide a dropdown list of all of the workouts of a specific user.
Once one is selected, the user will hit a submit button.
After submitted, a new page will show all the exercises for that workout"""
if request.method == "GET":
#if we have a GET response, provide a form with filled data
form = RoutineForm(request.GET, user=request.user)
#data needs to equal the object that was selected from the GET form
data = 1
if form.is_valid():
data=form.cleaned_data("workout")
form.instance.owner = request.user #make sure we have the right user
form.save()
return HttpResponseRedirect('routine_workouts_app:routines')
context = {'form':form, 'data':data}
return render(request, 'routine_workouts_app/routines.html', context)
@login_required
def routine(request, data):
"""I think this is the view that will display the information of a workout as of now.
Should be similar to the workout view."""
a_workout = Workout.objects.get(id=data)
#Make sure the topic belongs to the current user
if a_workout.owner != request.user:
raise Http404
exercises = a_workout.exercise_set.order_by('exercise_name')
context = {'a_workout': a_workout, 'exercises':exercises}
return render(request, 'routine_workouts_app/routine.html', context)
routines.html
<form action="{% url 'routine_workouts_app:routine' data %}" method="get">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Make Workout</button>
</form>
网址
path('routines/', views.routines, name='routines'), #this one deals with selecting a workout and submitting a form
#via routine/ shows the specific workout. just like workouts/int
path('routines/<int:data>/', views.routine, name='routine'), #this one displays the information based on the form
和forms.py
class RoutineForm(forms.ModelForm):
"""This creates a form to work for Routine making"""
def __init__(self, *args, user=None, **kwargs): #this code helps to manage ownership of workouts.
super().__init__(*args, **kwargs)
self.fields['workout'].queryset = Workout.objects.filter(owner=user)
#info comes from the Routine model. Only field is 'workout' and labels is how we are going to identify the field on the webpage
class Meta:
model = Routine
fields = ['workout']
labels = {'workout': 'Workout'}
基本上,我希望data 等于用户在views.py 中的routines 函数中选择的对象。从那里,我可以获取对象 ID 并将用户引导到正确的页面。截至目前,无论何时选择使用,它们都将被定向到 ID 为 1 的“锻炼”(因此,它为什么起作用但不是我想要的)。
提前感谢您的帮助。另外,有人可以推荐任何有助于提高 Django 技能的教科书吗?
图片供参考:
【问题讨论】:
标签: python django django-forms getmethod