Can anyone help me with this issue - Django View (Passing of keys) - html

I have the following views:
def device_port(request):
devices = Device.objects.all()
if request.method == "POST":
selected=request.POST.get('device')
devices = Device.objects.get(pk=selected)
tablename = 'dev_interface_'+selected
print("tablename: " +tablename)
cursor=connection.cursor()
cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2")
righttable = cursor.fetchall()
return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} )
return render(request, 'interface/device_port.html',{'devices':devices})
def device_port_selected(request, pk):
if request.method == "POST":
job = JobForm(request.POST)
device = devices.hostname
print(devices)
#job.associateddevice = devices.hostname
try:
selection=request.POST.get('portrange')
except:
selection = ""
messages.warning(request, "Please select the ports")
print(selection)
#job.associatedinterface = selection
return render(request, 'interface/device/port/selected/'+device+'.html',{'devices':devices, 'righttable':righttable} )
return render(request, 'interface/device_port_selected.html',{'devices':devices, 'selected': selected, 'righttable':righttable} )
urls.py
urlpatterns = [
path('', views.home, name='interface-home'),
path('device/', DeviceListView.as_view(), name='interface-device'),
path('device_edit/<int:pk>/', views.device_edit, name='device-edit'),
path('device_delete/<int:pk>/', views.device_delete, name = 'device-delete'),
path('device_add/', views.device_add, name='device-add'),
path('device/port/', views.device_port, name='device-port'),
path('device/port/selected/', views.device_port_selected, name='device-port-selected'),
path('device/routeport/', views.device_routeport, name='device-routeport'),
path('interface/', views.interface_list, name='interface-list')
]
device_port.html
<form method="POST">
<div class="form-row align-items-center">
<div class="col-md-5 my-1">
{% csrf_token %}
<label for="Hostname">Hostname</label>
<div class="input-group">
<select id = "list" class="custom-select mr-sm-2" onchange="getSelectValue();">
<option selected>Select</option>
{% for device in devices %}
<option value={{device.id}}>{{device.hostname}}</option>
{%endfor%}
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Go</button>
</div>
</div>
</div>
</div>
<input type ="text" name="device" id= "txtvalues" style="display:none">
</form>
So there are 2 page I am dealing with over here (/device/port and /device/port/selected). In this first page /device/port, user is required to pick a value from the drop down box and press the button Go. From here, it is intended to go to the next page which is /device/port/selected with the selected value in the first page pass to the next page.
But with the following code, I receive the error of
device_port_selected() missing 1 required positional argument: 'pk'
when moving from the first page to the next page.

You can't pass a context dictionary to a redirect. The second argument should be the URL arguments, not a context. So change the following line:
return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} )
to
return redirect('device-port-selected', pk=selected)
Note that it is better to use the name of the URL (i.e. device-port-selected) instead of the whole path as you can change paths in the future without affecting the rest of your code.

Related

How can I edit manytomanyfield data

