【问题标题】:Django Forms: How do I use a selected object from dropdown menu?Django Forms:如何使用下拉菜单中的选定对象?
【发布时间】: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


    【解决方案1】:

    您可以在验证表单后使用redirect 快捷方式重定向到带有参数的命名网址。参数是锻炼 id,它存储在表单创建的例程实例中。

    <form action="{% url 'routine_workouts_app:routines' %}" method="get">
            {% csrf_token %}
            {{ form.as_p }}
            <button name="submit">Make Workout</button>
    </form>
    
    
    
    
    from django.shortcuts import redirect
    
    @login_required
    def routines(request):
        form = form = RoutineForm(request.GET or None, user=request.user)
        if form.is_valid():
            # workout_instance = form.cleaned_data("workout")
            routine_instance = form.save(commit=False)
            routine_instance.owner = request.user # make sure we have the right user
            routine_instance.save()
            return redirect('routine_workouts_app:routine', args=(routine_instance.workout.pk,))
            
        context = {'form': form}
        return render(request, 'routine_workouts_app/routines.html', context)
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 2019-05-23
      • 1970-01-01
      • 2022-01-20
      • 2014-04-18
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2016-11-28
      相关资源
      最近更新 更多