Issue
I have a form which has 2 types of inputs, prepopulated and data and data that requires to be added in the input.
I am trying to submit the form but I am getting nothing in the data base. I have found several related answers but they are old and require that either all the data to pre-populated or all data to be added, but in my form it is a mix of both.
Here is the views:
def addlog(request, pk):
url = request.META.get('HTTP_REFERER')
if request.method == 'POST':
form = LogForm(request.POST)
if form.is_valid():
data = Log()
data.log_workout = form.cleaned_data['log_workout'] <------ prepopulated in template
data.log_repetitions = form.cleaned_data['log_repetitions']<------ not prepopulated in template
data.workout_id = Workout.pk
data.save()
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
Template:
<form
class="review-form" action="{% url 'my_gym:addlog' workout.id %}" method="post">
{% csrf_token %}
<input hidden type="text" name="log_workout" value="{{ object.name }}" required id="id_log_workout">
<input name="log_repetitions" required id="id_log_repetitions">
</div>
<button type="submit">
</button>
</form>
here is log model:
class Log(models.Model):
log_workout = models.CharField(max_length = 30, blank=True, null=True)
log_repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True)
class LogForm(forms.Form):
log_workout =forms.CharField()
log_repetitions = forms.IntegerField()
class Meta:
model = Log
fields = ['log_workout','log_repetitions']
a clarification before adding the input forms in the template I used {{ form|crispy }} and when I manually add data it went to the server.
Solution
You can access them through the request object. request.POST.get('log_workout')
the value should be posted because it's inside the form tag
Edit: this is only for extra fields not in forms.py
General Form Debugging Format (reference)
if request.method == 'POST':
print(request.POST)
form = FormToSave(request.POST)
if form.is_valid():
print('Valid!')
form.save()
else:
print(form.errors)
# or
print(form.errors.as_data())
^ I automatically place these prints when doing a form, and then I delete them when I know everything is working correctly
Answered By - Nealium
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.