Django request.POST.get does not save to model field - django

I am trying to save data from request.POST dictionary. I would like to get the the 'name' value from request.POST which should correspond to the prefix. However, it does not happen and nothing gets saved to Name model. Also, I get no error. Could you please kindly advise how to solve this case? Thank you.
views.py
from django.shortcuts import render
from .forms import modelformset_factory, AssumptionsForm
from .models import Assumptions
from django.core.exceptions import ValidationError
import pdb
model_names = ['A', 'B']
def get_assumptions(request):
AssumptionFormset = modelformset_factory(
Assumptions, form=AssumptionsForm, extra=5)
if request.method == 'POST':
formsets = [AssumptionFormset(request.POST, prefix=thing) for thing in model_names]
if all([formset.is_valid() for formset in formsets]):
for formset in formsets:
for form in formset:
form.save(commit=False)
form.Name = request.POST.get('name')
form.save()
else:
formsets = [AssumptionFormset(prefix=thing) for thing in model_names]
return render(request, 'assumptions.html', {'formsets': formsets})
assumptions.html
<div class="form">
<form action="" method="post">
{% for formset in formsets %}
{% csrf_token %}
{{ formset.management_form }}
{{ formset.non_form_errors.as_ul }}
<h1>{{formset.prefix}}</h1>
<table id="formset" class="form">
{% for form in formset.forms %}
{% if forloop.first %}
<thead><tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr></thead>
{% endif %}
<tr class="{% cycle 'row1' 'row2' %}">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="hidden" id={{formset.prefix}} name={{formset.prefix}} />
{% endfor %}
<input type="submit" value="Submit">
</form>
</div>
forms.py
from django import forms
from django.forms import modelformset_factory, ModelForm
from .models import Assumptions
class AssumptionsForm(ModelForm):
class Meta:
model = Assumptions
fields = '__all__'
exclude = ['Name']
models.py
from django.db import models
from django.forms import ModelForm
class Assumptions(models.Model):
Worst = models.FloatField(null=True, blank=True, default=None)
Base = models.FloatField(null=True, blank=True, default=None)
Best = models.FloatField(null=True, blank=True, default=None)
Name = models.TextField(null=True, blank=True, default=None)

You should also pass "name=name" and "value={{formset.prefix}}" in your HTML form.
<input type="hidden" id={{formset.prefix}} name="name" value="{{formset.prefix}}" />

I figured out. The reason is that instance of the model was not created. Code should be as follows:
for form in formset:
assumption_data = form.save(commit=False)
assumption_data.Name = request.POST['name']
assumption_data.save()
where assumptions_data is an instance of Assumptions model. Thank you everyone for insights provided.

Related

How can I 'bound' a modelformset to an object, fill it and editing in the same page?

I m new in Django and development.
I have a items list, and when I clik on the result button of a test, I would like to have a modelformset for this specific test where i can fill it and editing in the same page.
The code I wrote is 'working' but the problem it's when I fill the form and submit it, it' s editing the same for all the test.
I hope you will understand my explanation( not english speaker)
Here my code:
model.py:
class ResultatTest(models.Model):
id = models.AutoField(primary_key=True)
test = models.ForeignKey('Test', on_delete=models.CASCADE)
services = models.CharField(max_length=30, choices=SERV_CHOICES)
notes = models.IntegerField(null=True)
comments = models.TextField()
def __str__(self):
return self.services
view.py:
def resultatTest(request, id):
id = get_object_or_404(Test, pk=id)
ResultatTestFormset = modelformset_factory(ResultatTest, fields=('test', 'services', 'notes', 'comments'),extra=1)
if request.method == "POST":
formset = ResultatTestFormset(request.POST)#queryset=form.object.filter(test=test_id)
if formset.is_valid():
instances = formset.save(commit= False)
for instance in instances:
instance.save()
else:
formset = ResultatTestFormset()
return render(request, "Portail/Details/resultat.html", {'id': id,'formset': formset})
items/test.html:
onclick ="window.location ='/resultat/{{test.id}}','_self';
url.py:
path('resultat/<int:id>/',resultatTest,name='resultat'),
resultat.html:
<form action="" method="post" id="resultatForm ">
{% csrf_token %}
<table id='supertable' border=1>
{{ formset.management_form }}
{% for form in formset %}
{% if forloop.first %}
<tr>
{% for field in form.visible_fields %}
<td style="background: cyan; line-height:1; white-space:nowrap;width:500px;" >{{ field.label_tag }}</td><
{% endfor %}
</tr>
{% endif %}
<tr>
{% for field in form.visible_fields %}
<td style="background: white; line-height:1; white-space:nowrap;" > {{ field}}</td>
{% endfor %}
</tr>
{ % endfor %}
I have tried and search a lot of things but I cannot solve my problem.

Django template does not output multiple forms and save to modelform

