My comment reply function is not working? - django

I am making a blog but I am stuck on a comment replies function. I don't know how to make a Reply function from which users can reply to the comments. I tried a lot but it's still displaying those comments like other comments not as replies to that specific comment.
Here,s the models.py
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
pub_date = models.DateTimeField(auto_now_add = True)
reply = models.ForeignKey('Comment',null = True,blank = True,on_delete=models.CASCADE)
class Meta:
ordering = ['-pub_date']
def __str__(self):
return self.name
#property
def get_replies(self):
return self.replies.all()
class Reply(models.Model):
post = models.ForeignKey(Comment,on_delete=models.CASCADE,related_name = "replies")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
Here's the views.py
def BlogDetail(request,pk):
post = get_object_or_404(Post,pk = pk)
comment = CommentForm(request.POST or None)
subscribe = Subscribe()
reply = ReplyForm(request.POST or None)
if request.method == 'POST':
subscribe = Subscribe(request.POST)
comment = CommentForm(request.POST)
reply = ReplyForm(request.POST)
if comment.is_valid():
comment.instance.post = post
comment.save()
elif subscribe.is_valid():
subscribe = subscribe.save(commit = True)
return redirect('index')
elif reply.is_valid():
reply.instance.com = com
reply = reply.save(commit = True)
return redirect('index')
return render(request,'app/blog.html',{'blog_object':post,'comment':comment,
'subscribe':subscribe,'reply':reply,
})
Here,s the blog.html
<form method='POST' action=".">
{%csrf_token%}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-4">
<div class="col-inner ts-20 m-sm">
<input type="submit" value="Subscribe to my daily letter" class="btn btn-primary subscribe">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-8">
<div class="ts-20">
<div class="form-group form-group-with-icon comment-form-email">
{{subscribe.email}}
</form>
<div class="form-control-border"></div>
</div>
</div>
</div>
</div>
<h3 style="color: #ff714a; font-weight:300;">
Leave a comment
</h3>
{% if request.user.is_authenticated %}
<div class="comments">
<div class="row">
<div class="container">
</div>
<form action="." method="post" id="commentform" class="comment-form">
{% csrf_token %}
<div class="col">
<div class="form-group form-group-with-icon comment-form-email">
{{comment}}
<div class="form-control-border"></div>
</div>
</div>
<div class="col">
<p class="form-submit">
<input name="submit" type="submit" id="submit" class="submit" value="Post Comment">
</p>
</div>
</form>
</div>
{% endif %}
<div class="post-comments">
<h3 style="color: #ff714a; font-weight:300;">See the latest comments</h3>
{% for comment in blog_object.get_comments %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{comment.name}}</strong>
<div class="col comment_body">
<p>{{comment.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
</div>
<form action="." method='POST'>
{% csrf_token %} {{reply}}
<input type="submit" value="submit">
</form>
{% endfor %} {% for reply in com.get_replies %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{reply.name}}</strong>
<div class="col comment_body">
<p>{{reply.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
<div class="reply">
</div>
</div>
</form>
{% endfor %}
</div>

Related

django crispy form does not work in the template

I'm trying to make my form-fields to be in a row like this html code down below, but it does not work, I want all the fields in the PrimryForm class to be in a row not in a column:
Html code:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<input type="text" class="form-control">
</div>
</div>
<div class="col">
<div class="form-group">
<input type="text" class="form-control">
</div>
</div>
<div class="col">
<div class="form-group">
<input type="text" class="form-control">
</div>
</div>
</div>
</div>
Forms.py file:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Row, Column
class PrimaryForms(forms.ModelForm):
signature_of_student = JSignatureField(
widget=JSignatureWidget(
jsignature_attrs={'color':'#e0b642', 'height':'200px'}
)
)
signature_of_guardian = JSignatureField(
widget=JSignatureWidget(
jsignature_attrs={'color':'#e0b642', 'height':'200px'}
)
)
date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
class Meta:
model = Primary
fields = ['admission_number', 'profile_picture', 'first_name',
'last_name', 'gender', 'address_of_student', 'class_Of_student',
'comment_of_student',
'year_of_graduation', 'date_of_birth', 'religion', 'mother_name', 'signature_of_student',
'relationship', 'signature_of_guardian']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-3'
self.helper.field_class = 'col-md-9'
My Form/template:
{% load crispy_forms_tags %}
<div class="container">
<div class="row justify-content-center">
<div class="col">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% crispy form %}
<br>
<button type="submit" class="btn btn-primary">Create Student</button>
</form>
</div>
</div>
</div>
How can I do this using django-crispy-form?
I solve my problem using boostrap-5 ROW and COLUMN in the template
from this template:
{% load crispy_forms_tags %}
<div class="container">
<div class="row justify-content-center">
<div class="col">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% crispy form %}
<br>
<button type="submit" class="btn btn-primary">Create Student</button>
</form>
</div>
</div>
</div>
To This:
{% load crispy_forms_tags %}
<br>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
<div class="form-group row">
<div class="col">
{{form.admission_number|as_crispy_field}}
</div>
<div class="col">
{{form.profile_picture|as_crispy_field}}
</div>
<div class="col">
{{form.first_name|as_crispy_field}}
</div>
<div class="col">
{{form.last_name|as_crispy_field}}
</div>
</div>
<div class="tex-center">
<button type="submit" class="btn btn-primary btn-lg">Create Student</button>
</div>
</div>
</form>

Image not getting uploaded in Django

I tried to save a record using two different methods but both are not working.
Django Form
Models (create method)
1 I have created a ModelForm
class ProductForm(ModelForm):
class Meta:
model= ProductDetails
fields= ("name","category","subcategory","price","mrp","product_details","main_img","img1","img2","img3")
labels={
"name":"Product Name",
"product_details":"Description",
"category":"Category",
"subcategory":"Sub-Category",
"price":"Price",
"mrp":"MRP",
"main_img":"Main Image",
"img1":"Image 1",
"img2":"Image 2",
"img3":"Image 3",
}
widgets = {
'name':forms.TextInput(attrs={'class':'form-control validate',}),
'product_details':forms.TextInput(attrs={'class':'form-control validate',}),
'category':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}),
'subcategory':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}),
'price':forms.TextInput(attrs={'class':'form-control validate',}),
'mrp':forms.TextInput(attrs={'class':'form-control validate',}),
'main_img':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img1':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img2':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img3':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
}
Models File
# For Product details
class ProductDetails(models.Model):
name= models.CharField(max_length=100)
price= models.FloatField()
mrp= models.FloatField()
main_img = models.ImageField(upload_to='product_img')
img1 = models.ImageField(upload_to='product_img')
img2 = models.ImageField(upload_to='product_img')
img3 = models.ImageField(upload_to='product_img')
category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE)
subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE)
product_details = RichTextField(blank=True, null=True)
trending = models.BooleanField(default=False)
def __str__(self):
return self.name
Method 1
Save record using form.save()
getting Form validation error
I have tried by removing main_img,img1,img2,img3 from all place (Forms.py, template, views,py). Then there is not validation error and record is getting saved successfully.
The validation error is just because of some issue with the image uploading
print(form.errors)= <ul class="errorlist"><li>main_img<ul class="errorlist"><li>This field is required.</li></ul></li><li>img1<ul class="errorlist"><li>This field is required.</li></ul></li><li>img2<ul class="errorlist"><li>This field is required.</li></ul></li><li>img3<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
def add_product(request):
if request.method == "POST":
form = ProductForm(request.POST or None, request.FILES or None)
print(form.errors )
if form.is_valid():
category_id = request.POST.get('category')
subcategory_id = request.POST.get('subcategory')
category= Category.objects.get(id=int(category_id))
subcategory= SubCategory.objects.get(id=int(subcategory_id))
form.category = category
form.subcategory = subcategory
form.save()
return redirect("/dashboard/products")
form = ProductForm()
categories=Category.objects.all()
subcategories=SubCategory.objects.all()
return render(request, "01-add-product.html", "form":form,"categories":categories,"subcategories":subcategories})
Method 2
Tried Saving records using models.save()
The record is getting saved but image is not getting uploaded to the media folder
On saving record from Django-admin the image is getting uploaded to proper place i.e. /media.product_img/...
But From this outside HTML its showing the file name in Django-admin but the file is not available in media folder
I already added urlpattern + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my project/urls.py.
Also tried adding the same in urls.py of this app
Note = I have mentioned upload_to=product_img in my model (this may be important to know)
def add_product(request):
if request.method == "POST":
name = request.POST['name']
product_details = request.POST['product_details']
category_id = request.POST.get('category')
subcategory_id = request.POST.get('subcategory')
category= Category.objects.get(id=int(category_id))
subcategory= SubCategory.objects.get(id=int(subcategory_id))
price = request.POST['price']
mrp = request.POST['mrp']
main_img = request.POST['main_img']
img1 = request.POST['img1']
img2 = request.POST['img2']
img3 = request.POST['img3']
product = ProductDetails.objects.create(name=name,product_details=product_details,category=category,subcategory=subcategory,price=price,mrp=mrp,main_img=main_img,img1=img1,img2=img2,img3=img3)
product.save()
Here is my template
{% extends '01-admin-base.html' %}
{% load static %}
{% block content %}
<div class="container tm-mt-big tm-mb-big">
<div class="row">
<div class="col-xl-9 col-lg-10 col-md-12 col-sm-12 mx-auto">
<div class="tm-bg-primary-dark tm-block tm-block-h-auto">
<div class="row">
<div class="col-12">
<h2 class="tm-block-title d-inline-block">Add Product</h2>
</div>
</div>
<div class="row tm-edit-product-row">
<div class="col-xl-6 col-lg-6 col-md-12">
<form action="" method="post" class="tm-edit-product-form">
{% csrf_token %}
{{form.media}}
<div class="form-group mb-3">
<label
for="name"
>Product Name
</label>
{{form.name}}
</div>
<div class="form-group mb-3">
<label
for="category"
>Category</label
>
<select
class="custom-select tm-select-accounts"
id="category" name="category"
>
<option selected>Select category</option>
{% for category in categories %}
<option value="{{category.id}}">{{category.name}}</option>
{% endfor %}
</select>
</div>
<div class="form-group mb-3">
<label
for="subcategory"
>Sub Category</label
>
<select
class="custom-select tm-select-accounts"
id="subcategory" name="subcategory"
>
<option selected>Select sub-category</option>
{% for subcategory in subcategories %}
<option value="{{subcategory.id}}">{{subcategory.name}}</option>
{% endfor %}
</select>
</div>
<div class="row">
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label
for="price"
>Price
</label>
{{form.price}}
</div>
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label
for="mrp"
>MRP
</label>
{{form.mrp}}
</div>
</div>
<div class="form-group mb-3">
<label
for="description"
>Description</label
>
{{form.product_details}}
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-12 mx-auto mb-4">
<div class="custom-file mt-3 mb-3">
<label>Main Image</label>
{{form.main_img}}
</div>
<br><br>
<label>Images</label>
<div class="custom-file mt-3 mb-3">
{{form.img1}}
</div>
<div class="custom-file mt-3 mb-3">
{{form.img2}}
</div>
<div class="custom-file mt-3 mb-3">
{{form.img3}}
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block text-uppercase">Add Product Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
Please help me to get solution for this.
You need to add enctype="multipart/form-data"> in Html form so:
<form action="/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>

