I am using Flask, SqlAlchemy, and WT Forms. I have done many forms on this project, but this particular form doesn't submit. I've gone over it several times. I have tried printing forms.errors (No errors btw). I have {{ form.hidden_tag() }}. I'm pretty sure that it is something simple that I am overlooking.
My html:
{% extends "layouts/base.html" %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Load</title>
{% block head %}
{% endblock %}
<style>
</style>
</head>
<body>
{% block content %}
<h1>Add Load</h1>
<div class="container">
<div class="row">
<div class="col-md-4">
<form method="POST", action="/loads/add_load">
{{ form.hidden_tag() }}
<div class="form-outline mb-4">
{{ form.broker_id.label }} <br>
{{ form.broker_id(class_="form-control") }}
</div>
<div class="form-outline mb-4">
{{ form.carrier_id.label }} <br>
{{ form.carrier_id(class_="form-control", id="select_carrier", onchange="get_drivers()") }}
</div>
<div class="form-outline mb-4">
{{ form.driver_id.label }} <br>
{{ form.driver_id(class_="form-control", id="select_driver") }}
</div>
<div class="form-outline mb-4">
{{ form.load_number.label }}
{{ form.load_number(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.rate.label }}
{{ form.rate(class_="form-control", size=32) }}
</div>
</div>
<div class="col-md-4">
<div class="form-outline mb-4">
{{ form.weight.label }}
{{ form.weight(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.detention_time.label }}
{{ form.detention_time(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.detention_fee.label }}
{{ form.detention_fee(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.lumper_fee_total.label }}
{{ form.lumper_fee_total(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.lumper_fee_paid_by_carrier.label }}
{{ form.lumper_fee_paid_by_carrier() }}
</div>
</div>
<div class="col-md-4">
<div class="form-outline mb-4">
{{ form.layover_fee_total.label }}
{{ form.layover_fee_total(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.tonu_fee.label }}
{{ form.tonu_fee(class_="form-control", size=32) }}
</div>
<div class="form-outline mb-4">
{{ form.status.label }}
{{ form.status(class_="form-control") }}
</div>
<div class="form-outline mb-4">
{{ form.notes.label }}
{{ form.notes(class_="form-control", size=32) }}
</div>
<br><br><br><br>
<button type="submit" class="btn btn-primary float-end">Submit</button>
</form>
</div> <!--end column-->
</div> <!--end row-->
</div> <!--end container-->
</body>
{% endblock %}
</html>
Form:
class AddLoadForm(FlaskForm):
broker_id = SelectField('Broker', choices=[])
carrier_id = SelectField('Carrier', choices=[])
driver_id = SelectField('Driver', choices=[], validators=[InputRequired(), Length(min=1, max=80)])
load_number = StringField('Load Number:')
rate = DecimalField('Rate:')
weight = IntegerField('Weight')
detention_time = IntegerField('Detention Time (minutes)')
detention_fee = DecimalField('Detention Fee',places=2)
lumper_fee_total = DecimalField('Lumper Fee Total',places=2)
lumper_fee_paid_by_carrier = BooleanField('Carrier Pays Lumper Fee')
layover_fee_total = DecimalField('Layover Fee Total',places=2)
tonu_fee = DecimalField('TONU Fee',places=2)
status = SelectField('Status:', choices=load_status_choices)
notes = TextAreaField('Notes', id="textfield")
View Function:
#loads_blueprint.route('/add_load', methods=['GET', 'POST'])
#login_required
def add_load():
dispatcher_id = current_user.id
broker_choices = db.session.query(Broker.id, Broker.brokerage_name).filter(current_user.company_id==Broker.dispatch_company_id).all()
carrier_choices = db.session.query(Carrier.id, Carrier.company_name).filter(current_user.company_id==Carrier.dispatch_company_id).all()
load = db.session.query(Loads)
form = AddLoadForm(obj=load)
form.broker_id.choices = [(b[0], b[1]) for b in broker_choices]
form.carrier_id.choices = [(c[0], c[1]) for c in carrier_choices]
print(form.errors,"Before if <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
if form.validate_on_submit():
print("Form was validated <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
ins = Loads(
dispatcher_id = dispatcher_id,
broker_id = int(form.broker_id.data),
carrier_id = int(form.carrier_id.data),
driver_id = int(form.driver_id.data),
load_number = form.load_number.data,
rate = float(form.rate.data),
weight = int(form.rate.data),
detention_time= int(form.detention_time.data),
detention_fee = float(form.detention_fee.data),
lumper_fee_total = float(form.lumper_fee_total.data),
lumper_fee_paid_by_carrier = float(form.lumper_fee_paid_by_carrier.data),
layover_fee_total = float(form.layover_fee_total.data),
tonu_fee = float(form.tonu_fee.data),
status = form.status.data,
notes = form.notes.data
)
db.session.add(ins)
db.session.commit()
#Get ID of added load
last_load_id = db.session.query(Loads.id).filter(Loads.dispatcher_id==dispatcher_id).order_by(desc(id)).first()
return redirect(url_for('loads.edit_load',load_id = last_load_id))
return render_template("/loads/add_load.html", form=form)
Here is a version where I replaced if form.validate_on_submit(): with a try block. It works but I want to be able to use the forms correctly.
#loads_blueprint.route('/add_load', methods=['GET', 'POST'])
#login_required
def add_load():
dispatcher_id = current_user.id
broker_choices = db.session.query(Broker.id, Broker.brokerage_name).filter(current_user.company_id==Broker.dispatch_company_id).all()
carrier_choices = db.session.query(Carrier.id, Carrier.company_name).filter(current_user.company_id==Carrier.dispatch_company_id).all()
load = db.session.query(Loads)
form = AddLoadForm()
form.broker_id.choices = [(b[0], b[1]) for b in broker_choices]
form.carrier_id.choices = [(c[0], c[1]) for c in carrier_choices]
try: #Couldn't get form to validate on submit
ins = Loads(
dispatcher_id = dispatcher_id,
broker_id = int(form.broker_id.data),
carrier_id = int(form.carrier_id.data),
driver_id = int(form.driver_id.data),
load_number = form.load_number.data,
rate = float(form.rate.data),
weight = form.weight.data,
detention_time= int(form.detention_time.data),
detention_fee = float(form.detention_fee.data),
lumper_fee_total = float(form.lumper_fee_total.data),
lumper_fee_paid_by_carrier = float(form.lumper_fee_paid_by_carrier.data),
layover_fee_total = float(form.layover_fee_total.data),
tonu_fee = float(form.tonu_fee.data),
status = form.status.data,
notes = form.notes.data
)
db.session.add(ins)
db.session.commit()
#Get ID of added load
#last_load_id = db.session.query(Loads.id).filter(Loads.dispatcher_id==dispatcher_id).order_by(desc(id)).first()
return redirect(url_for('main.dashboard'))
except Exception as e:
print(e)
return render_template("/loads/add_load.html", form=form)
Your route is add_load, so you are trying to add. you need to change the following line from:
form = AddLoadForm(obj=load)
to
form = AddLoadForm()
if you are using the same route for editing and adding or you want the form to be filled for some reason then use:
form = AddLoadForm()
if request.method="GET":
form = AddLoadForm(obj=load)
I hope this will help.
Related
I would like to ask you, is there a possibility to render only part of page? I have a block with some fields and a possibility to add new block. I guess just copying the original element into hidden field is not the best practice, but rendering the same template after each added part.
retrieve_reports.html:
{% for pd in form.ProductsDims %}
{{ pd.form.hidden_tag() }}
<div class="box-body with-border" id="reports{{loop.index0}}">
<div class="col-md-10">
{{ pd.form.name.label }}
</div>
{{ pd.form.name(class="form-control input-sm") }}
<div class="retrieval_default">
<div class="col-md-6">
<p style="text-align:left;">{{ pd.form.dims.label }}</p>
{{ pd.form.dims() }}
<script> new SlimSelect({select: "#ProductsDims-{{loop.index0}}-dims" })</script>
</div>
<br>
<div class="col-md-6">
<p style="text-align:left;">{{ pd.form.products.label }}</p>
{{ pd.form.products() }}
<script> new SlimSelect({select: "#ProductsDims-{{loop.index0}}-products" })</script>
</div>
{% if pd.form.name.data=="Historical" %}
<div class="col-md-6"><br>
<p style="text-align:left;">{{ pd.form.deal_date.label }}</p>
<div class="input-group date">
<input type="text" data-date-format="yyyy-mm-dd" data-provide="datepicker" autocomplete="off"
class="form-control pull-right input-sm" name="deal_date" id="deal_date"
placeholder="YYYY-MM-DD" value="{{pd.form.deal_date.data}}" title="Default value is Now + 60 days">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
</div>
{% for error in pd.form.deal_date.errors %}
<span class="fa fa-circle-o text-red"> {{ error }}</span>
{% endfor %}
</div>
{% endif %}
</div>
</div>
retrieve_reports_route.py:
def route_retrieveresults():
form = RetrieveResultsForm(request.form)
filetail = ""
filename = ""
rootdir = f"temporary\\{user.id}\\"
dims = [dims.dims_name.replace("\n", "") for d in Dims.query().all()]
for pd in form.ProductsDims:
pd.products.choices = [(item, item) for item in pd.form.products.data]
pd.dims.choices = [(item, item) for item in dims]
...
if (request.method == 'GET'):
...
if request.form.get('Submit') == 'submit':
...
return render_template('retrieve_reports.html',
form=form,
errors_present=errors_present,
filename=filename,
email_form=SendEmailForm(),
user_email=user.email if current_user.is_authenticated else "",
user_id=user.id if user.is_authenticated else ""
)
I have a problem with the following;
I have a dependent dropdown menu in a Django model form. Now I want to use it several times in the same form but I can't get it to work if I load more than one then I can only enter/use one. And I have a 2nd problem if this works how do I get the different values in a list/array so that I can store them in the db?
The ultimate goal is to select how many beams are desired and on that basis to be able to enter the desired hours, ion species, energy and flux per beam.
My code is as follows:
models.py
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
class IonSpecies(models.Model):
# ionspecie = models.CharField(max_length=10)
Name = models.CharField(max_length=10)
def __str__(self):
# return self.ionspecie
return self.Name
class Energys(models.Model):
Ion_Species = models.ForeignKey(IonSpecies, on_delete=models.CASCADE)
Name = models.CharField(max_length=50)
def __str__(self):
# return self.energy
return self.Name
# Create your models here.
class CreateBeamRequestModel(models.Model):
#status choices
SELECT = 'Select'
REQUEST = 'Request'
TENTATIVE = 'Tentavive'
ACCEPTED = 'Accepted'
CONFIRMED = 'Confirmed'
CANCELLED = 'Cancelled'
COMPLETED = 'Completed'
QUEUED = 'Queued'
STATUS_CHOICES = [
(SELECT, ('Select an option')),
(REQUEST, ('Request')),
(TENTATIVE, ('Tentative')),
(ACCEPTED, ('Accepted')),
(CONFIRMED, ('Confirmed')),
(CANCELLED, ('Cancelled')),
(COMPLETED, ('Completed')),
(QUEUED, ('Queued')),
]
#different beam choices (1 to 4)
DIFBEAMS_CHOICES = [tuple([x,x]) for x in range(1,5)]
#shift choices (1 to 16 is max a week)
SHIFTS_CHOICES = [tuple([x,x]) for x in range(1,17)]
#fields of the model
Project_Code = models.CharField(unique=True, max_length=20, blank = True)
Pac_Rate = models.CharField(max_length=10, blank = True)
Partrec_Contact_Name = models.CharField(max_length=50, blank = True)
Partrec_Contact_Email = models.EmailField(blank = True)
Previous_Experiment = models.CharField(max_length=200, blank = True)
Status = models.CharField(max_length=25, choices=STATUS_CHOICES, default='SELECT')
Project_Title = models.CharField(max_length=100, blank = True)
Spokesperson_Name = models.CharField(max_length=50, blank = True)
Spokesperson_Adress = models.CharField(max_length=50, blank = True)
Spokesperson_Phonenumber = models.CharField(max_length=20, blank = True)
Spokesperson_Email = models.EmailField(blank = True)
Collaborator_Name = models.TextField(blank = True)
Collaborator_Nationality = models.TextField(blank = True)
Collaborator_Home_Institute = models.TextField(blank = True)
Different_Beams = models.IntegerField(choices=DIFBEAMS_CHOICES, default='1')
# Shifts = models.IntegerField(choices=SHIFTS_CHOICES, default='1')
Hours = models.IntegerField(default='1')
Ion_Species = models.ForeignKey(IonSpecies, on_delete=models.CASCADE)
Energy = ChainedForeignKey(Energys, chained_field="Ion_Species", chained_model_field="Ion_Species", show_all=False, auto_choose=True)
Flux = models.CharField(max_length=50, blank = True, null = True)
Start_Date = models.DateTimeField(blank = True, null=True)
End_Date = models.DateTimeField(blank = True, null=True)
Requiered_Equipment = models.TextField(blank = True)
Special_Requirements = models.TextField(blank = True)
Special_Safety_Procedures = models.TextField(blank = True)
Lab_Support_Requirements = models.TextField(blank = True)
Funded = models.TextField(blank = True)
Summary = models.TextField(blank = True)
def __str__(self):
return self.Project_Code
def get_absolute_url(self):
return f"/beamrequest/{self.Project_Code}"
def get_edit_url(self):
return f"{{self.get_absolute_url}}/update/"
def get_delete_url(self):
# return f"/beamrequest/{self.Project_Code}/delete/"
return f"{{self.get_absolute_url}}/delete/"
forms.py
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block extrahead %}
{% endblock %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<form method="post" novalidate>
{% csrf_token %}
<div class="Error_Messages">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
<br><br>
<b>Internal contact information</b>
<hr class="divider"></hr>
<div class="row">
<div class="col-6">
{{ form.Project_Code|as_crispy_field }}
</div>
<div class="col-6">
{{ form.Partrec_Contact_Name|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-6">
{{ form.Pac_Rate|as_crispy_field }}
</div>
<div class="col-6">
{{ form.Partrec_Contact_Email|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-6">
{{ form.Previous_Experiment|as_crispy_field }}
</div>
<div class="col-6">
</div>
</div>
<div class="row">
<div class="col-6">
{{ form.Status|as_crispy_field }}
</div>
<div class="col-6">
</div>
</div>
<br><br>
<b>External contact information</b>
<hr class="divider"></hr>
<div class="row justify-content-center">
<div class="col-6">
{{ form.Project_Title|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-6">
{{ form.Spokesperson_Name|as_crispy_field }}
</div>
<div class="col-6">
{{ form.Spokesperson_Adress|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-6">
{{ form.Spokesperson_Phonenumber|as_crispy_field }}
</div>
<div class="col-6">
{{ form.Spokesperson_Email|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-4">
{{ form.Collaborator_Name|as_crispy_field }}
</div>
<div class="col-4">
{{ form.Collaborator_Nationality|as_crispy_field }}
</div>
<div class="col-4">
{{ form.Collaborator_Home_Institute|as_crispy_field }}
</div>
</div>
<br><br>
<b>Beam information</b>
<hr class="divider"></hr>
<div class="row">
<div class="col-6">
{{ form.Start_Date|as_crispy_field }}
</div>
<div class="col-6">
{{ form.End_Date|as_crispy_field }}
</div>
</div>
<div class="justify-content-center">
<div class="col-6">
{{ form.Different_Beams|as_crispy_field }}
</div>
</div>
<div class="row justify-content-center">
<div id="hidden1">
<div class="col-6">
{{ form.Hours|as_crispy_field }}
{{ form.Ion_Species|as_crispy_field }}
{{ form.Energy|as_crispy_field }}
{{ form.Flux|as_crispy_field }}
</div>
</div>
<div id="hidden2">
<div class="col-6">
{{ form.Hours|as_crispy_field }}
{{ form.Ion_Species|as_crispy_field }}
{{ form.Energy|as_crispy_field }}
{{ form.Flux|as_crispy_field }}
</div>
</div>
<div id="hidden3">
<div class="col-6">
{{ form.Hours|as_crispy_field }}
{{ form.Ion_Species|as_crispy_field }}
{{ form.Energy|as_crispy_field }}
{{ form.Flux|as_crispy_field }}
</div>
</div>
<div id="hidden4">
<div class="col-6">
{{ form.Hours|as_crispy_field }}
{{ form.Ion_Species|as_crispy_field }}
{{ form.Energy|as_crispy_field }}
{{ form.Flux|as_crispy_field }}
</div>
</div>
</div>
<div class="row justify-content-center">
{{ form.Requiered_Equipment|as_crispy_field }}
{{ form.Special_Requirements|as_crispy_field }}
{{ form.Special_Safety_Procedures|as_crispy_field }}
{{ form.Lab_Support_Requirements|as_crispy_field }}
{{ form.Funded|as_crispy_field }}
{{ form.Summary|as_crispy_field }}
</div>
<div class="row justify-content-center">
<button type="submit" class="btn btn-success">Save New Request</button>
</div>
</form>
<br>
<script type="text/javascript">
$('#hidden2').css({
'display': 'none'
});
$('#hidden3').css({
'display': 'none'
});
$('#hidden4').css({
'display': 'none'
});
$('#id_Different_Beams').on('change', function() {
if (this.value === '2') {
$('#hidden1').show();
$('#hidden2').show();
$('#hidden3').hide();
$('#hidden4').hide();
}
else if ($(this).val() == '3') {
$('#hidden1').show();
$('#hidden2').show();
$('#hidden3').show();
$('#hidden4').hide();
}
else if ($(this).val() == '4') {
$('#hidden1').show();
$('#hidden2').show();
$('#hidden3').show();
$('#hidden4').show();
}
else {
$('#hidden1').show();
$('#hidden2').hide();
$('#hidden3').hide();
$('#hidden4').hide();
}
});
</script>
{% endblock %}
Views.py
from django.http import Http404, HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
from .models import CreateBeamRequestModel, IonSpecies, Energys
from .forms import CreateBeamRequestForm
# Create your views here.
#home page
def beam_request_home_page(request):
page_title = 'Beam Request'
template_name = 'request/home.html'
context = {"title": page_title}
return render(request, template_name, context)
##login_required
#Create view
#staff_member_required
def beam_request_create_page(request):
page_title = 'Create new Request'
template_name = 'request/create.html'
form = CreateBeamRequestForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
form.save()
form = CreateBeamRequestForm()
context = {"title": page_title, "form": form}
return render(request, template_name, context)
I have a problem when I want to visit the user dashboard. On each article there is a link to the user profile, however, when I click on the link I'm getting NoReverseMatch. I was doing troubleshoots for days but I'm not able to fix the problem. Any help on how to fix this error is more than welcome, thank you!
article.html:
<h6> {{ article.author.profile.username}}</h6>
accounts>views:
#login_required
def guest_dashboard(request, pk):
user_other = User.objects.get(pk = pk)
already_followed = Follow.objects.filter(follower = request.user, following = user_other)
if guest_dashboard == request.user:
return HttpResponseRedirect(reverse('dashboard'))
return render(request, 'account/dashboard-guest.html', context = {'user_other' : user_other, 'already_followed' : already_followed})
articles>View:
def article_detail(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm()
already_liked = Likes.objects.filter(article=article, user=request.user)
likesCounter = Likes.objects.filter(article=article).count()
if already_liked:
liked = True
else:
liked = False
if request.method == 'POST':
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.user = request.user
comment.article = article
comment.save()
return HttpResponseRedirect(reverse('article_detail', kwargs={'pk':pk}))
return render(request, 'article/single-article.html', context={'article':article, 'comment_form':comment_form, 'liked': liked,'likesCounter':likesCounter,'already_liked':already_liked})
article>URLs:
path('<pk>', article_detail , name = 'article_detail'),
account>URLs:
path('account/dashboard/', dashboard, name = 'dashboard'),
path('account/dashboard/<pk>/', guest_dashboard, name = 'guest_user'),
dashboard-guest.html>
{% extends 'base.html' %}
{% load static %}
{% block content %}
<!-- PROFILE CONTENT -->
<div id="profile-container">
<img class = "profile-cover-image" src = "/media/{{ user_other.profile.cover_picture }}">
<div class="profile-profile-image-cover">
<img class = "profile-profile-image-img" src = "/media/{{ user_other.profile.profile_picture }}">
</div>
<div class="edit-profile">
<div class="social-media-links">
<span><i class="fab fa-facebook-square fa-2x color-fb dec_none"></i></span>
<span><i class="fab fa-linkedin fa-2x color-linked dec_none"></i></span>
<span><i class="fab fa-twitter-square fa-2x color-twitter dec_none"></i></span>
</div>
</div>
<div class="profile-btns">
{% if not already_followed%}
Follow
{% else %}
Unfollow
{% endif%}
{% if user.post_author.all.count > 100 %}
<i class="fas fa-camera-retro fa-4x awards"></i>
{% endif %}
{% if user.article_author.all.count > 100 %}
<i class="fas fa-crown fa-4x awards"></i>
{% endif %}
</div>
</div>
<!-- END OF PROFILE CONTENT-->
<!-- PROFILE STAFF -->
<div class="profile-controllers">
<div class="profile-main-controller">
<div class="containerce">
<p class = 'boxce txt-center'><i class="fas fa-feather-alt fa-2x dcolor"></i>{{ user_other.article_author.all.count }}</p>
<p> Articles </p>
</div>
<div class="containerce">
<p class = 'boxce txt-center'><i class="fas fa-image fa-2x dcolor"></i> {{ user_other.post_author.all.count }}</p>
<p> Posts </p>
</div>
<div class="containerce">
<p class = 'boxce' txt-center><i class="fas fa-mask fa-2x dcolor"></i> {{ user_other.follower.count }}</p>
<p> Following </p>
</div>
<div class="containerce">
<p class = 'boxce txt-center'><i class="fas fa-hand-holding-heart fa-2x dcolor"></i> {{ user_other.following.count }} </p>
<p> Followers </p>
</div>
<div class="containerce">
{% if user_other.article_author.all.count and user_other.article_author.all.count > 100 %}
<p class = 'boxce txt-center'><i class="fas fa-award fa-2x dcolor"></i> 2</p>
{% else %}
<p class = 'boxce txt-center'><i class="fas fa-award fa-2x dcolor"></i> 0</p>
{% endif %}
<p> Awards </p>
</div>
</div>
</div>
<!-- MAIN FUNCTIONS -->
<div class="functions">
<div class="profile-buttons" id = "profile-buttons">
<a id = "btn_articles" href = "#" class = "btn-profile-buttons active">Articles </a>
<a id = "btn_posts" href = "#" class = "btn-profile-buttons ">Posts </a>
<a id = "btn_videos" href = "#" class = "btn-profile-buttons ">Videos</a>
</div>
<div class = "liner"></div>
</div>
<!-- POSTS -->
<div class="container-posts" id = "container_posts">
<!-- Original posts card-->
{% if user_other.post_author.all %}
{% for post in user_other.post_author.all %}
<div class="container-posts-card">
<a href = "{% url 'post_detail' pk=post.pk %}">
<img src = "{{ post.image.url}}" class = "container-post-card-img"> </a>
<div class="posts_card_edit">
<span class = "ellipsis-edit"><i class="fas fa-ellipsis-v"></i></span>
</div>
</div>
{% endfor %}
{% endif %}
<!-- END OF POST CARD-->
</div>
<!--ENDPOSTS-->
<!-- ARTICLES -->
<div class="container-articles" id = "container_articles">
{% if user_other.article_author.all %}
{% for user_other in user.article_author.all %}
<div class="container-article-card">
<a href = "{% url 'article_detail' pk=article.pk %}" class = "article-card-btn">
<img src = "{{ article.image.url }}" class = "container-article-card-img">
<div class="article-card-details">
<h6 class = "container-article-card-title">{{ article.title }}</h6>
<p class = "article-card-created">{{ article.publish_date }}</p>
</div></a>
<div class="container-article-card-edit">
<span class = "ellipsis-edit"><i class="fas fa-ellipsis-h"></i></span>
</div>
</div>
{% endfor %}
{% else %}
<div class="container-article-card">
<p>No Articles</p>
</div>
{% endif %}
</div>
<!-- ENDARTICLES-->
<!-- END OF MAIN FUNCTIONS -->
<br>
{% endblock %}
single-article.html
{% extends 'base.html' %}
{% load static %}
{% load humanize %}
{% load crispy_forms_tags %}
{% block content %}
<!-- CONTENT -->
<div id="container-single-post">
<div class="left-side">
<img class = "single-article-img" src = "{{ article.image.url }}">
<div class="single-post-author">
<img class = 'single-post-author-image' src = "{{ article.author.profile.profile_picture.url}}" style="object-fit:cover">
</div>
</div>
<div class="right-side">
<h6> {{ article.author.profile.username}}</h6>
{% if article.author.profile.full_name %}
<span span = "single-post-att">{{ article.author.profile.full_name}}</span>
{% else %}
<span span = "single-post-att"></span>
{% endif %}
<span span = "single-post-att">{{ article.category }}</span>
<span span = "single-post-att">{{ article.publish_date | naturaltime }}</span>
{%for a in already_liked %}
<div>{{a.user.profile.full_name}}, you are awesome!</div>
{% endfor %}
{% if not liked %}
<span class = "single-post-love" id="probaman"><i class="far fa-heart fa-2x"></i>{{likesCounter}}</span>
{% else %}
<span class = "single-post-love"><i class="fas fa-heart fa-2x"></i>{{likesCounter}}</span>
{% endif %}
</div>
<div class="single-post-content">
<h5>{{ article.title }}</h5>
<p>{{ article.content}}
</p>
</div>
<div class="single-post-comments">
<p>Comments</p>
<!-- Display Comment -->
{% for comment in article.article_comment.all %}
<div class="comment-single">
<div class="comment-author">
<img class = 'single-comment-author-image' src = "{{comment.user.profile.profile_picture.url}}" style="object-fit:cover">
<span class = 'comment-author'>{{comment.user.profile.full_name}}×</span>
</div>
<p class = "comment-date">{{comment.comment_date| naturaltime}}</p>
<div class="comment-author-content">
<p class = "comment-content">{{ comment.comment }}</p>
</div>
</div>
{% endfor %}
<!-- END Display Comment-->
<!-- POST COMMENT -->
<div class="col-lg-12">
<form method = "POST" class = "form-comment">
{{ comment_form | crispy }}
{% csrf_token %}
<button type ='submit' class = 'btn-default-comment'>Comment</button>
</form>
</div>
<!-- END POST COMMENT-->
</div>
</div>
<!-- END OF CONTENT-->
<br>
<br>
{% endblock %}
In the template, you have <a href = "{% url 'article_detail' pk=article.pk %}", but the variable article is not created anywhere. Where should it come from?
There is a loop {% for user_other in user.article_author.all %}, and it seems like it should somehow lead to an article, but that's unclear without the models and business logic knowledge. Should it be {% for article in user.article_author.all %} ?
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)|...
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 %}