the issue is that template does not output multiple forms and save to Assumptions modelform. I am trying to save input from multiple forms by adding different names from template to Assumptions.Name field in Assumptions model. However, this approach does not work for some reason. Advise how to solve it would be highly appreciated. Thank you in advance.
views.py
from django.shortcuts import render
from .forms import modelformset_factory, AssumptionsForm
from .models import Assumptions
def get_assumptions(request):
if request.method == 'POST':
if 'name' in request.POST:
formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5)
if formset.is_valid():
print('valid form')
for form in formset:
print('Looping forms')
assumptions = form.save(commit='False')
assumptions.Name = 'name'
assumptions.save()
formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5)
return render(request, 'assumptions.html', {'formset': formset})
assumptions.html
{% for name in "AB" %}
<div class="form">
<form action="" method="post">
{% csrf_token %}
{{ formset.management_form }}
{{ formset.non_form_errors.as_ul }}
<table id="formset" class="form">
{% for form in formset.forms %}
{% if forloop.first %}
<thead><tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr></thead>
{% endif %}
<tr class="{% cycle 'row1' 'row2' %}">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" name="{{name}}" value="save" />
</form>
</div>
{% endfor %}
models.py
from django.db import models
from django.forms import ModelForm
class Assumptions(models.Model):
Worst = models.FloatField(null=True, blank=True, default=None)
Base = models.FloatField(null=True, blank=True, default=None)
Best = models.FloatField(null=True, blank=True, default=None)
Name = models.TextField(null=True, blank=True, default=None)
forms.py
from django import forms
from django.forms import modelformset_factory, ModelForm
from .models import Assumptions
class AssumptionsForm(ModelForm):
class Meta:
model = Assumptions
fields = ['Worst', 'Base', 'Best']
exclude = ['Name']

Django looping formsets cause ValidationError in management form

I am trying to output two same forms and save them to database with different prefix. I used this post https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ as an example. However I get validation error that management form is being tampered with. Could you please kindly advise how to solve it? Thank you.
Also is it possible to filter database by the prefix in this case if i want to retrieve the data later for analysis.
VIEWS.PY
from django.shortcuts import render
from .forms import modelformset_factory, AssumptionsForm
from .models import Assumptions
model_names = ['Form1', 'Form2']
def get_assumptions(request):
AssumptionsFormset = modelformset_factory(
Assumptions, form=AssumptionsForm, extra=5)
if request.method == 'POST':
formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names]
if all([formset.is_valid() for formset in formsets]):
for formset in formsets:
for form in formset:
form.save()
else:
formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names]
return render(request, 'assumptions.html', {'formsets': formsets})
ASSUMPTIONS.HTML
<div class="form">
<form action="" method="post">
{% csrf_token %}
{% for formset in formsets %}
{{ formset.management_form }}
{{ formset.non_form_errors.as_ul }}
<h1>{{formset.prefix}}</h1>
<table id="formset" class="form">
{% for form in formset.forms %}
{% if forloop.first %}
<thead><tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr></thead>
{% endif %}
<tr class="{% cycle 'row1' 'row2' %}">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit">
{% endfor %}
</form>
</div>
MODELS.PY
from django.db import models
from django.forms import ModelForm
class Assumptions(models.Model):
Worst = models.FloatField(null=True, blank=True, default=None)
Base = models.FloatField(null=True, blank=True, default=None)
Best = models.FloatField(null=True, blank=True, default=None)
FORMS.PY
from django import forms
from django.forms import modelformset_factory, ModelForm
from .models import Assumptions
class AssumptionsForm(ModelForm):
class Meta:
model = Assumptions
fields = '__all__'
You are trying to initialize the formsets with request.POST on GET requests, which of course can't work.
Replace the second
formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names]
with
formsets = [AssumptionsFormset(prefix=thing) for thing in model_names]

Saving from a django-leaflet widget

I am having trouble saving the point coordinates from a django-leaflet form. I can display the leaflet widget and add point markers but when I submit the form no geometry is sent. I know this from looking at what is posted back to the server in FireBug.
e.g.
csrfmiddlewaretoken 3fOhKMkrlMqIvQfqsq6Myx9agpsif2aQ
geom
name test
submit Save
Here is the code:
forms.py
from leaflet.forms.fields import MultiPointField
class LocationForm(forms.ModelForm):
geom = MultiPointField()
class Meta:
model = Location
fields = ['name', 'geom']
models.py
from leaflet.forms.fields import MultiPointField
class Location(models.Model):
locationid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=256)
geom = MultiPointField()
def __unicode__(self):
return self.name
template file
{% load leaflet_tags %}
{% leaflet_js plugins="forms" %}
{% leaflet_css plugins="forms" %}
<form id="location_form" method="post" action="/addlocation/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text}}
{{ field }}
{% endfor %}
<div class="login-actions">
<button type="submit" name="submit" value="Save">Save</button>
</div> <!-- .actions -->
</form>
May be you missed, in settings:
'ENGINE': 'django.contrib.gis.db.backends.mysql', # if use mysql
in models:
from django.contrib.gis.db import models as gismodels
class Location(gismodels.Model):

django forms comments not visible

i can add comments in db and see its in admin panel but dont see added comments in posts (view_post.html).
i dont understand reason for this
models:
class Comment(models.Model):
name = models.CharField('Имя:', max_length=100)
create_date = models.DateField(blank=True, null=True)
text = models.TextField()
def __str__(self):
return '%s' % self.name
forms:
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['name', 'create_date', 'text']
views:
def view_post(request, slug):
post_detail = get_object_or_404(Article, slug=slug)
form = CommentForm(request.POST or None)
if form.is_valid():
comment = form.save(commit=False)
comment.post_detail = post_detail
comment.save()
return redirect(request.path)
return render_to_response('view_post.html', {
'post_detail': post_detail, 'form': form },
context_instance=RequestContext(request))
post template:
{% extends 'base.html' %}
{% block head_title %}{{ post_detail.title }}{% endblock %}
{% block title %}{{ post_detail.title }}{% endblock %}
{% block content %}
{{ post_detail.body }}
{% if post_detail.comment_set.all %}
{% for comment in post_detail.comment_set.all %}
{{ comment.name }}
{{ comment.text }}
{% endfor %}
{% endif %}
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" name="submit" value="Submit" />
</form>
{% endblock %}
You set comment.post_detail to the current Article when saving, but there you don't actually seem to have a post_detail ForeignKey. In fact you don't seem to have any relationship between Comment and Article at all, or between Comment and anything.