How to render error or validation messages to ModelForm in 2022

I've spent several hours researching on the internet, especially the official Django documentation, but still it is not clear to me which is the best option in 2022 (since almost all questions I read on SO are > 6 yo)
and there are diverse opinions on whether crispy forms is better or not.
Is still crispy forms a recommended option?
How can I (and what is the most recommended way to) get the typical validation error messages?
Like: "this field is mandatory" or "this input accepts numbers only"? I've seen some Django pages using those default messages but I don't know how to show them in my ModelForm fields.
Lets say I have the following model:
class Project(models.Model):
project_name = models.CharField(max_length=250, null=False, blank=False)
status = models.CharField(
max_length=250,
null=True,
blank=True,
default=PROJECT_STATUS_DEFAULT,
choices=PROJECT_STATUS,
)
creation_date = models.DateField(max_length=250, null=False, blank=False)
project_code = models.IntegerField(null=True, blank=True)
notes = models.CharField(max_length=250, null=True, blank=True)
And for the Project model I have the following ModelForm:
class CreateNewProjectForm(ModelForm):
creation_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS) #UK Date format
class Meta:
model = Project
fields = '__all__'
The view, when I try to create a new object Project:
def add_new_project(request):
context = {}
if request.method == 'POST':
form = CreateNewProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_page')
else:
print (form.errors)
form = CreateNewProjectForm()
context['form'] = form
return render(request, 'new_project.html', context)
HTML part:
<div class="card h-100">
<div class="card-header project-page-header">
<h3>Create A New Project</h3>
</div>
<div class="card-body px-0 new-project-card-body">
<div class="cardItem">
<div class="row">
<div class="col">
<div class="row">
<div class="tab-pane fade show active" id="general">
<form id="newProjectForm" method="POST" action="new_project">
{% csrf_token %}
<div class="accordion accordion-flush" id="accordionGeneral">
<div class="accordion-item">
<h2 class="accordion-header" id="general-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#general-collapseOne" aria-expanded="false" aria-controls="general-collapseOne">
Details
</button>
</h2>
<div id="general-collapseOne" class="accordion-collapse collapse show" aria-labelledby="general-headingOne" data-bs-parent="#accordionGeneral">
<div class="accordion-body">
<div class="row">
<div class="col-5">
<ul class="list-unstyled">
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Project Name
</div>
<div class="col-sm">
<input type="text" name="project_name" class="form-control" aria-label="Project Name">
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Status
</div>
<div class="col-sm">
<select name="status" class="selectpicker show-tick w-100" aria-label="Status">
{% for status in project_status %}
{% if forloop.first %}
<option value="{{ status.id }}" selected>{{ status.text }}</option>
{% else %}
<option value="{{ status.id }}">{{ status.text }}</option>
{% endif %}
{% endfor %}
</select>
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Creation Date
</div>
<div class="col-sm">
<input type="text" name="creation_date" class="form-control">
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Project Code
</div>
<div class="col-sm">
<input type="text" name="project_code" class="form-control">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="general-headingThree">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#general-collapseThree" aria-expanded="false" aria-controls="general-collapseThree">
Note
</button>
</h2>
<div id="general-collapseThree" class="accordion-collapse collapse" aria-labelledby="general-headingThree" data-bs-parent="#accordionGeneral">
<div class="accordion-body"><textarea name="notes" class="form-control" rows="7"></textarea></div>
</div>
</div>
<button type="submit" id="projectEditBtn" form="newProjectForm" class="btn btn-info rounded-0">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I saw solutions like this, but the problem is that my form fields are spread over different accordions, I can't use something like {% if form.errors %}, I need something more specific for each field.
First update your views like this
def add_new_project(request):
context = {}
if request.method == 'POST':
form = CreateNewProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_page')
else:
print (form.errors)
context['form'] = form
return render(request, 'new_project.html', context)
context['form'] = CreateNewProjectForm()
return render(request, 'new_project.html', context)
You can specify error for each field like this
{% if form.field_name.errors %}
{{ form.field_name.errors }}
{% endif %}

