Home > database >  Creating a basic Input Form in a Django
Creating a basic Input Form in a Django

Time:08-30

I am trying to create a simple form in Django but it is not showing the input form in HTML and there is not error appearing so that I can track the error.

Here is the model:

class Log(models.Model):
    log_weight = models.FloatField(validators=[MinValueValidator(0)],blank=True, null=True)
    log_repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True)

class LogForm(forms.Form):
    log_weight = forms.IntegerField()
    log_repetitions = forms.IntegerField()
    class Meta:
        model = Log
        fields = ['log_weight', 'log_repetitions']

Here is the views:

class workout_details(DetailView):
    model = Workout
    template_name = 'my_gym/start_workout.html'
    context_object_name = 'workout'

    def get_context_data(self, **kwargs):
        exercises = Exercise.objects.filter(workout_id=self.object)
        context = super().get_context_data(**kwargs)
        context['exercises'] = exercises
        return context

def addlog(request, id):
    url = request.META.get('HTTP_REFERER')  # get last url
    # return HttpResponse(url)
    if request.method == 'POST':  # check post
        form = LogForm(request.POST)
        if form.is_valid():
            data = Log()  # create relation with model
            data.log_repetitions = form.cleaned_data['log_repetitions']
            data.log_weight = form.cleaned_data['log_weight']
            data.workout_id = id
            data.save()  # save data to table
            return HttpResponseRedirect(url)
    return HttpResponseRedirect(url)

Here is the template:

    <form
     action="{% url 'my_gym:addlog' workout.id %}" method="post">
    {% csrf_token %}
    {{ form }}
    </form>

Here is the url:

urlpatterns = [
    path('', home.as_view(), name='home'),
    path('workout/<int:pk>/', workout_details.as_view(), name='workout'),
    path('workout/addlog/<int:pk>', addlog, name='addlog'),
]

My question: What is the reason that the form is not showing in the details page? How can I fix it.

CodePudding user response:

You missed to pass the form to the View context. Add the following to your DetailView get_context_data method:

context['form'] = LogForm()
  • Related