My tables in my django don't show up , the titles for the table do but the data itself does not. can someone tell me what is wrong with my code please. Thank you
dashboard.html
{% extends 'accounts/main.html' %}
{% block content %}
{% include 'accounts/status.html' %}
<br>
<div class="col-md-16">
<h5>LAST 5 ORDERS</h5>
<hr>
<div class="card card-body">
<a class="btn btn-primary btn-sm btn-block" href="">Create Order</a>
<table class="table table-sm">
<tr>
<th>Title</th>
<th>Language</th>
<th>Rating</th>
<th>Type of Media</th>
<th>Genre</th>
<th>Review</th>
<th>Notes</th>
<th>Date</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for media in medias %}
<tr>
<td>{{media.title}}</td>
<td>{{media.language}}</td>
<td>{{media.rating}}</td>
<td>{{media.type_of_media}}</td>
<td>{{media.genre}}</td>
<td>{{media.review}}</td>
<td>{{media.notes}}</td>
<td>{{media.date}}</td>
<td>Update</td>
<td>Delete</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
from django.db import models
class Media(models.Model):
CATEGORY = (
('Movie', 'Movie'),
('Tv Show', 'Tv Show'),
('Drama', 'Drama'),
('Other', 'Other'),
)
NUMBER = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
)
GROUP = (
('Action', 'Action'),
('Anime', 'Anime'),
('Comedy', 'Comedy'),
('Crime', 'Crime'),
('Fantasy', 'Fantasy'),
('Horror', 'Horror'),
('Romance', 'Romance'),
('Other', 'Other'),
)
title = models.CharField(max_length=200, null=True)
language = models.CharField(max_length=200, null=True)
rating = models.CharField(max_length=200, null=True, choices=NUMBER)
type_of_media = models.CharField(max_length=200, null=True, choices=CATEGORY)
genre = models.CharField(max_length=200, null=True, choices=GROUP)
review = models.CharField(max_length=1000, null=True)
notes = models.CharField(max_length=1000, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.title
class Status(models.Model):
POSITION = (
('Completed', 'Completed'),
('Continue Watching', 'Continue Watching'),
('Plan to Watch', 'Plan to Watch'),
('Dropped', 'Dropped'),
)
media = models.ForeignKey(Media, null=True,on_delete= models.SET_NULL)
status_of_media = models.CharField(max_length=200, null=True, choices=POSITION)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
# Create your views here.
def home(request):
return render(request, 'accounts/dashboard.html')
medias = Media.objects.all()
context = {'medias': medias}
return render(request, 'accounts/dashboard.html', context)
def products(request):
return render(request, 'accounts/products.html')
def customer(request):
return render(request, 'accounts/customer.html')
Those are all the relevant windows
Thanks
ignore this please i need more words to publish my question
def home(request):
return render(request, 'accounts/dashboard.html')
medias = Media.objects.all()
context = {'medias': medias}
return render(request, 'accounts/dashboard.html', context)
def products(request):
return render(request, 'accounts/products.html')
def customer(request):
return render(request, 'accounts/customer.html')
instead of this line.
{% for media in mediass %}
use the line below
{% for media in medias %}
you passed medias in your context.
I think you just misspelled it
You are returning before you add 'medias' to the context:
def home(request):
**return render(request, 'accounts/dashboard.html')**
medias = Media.objects.all()
context = {'medias': medias}
return render(request, 'accounts/dashboard.html', context)
Related
I have created a project and added models in the models and also created a form in forms.py. I am trying to modify some values using the commit=False. On submitting the form, it's not saving the data to the database and there is no error thrown from the code. I have no idea on how I can solve the issue.
models.py
from django.db import models
from django.contrib.auth.models import User
class Agent(models.Model):
name = models.CharField(max_length=255)
id_no = models.CharField(max_length=20)
address = models.CharField(max_length=255)
gender = models.CharField(max_length=8)
age = models.IntegerField()
agent_no = models.CharField(unique=True, max_length=12, null=True)
email = models.EmailField(max_length=50)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.name}"
class Company(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=255, null=True, blank=True)
address = models.CharField(max_length=255, null=True, blank=True)
telephone = models.IntegerField( null=True, blank=True)
email = models.EmailField(max_length=50, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.name}"
class Task(models.Model):
company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL)
agent = models.ForeignKey(Agent, null=True, on_delete=models.SET_NULL)
cargo = models.CharField(max_length=200)
document = models.FileField(upload_to='documents/')
quantity = models.FloatField()
amount = models.FloatField()
duty = models.FloatField(null=True, blank=True)
status = models.CharField(max_length=50, default='Pending')
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.cargo}"
forms.py
from django.contrib.auth.models import User
from django import forms
import re
from django.core.exceptions import ValidationError
from .models import *
class TaskForm(forms.ModelForm):
cargo = forms.CharField( required=False)
document = forms.FileField()
quantity = forms.FloatField()
amount = forms.FloatField()
class Meta:
model = Task
fields = ['cargo', 'document', 'quantity', 'amount']
views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .forms import *
from django.contrib.auth.models import Group
from django.contrib.auth import login, authenticate
#login_required(login_url='/login/')
def task(request):
if request.method == "POST":
form=TaskForm(request.POST)
if form.is_valid():
m = form.save(commit=False)
m.status ='Pending'
m.company = request.user.username
m.save()
else:
form= TaskForm(None)
context = {'form':form}
return render(request, 'registration/templates/task.html', context)
template.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
<div class="container my-2 d-flex" style="align-items:center; justify-content:center;">
<div class="card d-flex" style="width:70%; align-items:center; justify-content:center;">
<div class="form-control pt-3 " style="text-transform:uppercase;color:green"><h5>Upload trip information
</h5>
</div>
<div class="card-body" style="width:98%">
{{ form|crispy}}
</div>
<div class="card-footer" style="width:98%">
<input type="submit" value="Upload Information" class="btn btn-outline-secondary btn-sm">
</div>
</div>
</div>
</form>
{% endblock %}
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect
from .forms import *
from django.contrib.auth.models import Group
from django.contrib.auth import login, authenticate
#login_required(login_url='/login/')
def task(request):
if request.method == "POST":
form=TaskForm(request.POST,request.FILES) # this is important if you are dealing with files
if form.is_valid():
m = form.save(commit=False)
m.status ='Pending'
m.company = request.user.username
m.save()
return HttpResponseRedirect(reverse(' the url of where you want to redirect the user '))
else:
form= TaskForm()
context = {'form':form}
return render(request, 'registration/templates/task.html', context)
and in your templates try to add enctype in your form.
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container my-2 d-flex" style="align-items:center; justify-content:center;">
<div class="card d-flex" style="width:70%; align-items:center; justify-content:center;">
<div class="form-control pt-3 " style="text-transform:uppercase;color:green"><h5>Upload trip information
</h5>
</div>
<div class="card-body" style="width:98%">
{{ form|crispy }}
</div>
<div class="card-footer" style="width:98%">
<input type="submit" value="Upload Information" class="btn btn-outline-secondary btn-sm">
</div>
</div>
</div>
</form>
{% endblock %}
I am using Django to build a help desk and I want to allow the client to upload multiple files when they submit a ticket.
I am trying to do this by using a formset.
I have found many questions related to a similar problem, but I still have not been able to get my form working. I will appreciate a pointer in the right direction.
I have posted the relevant code below:
# models.py
class Ticket(models.Model):
PRIORITY_CHOICES = (
(1, 'Critical'),
(2, 'High'),
(3, 'Normal'),
(4, 'Low'),
(5, 'Very Low'),
)
STATUS_CHOICES = (
(1, 'Open'),
(2, 'Reopened'),
(3, 'Resolved'),
(4, 'Closed'),
(5, 'Duplicate'),
)
ticket_number = models.CharField(max_length=50, blank=True,
null=True, unique=True)
client = models.ForeignKey(settings.AUTH_USER_MODEL,
editable=True, on_delete=models.CASCADE,
related_name="tickets")
title = models.CharField("Summary",
max_length=200,
help_text='Provide a brief description of your request.')
description = models.TextField(blank=True,
help_text='Provide as much detail as possible to help us resolve this ticket as quickly as possible.')
due_date = models.DateField(blank=True, null=True)
assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name="assigned",
blank=True, null=True,
on_delete=models.CASCADE)
priority = models.IntegerField(choices=PRIORITY_CHOICES,
editable=True, default=3,
help_text='Please select a priority carefully. If unsure, leave it as "Normal".',
blank=True, null=True)
status = models.IntegerField(choices=STATUS_CHOICES,
editable=True,
default=1, blank=True, null=True)
closing_date = models.DateField(blank=True, null=True)
closing_notes = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
upload = models.FileField(upload_to='uploads/%Y/%m/%d/', blank=True, null=True)
def get_absolute_url(self):
return reverse('tickets:ticket-detail', args=[str(self.id)])
def __str__(self):
return str(self.ticket_number)
class TicketFile(models.Model):
attachment = models.FileField(upload_to='attachments/%Y/%m/%d', blank=True, null=True)
ticket = models.ForeignKey(Ticket, editable=True, on_delete=models.CASCADE)
description = models.CharField(max_length=200, blank=True)
def get_image_filename(self):
if self.docfile:
return media_url + str(self.docfile)
def __str__(self):
return str(self.attachment)
# forms.py
class TicketFormIsStaff(ModelForm):
class Meta:
model = Ticket
exclude = ()
class TicketFileForm(forms.ModelForm):
attachment = forms.FileField(label='Attachment')
class Meta:
model = TicketFile
fields = ('attachment', )
TicketAttachmentFormset = modelformset_factory(Ticket,
form=TicketFileForm, extra=2)
# views.py
class TicketCreateView(CreateView):
model = Ticket
fields = ['ticket_number', 'client', 'title', 'description', 'status']
def get_context_data(self, **kwargs):
data = super(TicketCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['ticketfiles'] = TicketAttachmentFormset(self.request.POST)
print("data 1 ", data['ticketfiles'] )
else:
data['ticketfiles'] = TicketAttachmentFormset()
print("data 2 ", data)
return data
def form_valid(self, form):
context = self.get_context_data()
ticketfiles = context['ticketfiles']
with transaction.atomic():
self.object = form.save()
print("CONTEXT:::: ", ticketfiles)
if ticketfiles.is_valid():
ticketfiles.instance = self.object
ticketfiles.save()
return super(TicketCreateView, self).form_valid(form)
# ticket_form.html
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<table class="table">
{{ ticketfiles.management_form }}
{% for form in ticketfiles.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Save" />
</form>
All the data related to the Ticket model uploads correctly, but the files related to the TicketFile model do not upload. If I try to upload the data in the admin interface then everything works perfectly. I assume this means that all the media settings are correct.
If I add the description field to the formset then that gets saved correctly. The file is not saved though.
I resolved the file upload problem by changing the code in TicketCreateView from:
data['ticketfiles'] = TicketAttachmentFormset(self.request.POST)
to:
data['ticketfiles'] = TicketAttachmentFormset(self.request.POST, self.request.FILES, instance=form.instance))
I am having a one to one relationship between 2 models. While creating the second model, I want to pass the instance of the first model to the second one.
These 2 models are new tabs/features in our web application. I tried passing the instance through URL but didn't succeed. Maybe I am not following steps correctly.
Details about:
python version: Python 3.6.4 :: Anaconda, Inc.
django version: 2.0.2-3
Please find below the code:
1) models.py
class StudyConcept(models.Model):
requestor_name = models.CharField(max_length=240, blank=False, null=False)
project = models.CharField(max_length=240, blank=False, null=False)
date_of_request = models.DateField(blank=False, null=False)
brief_summary = models.CharField(max_length=4000, blank=False, null=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class Logistics(models.Model):
budget = models.CharField(max_length=255, blank=False, null=False)
business_technology = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False)
vendor_or_contracts = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False)
studyConcept = models.OneToOneField(StudyConcept, on_delete = models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
def get_absolute_url(self):
return reverse('update_Logistics', kwargs={'pk': self.pk})
def get_deliverablesLogistics(self):
return ','.join([str(i) for i in self.deliverablesLogistics.all().values_list('id', flat=True)])
def get_paymentScheduleLogistics(self):
return ','.join([str(i) for i in self.paymentScheduleLogistics.all().values_list('id', flat=True)])
def get_commentsLogistics(self):
return ','.join([str(i) for i in self.commentsLogistics.all().values_list('id', flat=True)])
class DeliverablesLogistics(models.Model):
milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False)
poa = models.CharField('POA', max_length=480, blank=False, null=False)
start_date = models.DateField(blank=False, null=False)
end_date = models.DateField(blank=False, null=False)
logistics = models.ForeignKey(Logistics, related_name='deliverablesLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class PaymentScheduleLogistics(models.Model):
milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False)
cost = models.DecimalField(max_digits=14, decimal_places=2, blank=False, null=False, default=0)
estimated_payment_date = models.DateField(blank=False, null=False)
logistics = models.ForeignKey(Logistics, related_name='paymentScheduleLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class CommentsLogistics(models.Model):
comments = models.CharField('Comment', max_length=2000, blank=True, null=True)
commented_by = models.CharField(max_length=2000, blank=True, null=True)
logistics = models.ForeignKey(Logistics, related_name='commentsLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
views.py
def load_concepts(request):
currentUser = User.objects.get(id=request.user.id)
concepts = StudyConcept.objects.all().filter(user=request.user)
#concepts = get_object_or_404(StudyConcept)
return render(request, 'concept_dropdown_list_options.html',{
'concepts':concepts
})
class LogisticsFormsetCreate(CreateView):
model = Logistics
template_name = 'createLogistics.html'
form_class = LogisticsForm
success_url = reverse_lazy('create_Logistics')
def get_context_data(self, **kwargs):
data = super(LogisticsFormsetCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['deliverable'] = DeliverablesLogisticsFormset(self.request.POST, prefix='deliverables')
data['paymentSchedule'] = PaymentScheduleLogisticsFormset(self.request.POST, prefix='payments')
data['comment'] = CommentsLogisticsFormset(self.request.POST, prefix='comments')
#data['studyRequestConcept'] = self.request.POST.get('studyRequestConcept')
else:
data['deliverable'] = DeliverablesLogisticsFormset(prefix='deliverables')
data['paymentSchedule'] = PaymentScheduleLogisticsFormset(prefix='payments')
data['comment'] = CommentsLogisticsFormset(prefix='comments')
#data['studyRequestConcept'] = self.request.GET.get('studyRequestConcept')
return data
def form_valid(self, form):
context = self.get_context_data()
deliverable = context['deliverable']
paymentSchedule = context['paymentSchedule']
comment = context['comment']
with transaction.atomic():
if deliverable.is_valid() and paymentSchedule.is_valid() and comment.is_valid():
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object = form.save()
deliverable.instance = self.object
deliverable.save()
paymentSchedule.instance = self.object
paymentSchedule.save()
comment.instance = self.object
comment.save()
messages.success(self.request, Logistics.__name__ +' Form ID: '+ str(self.object.id) + ' was submitted successfully')
return super(LogisticsFormsetCreate, self).form_valid(form)
else:
return self.render_to_response(self.get_context_data(form=form))
Template
{% extends "header.html" %}
{% load widget_tweaks %}
{% block content %}
{% csrf_token %}
{% include 'xdsoft_stylesheets.html' %}
{% include 'messages.html' %}
<div class="container" align="center">
<h1 class="display-5">Logistics</h1>
</div>
<br/>
<div class="table-responsive">
<table class="table table-striped table-bordered" id="example" data-toggle="table"
data-filter-control="true" data-show-export="true"
data-click-to-select="true" data-toolbar="#toolbar" data-escape>
<thead>
<tr>
<th></th>
<th class="text-center" data-field="id" data-filter-control="input">ID</th>
<th class="text-center" data-field="project" data-filter-control="input">Project</th>
<th class="text-center" data-field="date_of_request" data-filter-control="input">Date</th>
<th class="text-center" data-field="brief_summary" data-filter-control="input">Summary</th>
<th class="text-center" data-field="scientific_question" data-filter-control="input">Question</th>
</tr>
</thead>
<tbody>
{%for studyRequestConcept in concepts %}
<tr>
<td style="width:200px">
<a class=" btn btn-primary js-create-logistics" data-toggle="modal" data-target="#modal" href="{% url 'create_Logistics' %}">
<span class="glyphicon glyphicon-plus"></span>
New Logistics
</a>
</td>
<td class="text-left">{{studyRequestConcept.id}}</td>
<td class="text-left">{{studyRequestConcept.project}}</td>
<td class="text-left">{{studyRequestConcept.date_of_request}}</td>
<td class="text-left">{{studyRequestConcept.brief_summary}}</td>
<td class="text-left">{{studyRequestConcept.scientific_question}}</td>
</tr>
{% endfor%}
</tbody>
</table>
</div>
{% comment %}The modal container{% endcomment %}
<div class="modal" id="modal" data-backdrop="false"></div>
<script>
$(function () {
$('.js-create-logistics').click( function () {
var btn = $(this)
$.ajax({
url: btn.attr("href"),
context: document.body
}).done(function(response) {
$("#modal").html(response);
});
});
});
</script>
{% endblock %}
I have a view/template where I list all the Study Concepts and every row has a create new Logistics button next to it. After clicking create new logistics button, the modal/view will open that will allow you to create a new Logistics. I want to pass the instance of the object study concept when I click the button.
Also, CreateLogistics is a class-based view designed using "from django.views.generic import CreateView"
I will be more than happy to provide any further code or information needed. Thanks in advance for all the support and help.
Regards,
Amey Kelekar
You haven't shown your URLs, but you need to accept the ID in the URL for the CreateView and use it in form_valid. For example:
path('/create_logistics/<int:id>/', LogisticsFormsetCreate.as_view(), name="create_Logistics"),
So in the template you would do:
<a class="btn btn-primary js-create-logistics" data-toggle="modal" data-target="#modal" href="{% url 'create_Logistics' id=studyRequestConcept.id %}">
and in the view:
def form_valid(self, form):
...
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.studyConcept_id = self.kwargs['id']
self.object.save()
...
Sorry for this title, I wasn't sure how to name it properly. I'm having problem with getting queryset of ManyToManyField that is in relation with other ManyToManyField. So it's look like this, there is model Company that has ManyToManyField with Person and Person model got ManyToManyField with Position, because logic behind it is that 1 company can have many persons and 1 person can have few positions and can be employed by few companies (which is clear I think). I'm getting the queryset for Person in Company by this way
{% for team in brand.team.all %}
<p>{{ team.first_name }} {{ team.last_name }}</p>
<img class="img-thumbnail" src="/media/{{ team.photo }}">
<p>{{ team.position }} </p>
<p>{{ team.about }} </p>
{% endfor %}
And I'm getting what I want, comparing this to template looks like this
but I'm not getting positions of person, only company.Position.None and I've no idea how to get this. From documentation so far I know that it works for single ManyToManyField but I couldn't find example similar to mine case and I'm not sure how I should get (person's position)
Below are my files
models.py
from django.db import models
...
TYPES = (
('Startup', 'Startup'),
... )
CITIES = (
('Warszawa', 'Warszawa'),
... )
STACK = (
('PHP', 'PHP'),
... )
STUDENTS = (
('No', 'No'),
('Yes', 'Yes')
)
STACK_ICONS = (
('/static/icons/stack/php.png', 'PHP'),
('/static/icons/stack/javascript.png', 'JavaScript'),
...
)
POSITIONS = (
('CEO', 'Chief Executive Officer'),
('CTO', 'Chief Technology Officer'),
...
)
# object position with relationship many to many to person
class Position(models.Model):
position = models.CharField(max_length=50, choices=POSITIONS)
def __str__(self):
return self.position
# object person relation many to one (many persons to one company)
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
about = models.TextField(max_length=500, default=None)
position = models.ManyToManyField('Position')
photo = models.ImageField(blank=True, null=True, default=None)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
# object company
class Company(models.Model):
# field person with relation many to one (many persons to 1 company)
team = models.ManyToManyField('Person')
name = models.CharField(max_length=100, blank=False)
technologies = models.ManyToManyField('Stack')
website = models.TextField(max_length=150, blank=True, null=True, validators=[URLValidator()])
...
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
...
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})
def positions(request):
position = get_object_or_404(Position)
return render(request, 'company/comp_view.html', {'position': position})
...
comp_view.html
{% extends 'company/base.html' %}
<div class="col col-md-1"></div>
<div class="col col-md-5 card-section">
<div class="team ">
<div class="card-title">
<span>Team</span>
</div>
<div class="row text-center">
<div class="col col-md-4">
{% for team in brand.team.all %}
<p>{{ team.first_name }} {{ team.last_name }}</p>
<img class="img-thumbnail" src="/media/{{ team.photo }}">
<p>{{ team.position }}</p>
<p>{{ team.about }} </p>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
There's no such thing as a "single ManyToManyField". You have an m2m relationship, you need to iterate through it just like you do for the team members.
{% for position in team.position.all %}
{{ position.name }}
{% endfor %}
I have a modelform that only works(saves input data to database) if none of the fields has choices. When i introduce choices, i don't get any errors and the form seems to be valid but nothing gets saved.
I have combed through the documentation and i am not returning anything useful.
I am convinced that i need to do more in my views to get the selected input choices or i need to add a few methods to the model class. Please point me in the right direction.
Here is my model:
class OpeningHours(models.Model):
'''
'''
class Meta:
verbose_name = 'Opening Hour'
verbose_name_plural = 'Opening Hours'
#######################################################
mytime = Bizhours()
################################################
id = models.AutoField(primary_key=True)
company =models.CharField(max_length=100, null=True, blank=True)
weekday = models.CharField(max_length=100, choices=mytime.getweekdays(), default='Monday', null=True)
fromHour = models.CharField(max_length=100, null=True, blank=True)
fromMinute = models.CharField(max_length=100, null=True, blank=True)
toHour = models.CharField(max_length=100, null=True, blank=True)
toMinute = models.CharField(max_length=100, null=True, blank=True)
'''
id = models.AutoField(primary_key=True)
company = models.ForeignKey(Company)
weekday = models.IntegerField(choices=mytime.getweekdays())
fromHour = models.TimeField(choices=mytime.gettime12())
fromMinute = models.TimeField(choices=mytime.getminutes())
toHour = models.TimeField(choices=mytime.gettime12())
toMinute = models.TimeField(choices=mytime.getminutes())
'''
def __str__(self):
return "%s %s (%s - %s)" % (self.company, self.weekday, self.fromHour, self.toHour)
here is my views
#login_required
def addprofile(request):
current_user = request.user
#OpeningHoursFormSet = modelformset_factory(OpeningHours, form=OpeningHoursForm,extra=1)
if request.session['entry_count'] > 1:
messages.success( request, 'You can only create two business profiles now' )
return HttpResponseRedirect( reverse('home') )
else:
if request.method == 'POST':
form = OpeningHoursForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.company ="thiscompany"
model_instance.weekday = request.POST.get('weekday')
model_instance.save()
else:
print("problems saving edited form")
return HttpResponseRedirect('/bizprofile/success')
else:
form = OpeningHoursForm()
context = {'form': form}
return render_to_response('bizprofile/addprofile.html', context, context_instance=RequestContext(request))
here is the form
{% extends "bizprofile/bizprofilebase.html" %}
{% block content %}
{% if form.subject.errors %}
<ol>
{% for error in form.subject.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
{% if user.is_authenticated %}
<p>Welcome, {{ user.get_username }}. Thanks for logging in.</p>
<form method="post" action="">
{% csrf_token %}
<table>
{{form}}
</table>
<input type="submit" value="Submit Form"/>
</form>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
{% endblock %}
The problem lies in the fact that OP is using CharField for weekday data type, but the choices returned from a function are defined as integers. Since they are not compatible, the data could not be saved.