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)
Related
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.
lets think you have a table like this
MODELS.PY
class test(models.Model):
name = models.CharField(max_length=20)
pluspoints = models.BooleanField(default=False)
minuspoints = models.BooleanField(default=False)
total_points = models.IntegerField()
def __str__(self):
return str(self.name)
points.html
<form id="points_form">
{% csrf_token %}
<div class="row">
<div class="col-3">
{{ form.name|as_crispy_field }}
</div>
<div class="col-3">
{{ form.pluspoints|as_crispy_field }}
</div>
<div class="col-3">
{{ form.minuspoints|as_crispy_field }}
</div>
</div>
<br>
<input class="btn btn-outline-primary" type="submit" name="submit" value="give the points" />
</form>
views.py
def points(request):
points_filter = test.objects.filter(total_points=True)
points_count = test.objects.count()
context = {
'points_filter':points_filter,
'points_count':points_count,
}
return render(request, 'point/points.html', context)
now, I want to update the "total_points" -1 when I click on minuspoints and +1 when I click on pluspoints. Is this possible? or what could I do else.
I have issue might missed something , i have created CreateView view for submitting objects in db , all seems to ok , but when i try to submit i don't get anything happen no error at all except
"POST /create_task/ HTTP/1.1" 200 12972 ,
MY code goes as follows , please advice
Thanks
models.py
class MainTask(models.Model):
task_title = models.CharField(max_length=200)
global_task_info = models.TextField(max_length=500,default=None)
complete = models.BooleanField(default=False)
overall_precent_complete = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(default=datetime.datetime.now())
updated_at = models.DateTimeField(default=datetime.datetime.now())
due_date = models.DateTimeField(default=datetime.datetime.now())
task_location = models.CharField(max_length=400, blank=True, null=True)
global_task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="global_task_assign",default=1)
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_status = models.CharField(max_length=2,choices=TASK_STATUS_CHOICES,default='NOT STARTED')
def __str__(self):
return self.task_title
forms.py
class TaskCraetionForm(forms.ModelForm):
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'}))
global_task_info = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'}))
due_date = forms.DateTimeField(widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} ))
task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = MainTask
fields = ['task_title',
'global_task_info',
'due_date',
'global_task_assign',
'task_status',
]
views.py
class CreatTaskView(CreateView):
model = MainTask
template_name = "create_newtask.html"
form_class = TaskCraetionForm
success_url = None
def form_valid(self, form):
f = form.save(commit=False)
f.save()
return super(CreatTaskView, self).form_valid(form)
Thank you very much Alasdair you're comment gave me the direction and more added the following to my HTML template shown below and found out i have issue with my datetime picker format needed to added the following
Thanks
INPUTֹTIMEֹFORMATS = [
'%Y/%m/%d %H:%M']
due_date = forms.DateTimeField(input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
html temaplate
<form action="" method="POST">
<h3 class="mt-3 text-left">Create New Task</h3>
<hr>
<p class="text-muted text-left">Creat New Itom task</p>
{% csrf_token %}
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
<div class="input-group mt-3 mb-3 mr-auto">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-book-medical"></i></span>
</div>
{{ form.task_title}}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pen"></i></span>
</div>
{{form.global_task_info}}
</div>
<!---date time picker-->
<h6 class="text-left">Task Due Date</h6>
<div class="input-group date mb-3 col-3">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
{{ form.due_date }}
</div>
<!--end of date time picker-->
<!---user assign-->
<h6 class="text-left">Assign Task to IT member</h6>
<div class="input-group mb-3 mt-3 col-8">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user-tie"></i></div>
{{form.global_task_assign}}
</div>
</div>
<!--End Of User Assign-->
<h6 class="text-left">Set Task Status</h6>
<div class="input-group mb-3 mt-3 col-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="far fa-caret-square-right"></i></div>
</div>
{{form.task_status}}
</div>
<div class="col text-left">
<button type="submit" value="Save" class="btn btn-primary btn-lg text-white mt-2"><span><i class="fas fa-database"></i></span> Create Task</button>
</div>
</form>
</div>
</div>
I've been trying to display the exact values of model with ManyToMany relation but I just couldn't, all what I've achevied is receiving QuerySet
<QuerySet [<Stack: PHP>, <Stack: js>]>
by adding to template tags
{{ brand.technologies.all }}
But I would like to receive and display 2 fields, name and icon. I've tried with some loops like
{% for brand in brands %}
{% for technologies in brand.technologies.all %} {{ technologies.name }} {{ technologies.icon }} {% endfor %}
{% endfor %}
but it doesn't give any results. There is not problem with syntax because page is displaying and looks like this
image
models.py
STACK = (
('PHP', 'PHP'),
('js', 'JavaScript'),
...
)
STACK_ICONS = (
('/static/icons/stack/php.png', 'PHP'),
('/static/icons/stack/javascript.png', 'JavaScript'),
...
)
class Company(models.Model):
name = models.CharField(max_length=100, blank=False)
students = models.CharField(max_length=3, choices=STUDENTS)
type = models.CharField(max_length=15, choices=TYPES)
workers = models.PositiveIntegerField(validators=[MinValueValidator(1)])
city = models.CharField(max_length=15,choices=CITIES)
company_about = models.TextField(max_length=500, blank=False)
slug = models.SlugField(unique=True)
icon = models.ImageField(blank=True, null=True)
image = models.ImageField(blank=True, null=True)
logo = models.ImageField(blank=True, null=True)
technologies = models.ManyToManyField('Stack')
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Company, self).save(*args, **kwargs)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.name
# object stack relation manytomany with Company
class Stack(models.Model):
name = models.CharField(max_length=30, choices=STACK)
icon = models.CharField(max_length=80, choices=STACK_ICONS)
def __str__(self):
return self.name
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
...
def comp_list(request):
f = CompanyFilter(request.GET, queryset=Company.objects.all())
return render(request, 'company/comp_list.html', {'filter': f})
def companies(request):
company = get_object_or_404(Company)
return render(request, 'company/comp_list.html', {'company': company})
def home(request):
return render(request, 'company/home.html')
def brands(request, slug):
brand = get_object_or_404(Company, slug=slug)
return render(request, 'company/comp_view.html', {'brand': brand})
def stacks(request):
stack = get_object_or_404(Stack)
return render(request, 'company/comp_view.html', {'stack': stack})
comp_view.html
{% extends 'company/base.html' %}
{% block content %}
<div class="row company-details">
<div class="col col-md-2"></div>
<div class="col col-md-8">
<input class="btn btn-success" type="button" value="Go Back" onclick="history.back(-1)" />
<div class="col col-md-12 company-bg" style="background-image: url('{{ brand.image.url }}'); background-repeat: no-repeat, repeat;">
</div>
<div class="bottom-overlay"></div>
<div class="company-description">
<div class="heading">
<div class="title">About us</div>
<div class="social-media">
Facebook
</div>
</div>
<div class="company-about">
{{ brand.company_about }}
</div>
</div>
<div class="company-stats">
<div class="company-logo-container">
<img class="company-logo" src="{{ brand.logo.url }}">
</div>
<div class="company-attributes">
<div class="field-group">
<div class="field">Type</div>
<div class="value">{{ brand.type }}</div>
</div>
<div class="field-group">
<div class="field">Company size</div>
<div class="value">{{ brand.workers }}+</div>
</div>
<div class="field-group">
<div class="field">Headquarters</div>
<div class="value">{{ brand.city }}</div>
</div>
<div class="field-group">
<div class="field">Open for students</div>
<div class="value">{{ brand.students }}</div>
</div>
</div>
<div class="technologies-section">
<p class="tech-heading">Technologies</p>
<div class="technologies-wrapper">
{{ brand.technologies.all }}
{% for brand in brands %}
{% for technologies in brand.technologies.all %} {{ technologies.name }} {% endfor %}
{% endfor %}
</div>
</div>
</div>
<div class="col col-md-2"></div>
</div>
{% endblock %}
I don't understand why you've suddenly added an outer loop through brands. You don't have anything called brands, and you're successfully accessing all the other data via brand. Just continue to do so, and drop the outer loop.
<div class="technologies-wrapper">
{% for technologies in brand.technologies.all %} {{ technologies.name }} {% endfor %}
</div>
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 %}