I am trying to edit manytomanyfield data. Here is my model
class Permission(models.Model):
shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True)
permission_title = models.CharField(max_length=255)
class Meta:
ordering = ["-id"]
def __str__(self):
return self.permission_title
class Roles(models.Model):
shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True)
role_title = models.CharField(max_length=255)
permissions = models.ManyToManyField(Permission)
class Meta:
ordering = ["-id"]
def __str__(self):
return self.role_title
Here in these models i have a model called permission. this model is in a manytomanyfield relation with Roles model. I want to edit this manytomanyfield. I have already did the creation part. But now i want to edit the data and I want to show the data in the templates, I chose while creating a role. I want to show it an input type checkox
Here is my views:-
def createRolesView(request, shop_id):
shopId = get_object_or_404(Shop, pk=shop_id)
permissions = Permission.objects.filter(
shop=shopId.id
)
if shopId.user == request.user:
if request.method == "POST":
role_title = request.POST.get("role_title")
shop = Shop.objects.get(id=shopId.id)
permissions = request.POST.getlist("permissions")
rl = Roles(
role_title = role_title,
shop = shop,
)
rl.save()
for p in permissions:
rl.permissions.add(p)
rl.save()
return redirect(f"/adminpanel/roles/{shopId.id}/")
args = {
"shopId": shopId,
"permissions": permissions,
}
return render(request, "roles/create-role.html", args)
else:
return redirect("warning")
def editRolesView(request, role_id, shop_id):
shopId = get_object_or_404(Shop, pk=shop_id)
roleId = get_object_or_404(Roles, pk=role_id)
if shopId.user == request.user:
if request.method == "POST":
roleId.role_title = request.POST.get("role_title")
shop = Shop.objects.get(id=shopId.id)
# roleId.permissions_set.all()
args = {
"shopId": shopId,
"roleId": roleId,
}
return render(request, "roles/edit-role.html", args)
else:
return redirect("warning")
Suggestions only, I haven't coded this myself.
[Edit. This question caused an "itch", so I coded it up to conform I was right. Skip ahead for a pretty generic edit M2M view ]
Two simple tables
One showing the current permissions assigned to the role, which has the queryset roles.permissions.all(), along with a "remove" checkbox for each.
The other showing the available permissions with an "add" checkbox for each. The queryset might be permissions.exclude( roles__pk=this_role.pk) (to exclude those already added, although it's harmless to add something already added). You should also exclude any permissions which this roles instance is not allowed to acquire.
You might use Django Formsets, but it's also rather easy to process raw data from request.POST in this case. Your template would basically be a form containing instances of
<input type="checkbox" name="add" value="{{permission.pk}}" >
and
<input type="checkbox" name="remove" value="{{permission.pk}}" >
with appropriate descriptive text gathered from the permission instance.
If it were me I'd display them as tables left and right, but as long as they are inside a <form> with Submit (and Done?) buttons, it's not relevant.
In your POST handling, you'd get the checked pk values with request.POST.getlist('add') and request.POST.getlist('remove'). For each one, revalidate that it was in the original queryset that was rendered into a form, and if the pk values are acceptable
role.permissions.add( permission) # or .remove( permission)
(where permission is the Permissions instance that's been revalidated)
After Submit of the above you'd probably redirect back to the same again so that the user can see that the requested additions and removals have happened. The "Done" button will redirect elsewhere( if "Done" in request.POST ... )
[Edit] The result of causing me an itch I had to scratch ....
class GenericEditM2MView( DetailView):
#model = Model # required as per DetailView
# template_name = # as per DetailView
#m2m_fieldname = None # no longer required if unique: the name of the model's m2m field to operate on
remove_qs = None # defaults to .all() of the m2m field
success_url = '.' # defaults to displaying the modified m2m relationship unless done
done_url = None # where to go if submit="Done", defaults to success_url
"""
template_name must define a form full of checkboxes, obtained from
{% for p in add_qs %}
<input type="checkbox" name="add" value="{{p.pk}}" > {% endfor}
{% for p in remove_qs %}
<input type="checkbox" name="remove " value="{{p.pk}}" > {% endfor}
default is to return to this same view after submit, to show that the changes
have been made. You can supply <input type="submit" name="submit" value="done" />
which will go to done_url instead of success_url
example use:
class PenStockM2MView( GenericEditM2MView):
template_name = 'playpen/edit_m2m.html'
model = PenStock
# m2m_fieldname = 'name' # works it out if ony one M2M field on the model
done_url = '/playpen/OK'
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
# everything works without this __init__ provided self.m2m_fieldname is present and correct.
# if model has only one m2m field, locate it via _meta as default.
# Also check m2m_fieldname is m2m because very confusing errors later if it's not!
f = getattr(self, 'm2m_fieldname', None)
m2m_fieldnames = [ field.name for field in self.model._meta.get_fields() if field.many_to_many ]
model_name = self.model.__name__
if f and not f in m2m_fieldnames:
raise AttributeError( f'field "{f}" is not a many-to-many field in {model_name}')
if not f:
if len( m2m_fieldnames ) == 1:
self.m2m_fieldname = m2m_fieldnames[0]
else:
raise AttributeError( f'Cannot identify a unique many-to-many field in {model_name}' )
def get_add_queryset(self):
field = getattr( self.object, self.m2m_fieldname)
remove_qs = self.get_remove_queryset()
already_there = remove_qs.values_list('pk', flat=True)
return remove_qs.model.objects.exclude( pk__in = already_there) # is qs.model documented?
def get_remove_queryset(self):
if hasattr( self, 'remove_queryset'):
return self.remove_qs
remove_qs = getattr( self.object, self.m2m_fieldname)
return remove_qs.all()
def get_context_data( self, **kwargs):
context = super().get_context_data( **kwargs)
context['add_qs'] = self.get_add_queryset()
context['remove_qs'] = self.get_remove_queryset()
return context
def post( self, request, *args, **kwargs):
self.object = self.get_object()
add = request.POST.getlist('add')
remove = request.POST.getlist('remove')
add_objs = list( self.get_add_queryset().filter(pk__in=add) )
remove_objs = list( self.get_remove_queryset().filter(pk__in=remove) )
field = getattr( self.object, self.m2m_fieldname )
field.add( *add_objs)
field.remove( *remove_objs)
return HttpResponseRedirect( self.get_done_url() or self.get_success_url() )
def get_success_url(self):
return self.success_url
def get_done_url( self):
done = self.request.POST.get("submit", None)
if done == "done" and hasattr(self, 'done_url'):
return self.done_url
return None
And here's a template (not completely generic. Using Bootstrap in base.html.)
<div class="row">
<div class="col-md-3 col-sm-4 col-xs-6">
<h1> Remove </h1>
<table class="table tbl">
{% for p in remove_qs %}
<tr><td>{{p.name }}</td><td><input type="checkbox" name="remove" value="{{p.pk}}" form="the-form" class="BigCheckbox"></td></tr>
{%endfor %}
</table>
</div>
<div class="col-md-3 col-sm-4 col-xs-6">
<h1> Add </h1>
<table class="table tbl">
{% for p in add_qs %}
<tr><td>{{p.name }}</td><td><input type="checkbox" name="add" value="{{p.pk}}" form="the-form" class="BigCheckbox"></td></tr>
{%endfor %}
</table>
</div>
</div>
<div class="row">
<form method="post" id="the-form"> {% csrf_token %}
<input type="submit" name="submit" value="submit" />
 
<input type="submit" name="submit" value="done" />
</form>
</div>

Formsets. Initial data cannot be displayed in ModelChoiceField

In my application, the user can create and edit reports. When rendering the report edit page, the fields are filled with initial data.
I ran into the following problem - one of the fields (operator) does not display the value that I pass to it in the view through the initial argument. Instead, the field either remains empty or takes on a default value, depending on the settings. All other fields are filled with initial data without errors.
I'm using Formsets, the problem field is ModelChoiceField. The initial data is taken from the json array.
As far as I could understand the HTML code - in the problem field "operator", in the "option" tag (it seems to be generated by the Select widget) the "selected" attribute is missing. But how to put this attribute there is not clear. Adding to the confusion is that the "eq_type" field, which is also a select field, is displayed without errors. "selected" appears next to the desired option.
Maybe someone came across a similar one? Please, tell me what could be the problem.
fragment of forms.py:
class AMSEquipmentForm(forms.Form):
EQ_TYPES = (
('panel_antenna', 'панельная антенна'),
('RRL_antenna', 'РРЛ антенна'),
('radio_module', 'радиомодуль')
)
eq_type = forms.ChoiceField(choices=EQ_TYPES, label='Тип')
height = forms.IntegerField(label='Высота')
proportions = forms.IntegerField(label='Размеры')
amount = forms.IntegerField(label='Количество')
manufacturer = forms.CharField(max_length=50, label='Производитель')
model = forms.CharField(max_length=50, label='Модель')
operator = forms.ModelChoiceField(queryset=Operator.objects.all(), label='Оператор') # Проблемное поле
note = forms.CharField(max_length=100, label='Примечание')
eq_type.widget.attrs.update({'class': 'formset-field'})
height.widget.attrs.update({'class': 'formset-field'})
proportions.widget.attrs.update({'class': 'formset-field'})
amount.widget.attrs.update({'class': 'formset-field'})
manufacturer.widget.attrs.update({'class': 'formset-field'})
model.widget.attrs.update({'class': 'formset-field'})
operator.widget.attrs.update({'class': 'formset-field'}) # Проблемное поле
note.widget.attrs.update({'class': 'formset-field'})
fragment of views.py:
def report_update(request, pk):
EquipmentFormset = formset_factory(AMSEquipmentForm, max_num=1)
report = Report.objects.get(idReport=pk)
form = ReportModelForm(instance=report)
formset = EquipmentFormset(initial=json.loads(report.reportEquipAms), prefix='reports_report') # Здесь передаю начальные данные
if request.method == 'POST':
form = ReportModelForm(request.POST or None)
formset = EquipmentFormset(request.POST or None, prefix='reports_report')
if form.is_valid() and formset.is_valid():
report.reportYear = form.cleaned_data['reportYear']
report.reportObject_id = form.cleaned_data['reportObject']
report.reportTemplate_id = form.cleaned_data['reportTemplate']
report.reportTeam_id = form.cleaned_data['reportTeam']
report.reportEquipment_id = form.cleaned_data['reportEquipment']
report.reportWind = form.cleaned_data['reportWind']
report.reportWeather = form.cleaned_data['reportWeather']
report.reportSoil = form.cleaned_data['reportSoil']
report.reportTemp = form.cleaned_data['reportTemp']
report.reportWeather3 = form.cleaned_data['reportWeather3']
report.reportElVoltage = form.cleaned_data['reportElVoltage']
report.reportElCableL = form.cleaned_data['reportElCableL']
report.reportElCableR = form.cleaned_data['reportElCableR']
report.reportElRope = form.cleaned_data['reportElRope']
report.reportElBus = form.cleaned_data['reportElBus']
report.reportMeasuresDate = form.cleaned_data['reportMeasuresDate']
report.reportData = form.cleaned_data['reportData']
report.reportEquipAms = json.dumps(formset.cleaned_data, cls=OperatorEncoder, ensure_ascii=False)
report.save()
return redirect('reports:report-list')
context = {
'report': report,
'form': form,
'formset': formset
}
return render(request, "reports/report_update.html", context)
fragment of models.py:
class Operator(models.Model):
idOperator = models.AutoField(primary_key=True)
operatorName = models.CharField(max_length=45)
operatorReport = models.ForeignKey("Report", null=True, on_delete=models.SET_NULL)
operatorContract = models.ForeignKey("Contract",null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.operatorName
class Meta:
verbose_name = "Оператор"
verbose_name_plural = "Операторы"
Displaying fields in the browser as viewed through the code inspector:
field eq_type:
<select name="reports_report-1-eq_type" class="formset-field" id="id_reports_report-1-eq_type">
<option value="panel_antenna">панельная антенна</option>
<option value="RRL_antenna" selected>РРЛ антенна</option>
<option value="radio_module">радиомодуль</option>
</select>
field operator:
<select name="reports_report-1-operator" class="formset-field" id="id_reports_report-1-operator">
<option value="8">Оператор3</option>
<option value="9">Оператор2</option>
<option value="10">Оператор1</option>
</select>
A fragment of the html template that is responsible for the form:
{% for equipment in formset %}
<tr class="item">
<td>
{{ equipment.eq_type }}
</td>
<td>
{{ equipment.height }}
</td>
<td>
{{ equipment.proportions }}
</td>
<td>
{{ equipment.amount }}
</td>
<td>
{{ equipment.manufacturer }}
</td>
<td>
{{ equipment.model }}
</td>
<td>
{{ equipment.operator }}
</td>
<td>
{{ equipment.note }}
</td>
<td>
<button type="button" class="btn btn-danger btn-sm remove-form-row" id="{{ formset.prefix }}">Delete</button>
</td>
</tr>
{% endfor %}
update
The initial data that I transfer in reportEquipAms looks like this:
[
{
'eq_type': 'panel_antenna',
'height': 18,
'proportions': 10,
'amount': 1,
'manufacturer': 'manufacturer_name',
'model': 'some model',
'operator': 'Оператор2', # Operator class object
'note': 'some note'
},
]
The list can contain one or more dictionaries. Based on the number of fields in the formset.
#NKSM told me in comment that I should pass the primary key of the Operator object in the "operator" field. I passed the name of the object there.
I rewrote OperatorEncoder:
class OperatorEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Operator):
return obj.idOperator
return json.JSONEncoder.default(self, obj)
Now everything works as it should.

django response method POST don't render to the html template

I have two request function in views one is with .get method and the other one with .post. Both of the function works properly because in the the terminal the code is 200.
[01/Apr/2021 08:04:39] "GET /search/search HTTP/1.1" 200 4164
[01/Apr/2021 08:04:57] "POST /search/search HTTP/1.1" 200 4164
The problem comes when i try to render the function with .post method to the html template nothing appear on the html page.
def wind_search(request):
if request.method == 'post':
city = request.post['city']
weather_city_url = urllib.request.urlopen('api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=1a7c2a40a0734d1dc18141fc6b6241bb').read()
list_of_data = json.loads(waether_city_url)
# main wind information
wind_speed = list_of_data['wind']['speed']
# wind_gust = wea['current']['wind_gust']
wind_deg = list_of_data['wind']['deg']
# wind conversiont m/s to knots
def wind_converter(w):
knots = 2
kt = (float(w)) * knots
return kt
wind_response = wind_converter(wind_speed)
#convert wind degree in cardinal direction.
def degrees_to_cardinal(d):
dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
ix = round(d / (360. / len(dirs)))
return dirs[ix % len(dirs)]
direction = degrees_to_cardinal(wind_deg)
wind_data = {
"wind_response":wind_response,
"wind_direction":direction,
}
else:
wind_data={}
context = {"wind_data":wind_data}
return render(request, 'API/wind_search.html',context)
This is the html template:
{% extends "API/base.html" %}
{% block content %}
<!--Jumbotron -->
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">Wind search</h1>
<p class="lead">Write the city and check th wind condition. </p>
<!-- form input search tool -->
<nav class="navbar navbar-expand-lg navbar-dark">
<form method="post" class="col-md"">
{% csrf_token %}
<div class=" input-group">
<input type="text" class="form-control" name="city" placeholder="Choose Your City ...">
<div class="input-group-btn">
<button type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
</nav>
<div class="row">
{% if wind_response and wind_direction %}
<h4><span>Wind Speed :</span> {{wind_data.wind_speed}}</h4>
<h4><span>Wind_Direction :</span> {{wind_data.wind_direction}}</h4>
</div>
{% endif %}
</div>
{% endblock content %}
I think the problem is with the html because basically the view don't show any error message, so i tried to change couple of time the html code but without success. Any help/ explenation is nice.
Thank you very much.
Please set the render and redirect template,
def wind_search(request):
if request.method == 'POST':
#this block of code manages if there is a POST request...
city = request.POST.get('city')
weather_city_url = urllib.request.urlopen('api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=1a7c2a40a0734d1dc18141fc6b6241bb').read()
list_of_data = json.loads(waether_city_url)
# main wind information
wind_speed = list_of_data['wind']['speed']
# wind_gust = wea['current']['wind_gust']
wind_deg = list_of_data['wind']['deg']
# wind conversiont m/s to knots
def wind_converter(w):
knots = 2
kt = (float(w)) * knots
return kt
wind_response = wind_converter(wind_speed)
#convert wind degree in cardinal direction.
def degrees_to_cardinal(d):
dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
ix = round(d / (360. / len(dirs)))
return dirs[ix % len(dirs)]
direction = degrees_to_cardinal(wind_deg)
wind_data = {
"wind_response":wind_response,
"wind_direction":direction,
}
# the page that you want to load after submitting your POST request <-----------------------------------------------------
return redirect( 'redirect to a view ' )
#the below block of code will cater for the GET method request
else:
wind_data={
'foo' : 'foo'
}
#the page you want to render on a Get Request <-----------------------------------------------------
return render(request,'render the required html for GET request' , wind_data)

how to pass value from html to view in django?

I have made this HTML code:
<h3>your major is {{user.userprofile.major}}</h3>
This will correctly show the major on the webpage, but I want to use this string to get something from another table in view.
How would I pass this string to view?
edit:
Here is my view.py
def dashboardView(request):
obj = BooksFile.objects.all()
query = BooksFile.objects.filter(book_major='cs)
return render(request, 'dashboard.html', {'books': obj, 'major': query})
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('login_url')
else:
form = UserCreationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form': profile_form}
return render(request, 'registration/register.html', context)
here is my template:
{% extends 'index.html' %}
{% block content %}
<h1>Welcome, {{user.username}}</h1>
<h2>Your major is {{user.userprofile.major}}</h2>
{% for book in books %}
<h3>Your book name is {{book.book_name}}</h3>
{% endfor %}
{% endblock %}
I am trying to show the book names from the booksfile table by corresponding major that user has. Right its showing the books that has "cs" attribute because I manually put "cs" in the get function in view. I am trying to send the major string from template to view, so that I can put what ever the user's major is in the get function. Or is there any other way to do it.
You need to use a form in your template and submit it to call your view. i.e.
<form action="your_view_url" method="POST">
<input type="text" name="major" value="{{user.userprofile.major}}"/>
<input type="submit"/>
</form>
an then in your view you access that with:
if request.POST:
major = request.POST.get('major')
As per documentation: https://docs.djangoproject.com/en/2.2/topics/forms/
First of all you have to get the value of model with help of queryset, and put it in the dictionary and then pass it with the template.
In views:
def get(self, request):
queryset = Model_name.objects.all()
ctx = {
'queryset': queryset,
}
return render(request, 'page_name(or template_name).html', ctx)
in template:
<form action="{%url'(your_view_name without brackets)'%}" method="POST">
{% for data in queryset%}
<span class="username">{{data.name(field of your model)}} .
</span>
<span class="email">{{data.email(field of your model)}} .
</span>
{% endfor%}
</form>

Is it possible to loop a custom model form in django?

Is it possible to create multiple objects for a model in django by looping the same form in a for loop. I am using a custom model form.
My template is:
{% for query in queryset %}
<form method="POST" action="{% url 'academics' %}" style=" padding: 5%">
{% csrf_token %}
<input type="text" name="Student" class="form-control" id="id_Student"
value="{{query}}">
<input type="text" name="Subject" class="form-control" required id="id_Subject">
<input type="checkbox" name="Presence" id="id_Presence">
<button type="Submit" id="submit">Submit</button>
{% endfor %}
<button type="Submit" id="submit">Submit</button>
</form>
My models.py is:
class Attendance(models.Model):
Student = models.CharField(max_length=100, blank=False)
Hour = models.CharField(max_length=1, blank=False)
Subject = models.CharField(max_length=8, blank=False)
Date = models.DateTimeField(default=timezone.now)
Presence = models.BooleanField(default=False, blank=False)
def __str__(self):
return f'{self.Student}'
My views.py is:
def academics(request):
if request.user.is_staff:
form = forms.AttendanceForm()
context = {
'form': form,
'queryset': User.objects.filter(profile__Year='SY',profile__Department='CSE')
}
if request.method == "POST" :
form = forms.AttendanceForm(request.POST)
if form.is_valid():
student = request.POST.get('Student')
hour = request.POST.get('Hour')
subject = request.POST.get('Subject')
boolean = request.POST.get('Presence')
def bool(boolean):
if boolean == 'on':
return 'True'
else:
return 'False'
form = Attendance(Student=student,Hour=hour,Subject=subject,Presence=bool(boolean))
form.save()
return render(request, 'console/academics.html',context)
Currently i can create multiple objects, but with the same values of the last form. ie, the object is created with the values of last form. Here i have looped the form so that n number of forms will be generated for n queries with the name filled automatically in the first field. I know explaining this is little complex. Anyone can help?
I'm not entirely clear what you mean by "looping a form", but if you want the user to be able to enter a list of arbitrary length of similar sets of data, then what you want is a Formset or a ModelFormset. When it comes back, you validate all the data that he has submitted, and if it's all good then you iterate through it, usually creating or modifying multiple objects.
Due to reputation I'm unable to comment but I believe this is how you achieve your desired result. by using WHILE LOOP.
I myself have not much knowledge of python & Django but I guess this is the logic. Please correct me if I am wrong instead of down voting.
var = 0
n = 5
if request.method == "POST":
form = forms.AttendanceForm(request.POST)
if form.is_valid():
while var < n:
student = request.POST.get('Student')
hour = request.POST.get('Hour')
subject = request.POST.get('Subject')
boolean = request.POST.get('Presence')
def bool(boolean):
if boolean == 'on':
return 'True'
else:
return 'False'
form = Attendance(Student=student, Hour=hour,Subject=subject,Presence=bool(boolean))
form.save()
var += 1
return render(request, 'console/academics.html', context)