For Loop Populate ID In URL Django

I have a button on my template that says check progress, what the button does is takes you to another page for that user based on their user id.
/points/student_progress/1000 <-- id
What I'm trying to accomplish:
When my for loop runs to populate the student names on my template, i want it also to populate the student ID on the button as well. /points/student_progress/{{student_id}} . Here is my code. How do i add this in ?
Views.py
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
messages.success(request,("Points were successfully added for student !"))
return render(request, 'points/k8_points_classroom.html', context )
if not form.is_valid():
messages.warning(request,(form._errors))
class_name = request.POST.get('class_name')[0]
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
context = {'form': form, 'students': students,}
return render(request, 'points/k8_points_classroom.html', context )
else:
form = K8Points_ClassroomForm()
return render(request, 'points/k8_points_classroom.html', context)
#login_required
def K8_Points(request):
if request.method == 'POST':
form = K8PointsForm(request.POST)
if form.is_valid():
form.save(commit=False)
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
# request.session['k8_points_context'] = context
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
form = K8PointsForm()
return render(request, 'points/k8_points.html', {'form': form} )
def Student_Progress(request, studentpsid):
studentid = Student.objects.get(studentpsid=studentpsid)
if K8Points.objects.filter(student_name=studentpsid).exists():
return render(request, 'points/student_progress.html', {'studentid': studentid} )
else:
return HttpResponseBadRequest("Student doesn't exist !")
HTML Template
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<script> </script>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
<input type="button" onclick="window.location.href = '/points/k8_points';" value="Exit Classroom"/>
</div>
</div>
<br>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary " data-toggle="modal"
data-target="#PointsBox{{student.pk}}"><i class="fas fa-level-up-alt"></i> Level Up
</button>
<i class="fas fa-chart-line"></i> Check Progress
</h4>
<div id="PointsBox{{student.pk}}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
{{form.student_name|as_crispy_field }}
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
<script>
const class_name = "{{class_name}}";
var classnamedropdown = document.getElementById('id_class_name');
for (i = 0; i < classnamedropdown.options.length; i++) {
// if(classnamedropdown.options[i].text == "Mr. Neo 8th Grade Science")
if(classnamedropdown.options[i].text == class_name)
{
console.log(classnamedropdown.options[i].text)
$("#id_class_name").val(classnamedropdown.options[i].value)
}
}
</script>
{% endblock %}
Check Progress
Had to just add the {{i.studentpsid}} in the loop.

