Django Form doesn't Get Correct Columns - django

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 %}

Related

how to put my form in line orientation (horizontal). django forms

I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized
MY HTML:
<div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel"
aria-labelledby="profile-tab">
<h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6>
<div class="row mt-4">
<div class="col">
{{ form_funcionarioadicional.management_form }}
{% for fa in form_funcionarioadicional %}
<div class="faform row">
<div class="col">
{{fa}}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
currently it is like this, I wanted to leave it horizontal
How can I fix this in html, or in forms.py?
You can iterate form like this with col class of Bootstrap...
views.py
def Demoview(request):
form = DemoForm()
context = {'form':form}
return render(request,'index.html',context)
form.py
class DemoForm(forms.ModelForm):
class Meta:
model = DemoClass
fields = "__all__"
widgets = {
'field1':forms.TextInput(attrs={'class':'form-control','placeholder':'Field1'}),
'field2':forms.NumberInput(attrs={'class':'form-control','placeholder':'Field2'}),
'field3':forms.EmailInput(attrs={'class':'form-control','placeholder':'Field3'}),
'field4':forms.TextInput(attrs={'class':'form-control','placeholder':'Field4'}),
}
HTML Code
{% block body %}
<div class="container-fluid">
<div class="row">
{% for fm in form %}
<div class="col-6">
<label >{{fm.label}}</label>
{{fm}}
</div>
{% endfor %}
</div>
</div>
{% endblock body %}
Output

IntegrityError at /send/ NOT NULL constraint failed: user_transactions.user_id

enter code heremodels
class Transactions(models.Model):
user=models.ForeignKey(CustomUser,related_name='accounts',on_delete=models.CASCADE, blank=True) recipient_account_type = models.CharField(max_length=230) recipient_name = models.CharField(max_length=100) recipient_acount_number = models.PositiveIntegerField() recipient_routing_number = models.PositiveIntegerField() recipient_bank_name = models.CharField(max_length=200) recipient_swift_code = models.CharField(max_length=100) recipient_sending_amount = models.DecimalField(max_digits=15, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) transaction_ID =models.IntegerField(default=ID) description = models.CharField(max_length=1000)
forms
class TransactionForm(forms.ModelForm):
class Meta:
model = Transactions
fields = ['recipient_account_type','recipient_name','recipient_acount_number',
'recipient_routing_number','recipient_bank_name','recipient_swift_code','recipient_sending_amount','description',]
Widget = forms.TextInput(attrs={'autofocus':'autofocus','size':'40', 'font-size':'xx-large'})
views
#login_required(login_url='/login/')
def send(request):
posts =Transactions.objects.filter(user=request.user)
form = TransactionForm()
if request.method=="POST":
form = TransactionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/success/')
else:
print(form.errors)
# messages.error(request, 'Failed, Resend')
context = {'form':form,'posts':posts}
return render(request, 'index_user/send-money.html', context)
**template**
{% extends 'about/user-base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% load humanize %}
{% block content %}
<!-- Content
============================================= -->
<div id="content" class="py-4">
<div class="container">
<div class="row mt-4 mb-5">
<div class="col-lg-11 mx-auto">
<div class="row widget-steps">
<div class="col-12 step active">
<div class="step-name">Details</div>
</div>
</div>
</div>
</div>
<h2 class="fw-400 text-center mt-3">Send Money</h2>
<p class="lead text-center mb-4">Send your money at anytime, anywhere in the world.</p>
<div class="row">
<div class="col-md-18 col-lg-7 col-xl-6 mx-auto bg-primary">
<div class="bg-white shadow-sm rounded p-3 pt-sm-4 pb-sm-5 px-sm-5 mb-4">
<hr class="mx-n3 mx-sm-n5 mb-4">
<div class="bg-white shadow-sm rounded p- pt-sm-5 pb-sm-5 px-sm-5 mb-4 bg-secondary">
<div class="text-center bg-primary p-4 rounded mb-4">
<h3 class="text-10 text-white fw-400">${{user.account_balance|intcomma}}</h3>
<p class="text-white">Available Balance</p>
{% comment %} Withdraw Full Amount </div> {% endcomment %}
<!-- Send Money Form
============================ -->
<p style="color: red; font-size:large">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</p>
<center style="background-color: #007bff;">
<form id="form-send-money" method="POST" action="" class="bg-success" >
{% csrf_token %}
<div class="mb-3 pb-sm-5 px-sm-5">
{% comment %} <label for="withdrawto" class="form-label">Withdraw From</label> {% endcomment %}
<br>
{% comment %} <select id="withdrawto" class="form-select px-sm-4 pb-sm-1" name="">
<option value="">FNMB Bank - {{user.account_number}}</option>
</select> {% endcomment %}
</div>
<div id="id_long_desk" class="mb-3 px-sm-4 pb-sm-9">
<label for="emailID" class="form-label">Recipient Full Name</label>
<br>
{{form.recipient_name}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Account Number</label>
<br>
{{form.recipient_acount_number}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Bank Name</label>
<br>
{{form.recipient_bank_name}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Routing Number</label>
<br>
{{form.recipient_routing_number}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Swift Code</label>
<br>
{{form.recipient_swift_code}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Account Type</label>
<br>
{{form.recipient_account_type}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Sending Amount</label>
<br>
{{form.recipient_sending_amount}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Description</label>
<br>
{{form.description}}
</div>
{% comment %} <div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Fees</label>
<br>
$ {{form.fees}}
</div> {% endcomment %}
<!-- <p>Transfer Fees <span class="float-end"> 12.21 USD</span></p> -->
<hr>
<div class="d-grid"><button class="submit btn btn bg-white">Send</button></div>
<hr>
</form>
</center>
<!-- Send Money Form end -->
</div>
</div>
</div>
</div>
</div>
<!-- Content end -->
{% endblock %}
Have you checked whether your form is valid with something like the following?
if form.is_valid():
obj = form.save()
else:
# errror handling? debug with form.errors...
If your code does look like above, please add more info (like the form handling method as a whole)

My for loop does not work as expected - Data does not show up in my django template

I am trying to use a for loop in my Django template to show the data stored in the models of a table but for some reason , the data does not show up in the template.
Views.py
def add_part(request):
parts = Parts.objects.all()
context = {
"parts": parts
}
return render(request, 'admintemplate/add_parts_template.html', context)
def add_part_save(request):
if request.method != "POST":
messages.error(request, "Method Not Allowed!")
return redirect('add_part')
else:
part_name = request.POST.get('part_name')
part_type = request.POST.get('part_type')
supplier_id = request.POST.get('suppliers')
suppliers = Suppliers.objects.get(id=supplier_id)
try:
part = Parts(part_name=part_name, part_type=part_type, supplier_id=supplier)
part.save()
messages.success(request, "Part Added Successfully!")
return redirect('add_part')
except:
messages.error(request, "Failed to Add Part!")
return redirect('add_part')
models.py
The parts and the services model are exactly the same with different column names, so I think the functionality for both should be the same.
Suppliers models
class Suppliers(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
Parts model
class Parts(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
part_type = models.CharField(max_length=20)
supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE)
Services model
class Services(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
service_type = models.CharField(max_length=20)
supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE)
Part template
{% extends 'admintemplate/base_template.html' %}
{% block page_title %}
Add Parts
{% endblock page_title %}
{% block main_content %}
{% load static %}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add Parts</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST" action="{% url 'add_part_save' %}">
{% csrf_token %}
{% comment %} Display Messages {% endcomment %}
{% if messages %}
<div class="form-group">
<div class="col-12">
{% for message in messages %}
{% if message.tags == "error" %}
<div class="alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% elif message.tags == "success" %}
<div class="alert alert-success alert-dismissible fade show" role="alert" style="margin-top: 10px;">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
<div class="card-body">
<div class="form-group">
<label>Part Name </label>
<input type="text" class="form-control" name="part_name" placeholder="Part Name">
</div>
<div class="form-group">
<label>Part Type </label>
<input type="text" class="form-control" name="part_type" placeholder="Part Type">
</div>
<div class="form-group">
<label>Supplier Name</label>
<select class="form-control" name="suppliers">
{% for supplier in suppliers %}
<option value="{{ supplier.id }}">{{ supplier.name }}</option>
{% endfor %}
</select>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Add Part</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
</div>
</div><!-- /.container-fluid -->
</section>
{% endblock main_content %}
Now the services in parts template does not show up at all. There is no choices on the form. But, for the add services template, it does populate. I have no idea why this happens because I have used the exact same code for both templates.
Changing the view to this solved the issue
def add_part(request):
parts = Parts.objects.all()
context = {
"suppliers": suppliers
}
return render(request, 'admintemplate/add_parts_template.html', context)

How to combine any fields in one in Django filters

I wonder how you combine search from multiple fields into one. The fields would be textoQuestao, perguntaQuestao, aOpcao, bOpcao, cOpcao, eOpcao, eOpcao.
I would like all of these fields to be combined into one called texto and to search all selected fields.
filters.py
class FiltroQuestoes(django_filters.FilterSet):
texto =
class Meta:
model = Questao
fields = ['textoQuestao','perguntaQuestao','aOpcao','bOpcao','cOpcao','dOpcao','eOpcao','idProva','idQuestao','idCategoria']
views.py
def FiltroDeQuestoesView(request):
qs = filter(request)
context = {
'queryset': qs,
'categorias': Categoria.objects.all(),
'provas': Prova.objects.all()
}
return render(request, "polls/pesquisa.html", context)
def filter(request):
qs = Questao.objects.all()
categorias = Categoria.objects.all()
prova = request.GET.get('prova')
provas = Prova.objects.all()
questao = request.GET.get('questao')
categoria = request.GET.get('categoria')
return qs
search.html
{% block content %}
<form method="get">
<div class="well">
<h4 style="margin-top: 0">Filter</h4>
<div class="row">
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.texto.label_tag }}
{% render_field filter.form.texto class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.idProva.label_tag }}
{% render_field filter.form.idProva class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.idQuestao.label_tag }}
{% render_field filter.form.idQuestao class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.idCategoria.label_tag }}
{% render_field filter.form.idCategoria class="form-control" %}
</div>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</form>
{% endblock %}
I would suggest you should go with elasticsearch for this.
But you can use django Q objects to do OR query
qs = Questao.objects.filter(Q(textoQuestao__icontains=query_string)| Q(perguntaQuestao__icontains=query_string)|...

My comment reply function is not working?

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>