Django Form doesn't Get Correct Columns

I have struggled with this for about an hour and cannot seem to find a solution.
I have a django model that I have created form with using ModelForm. The form is inside a view and I want to manipulate the form variables before submitting to the database. The problem is that I cannot seem to get the correct columns to reference from the database for the form. Instead it looks like it is referencing the columns from another related table. Any suggestions?
Models
class RoutinePlans(models.Model):
routine = models.ForeignKey(Routines, on_delete='CASCADE')
exercise = models.ForeignKey(WeightExercises, on_delete='PROTECT')
set = models.IntegerField()
set_type = models.ForeignKey(SetType, on_delete='PROTECT')
reps = models.IntegerField()
day = models.IntegerField()
week = models.IntegerField()
def __str__(self):
return self.routine.name
class Routines(models.Model):
name = models.CharField(max_length=50)
level = models.ForeignKey(RoutineLevels, on_delete='PROTECT')
creator = models.ForeignKey(User, on_delete='CASCADE')
status = models.TextField(max_length=50)
description = models.TextField(max_length=255, null='TRUE', default=None)
def __str__(self):
return self.name
Forms
class PlanForm(forms.ModelForm):
DAY_CHOICES = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'))
day = forms.ChoiceField(widget=forms.Select, choices=DAY_CHOICES)
class Meta:
model = RoutinePlans
exclude = ['routine']
Views
#not sure if this view would have anything to do with the error but figured I would include it to give the full perspective
def createplan(request):
form = forms.CreatePlan()
if request.method == 'POST':
form = forms.CreatePlan(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.name = request.POST['name']
obj.creator_id = request.user.id
obj.status = "DRAFT"
obj.save()
return redirect('fitnessmanagement:editplan', id=obj.pk)
else:
print('error form invalid')
variables = {'form': form}
return render(request, template_name='createplan.html', context=variables)
def editplan(request, routine_id):
form = forms.PlanForm()
routine_name = Routines.objects.get(id=routine_id).name
if request.method == 'POST':
form = forms.PlanForm(data=request.POST)
if form.is_valid():
obj = form.save(commit=False)
#this is where I want to put obj.routine but the form will only pull fields from the Routines model and not the Routine Plans
obj.save()
return redirect('fitnessmanagement:editplan', routine_id=routine_id)
# variables to populate plan
plan = RoutinePlans.objects.filter(routine_id=routine_id)
plan_weeks = RoutinePlans.objects.filter(routine_id=routine_id).values('week').distinct()
plan_dayss = RoutinePlans.objects.filter(routine_id=routine_id).values('day', 'week').distinct()
plan_excercise_name = RoutinePlans.objects.filter(routine_id=routine_id).values('day', 'week', 'exercise_id', 'set_type_id').distinct()
plan_excercise = RoutinePlans.objects.filter(routine_id=routine_id).prefetch_related('exercise')
names = WeightExercises.objects.all()
setDetails = RoutinePlans.objects.filter(routine_id=routine_id).values('set', 'reps', 'day', 'week', 'exercise', 'set_type')
set_type = SetType.objects.all()
# end variables to populate plan
variables = {'form': form,
'id': routine_id,
'routine_name':routine_name,
'plan': plan,
'plan_weeks': plan_weeks,
'plan_exercises': plan_excercise,
'plan_exercise_name': plan_excercise_name,
'plan_days': plan_dayss,
'setDetails': setDetails,
'names': names,
'set_type': set_type,
}
return render(request, template_name='editplan.html',context=variables)
Templates
{% extends 'layout/master-layout.html' %}
{% load static %}
{% block content %}
<section id="content">
<!--start container-->
<div class="container">
<div class="row">
<div class="col s12 m6 l4">
<div class="card-panel">
<h4 class="header2">Add Workout</h4>
<div class="row">
<form class="col s12" method="POST">
{% csrf_token %}
<div class="row">
<div class="input-field col s12">
{{ form.week }}
<label for="weekNumber">Week Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.day }}
<label for="dayNumber">Day Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.exercise }}
<label for="exercise_name">Exercise Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.set_type }}
<label for="set_type">Set Type</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.set }}
<label for="set">Set Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.reps }}
<label for="reps">Rep Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.routine }}
<label for="routine">Routine</label>
</div>
</div>
<div class="row">
<div class="row">
<div class="input-field col s12">
<button class="btn waves-effect waves-light right trusique-red"
type="submit" name="submit">Add Workout
<i class="material-icons right">send</i>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col s12 m6 l8">
<div class="card-panel">
<h4>Editing: {{ routine_name }}</h4>
<ul class="collapsible" data-collapsible="expandable">
{% for plan_week in plan_weeks %}
<li>
<div class="collapsible-header"><i
class="material-icons">whatshot</i>{{ plan_week.week }}- Week
</div>
<div class="collapsible-body">
<ul class="collapsible" data-collapsible="expandable">
{% for plan_day in plan_days %}
{% if plan_day.week == plan_week.week %}
<li>
<div class="collapsible-header">{{ plan_day.day }}- day</div>
<!--collapsible workout name body -->
<div class="collapsible-body">
<ul class="collapsible" data-collapsible="expandable">
<!--begin workout name list-->
{% for plan_exercise in plan_exercise_name %}
{% for n in names %}
{% for s in set_type %}
{% if plan_day.day == plan_exercise.day and plan_week.week == plan_exercise.week and plan_exercise.exercise_id == n.id and plan_exercise.set_type_id == s.id%}
<li>
<div class="collapsible-header">{{ n.exercise_name }}-
Excercise {{ s.type }}
</div>
<div class="collapsible-body">
{% for setDetail in setDetails|dictsort:"set" %}
{# <p> setdetails exerceice {{ setDetail.exercise }}#}
{# plan excerice {{ plan_exercise.id }}</p>#}
{% if plan_day.day == setDetail.day and plan_week.week == setDetail.week and plan_exercise.exercise_id == setDetail.exercise and s.id == setDetail.set_type %}
<div class="row">
<div class="col s12 m4 l4">
Set {{ setDetail.set }}
</div>
<div class="col s12 m4 l4">
: {{ setDetail.reps }}Reps
</div>
</div>
{% endif %}
{% endfor %}
</div>
</li>
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
</ul>
</div>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
<!--end container-->
</section>
<!-- END CONTENT -->
{% endblock %}