I want to send my data through post request. I used postgres database.
I also tried for makemigrations and migrate this model, it also shows the error message.
When i tried to submit my form, it shows following error.
IntegrityError at /formSubmit
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (Own, Khar, 3, 23, 2323, 23233, 324, null).
Request Method: POST
Request URL: http://127.0.0.1:8000/formSubmit
Django Version: 2.1.7
Exception Type: IntegrityError
Exception Value:
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (Own, Khar, 3, 23, 2323, 23233, 324, null).
Exception Location: D:\coding time\Django+ GeoDjango\Django
Enviroment\venv\lib\site-packages\django\db\backends\utils.py in _execute,
line 85
Python Executable: D:\coding time\Django+ GeoDjango\Django
Enviroment\venv\Scripts\python.exe
Python Version: 3.7.2
my models.py file is comes form python manage.py inspectdb command. I managed the database in postgres. models.py file is here:
class Form(models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
email = models.CharField(max_length=29, blank=True, null=True)
password = models.CharField(max_length=30, blank=True, null=True)
class Meta:
db_table = 'form'
class Ownership(models.Model):
house_no = models.IntegerField(blank=True, null=True)
ward_no = models.IntegerField(blank=True, null=True)
tole = models.CharField(max_length=100, blank=True, null=True)
house_owner = models.CharField(max_length=100, blank=True, null=True)
gender = models.CharField(max_length=100, blank=True, null=True)
religion = models.CharField(max_length=100, blank=True, null=True)
language = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'ownership'
class Residence(models.Model):
ownership_type = models.CharField(max_length=100, primary_key=True)
house_type = models.CharField(max_length=100, blank=True, null=True)
land_type = models.CharField(max_length=100, blank=True, null=True)
total_room = models.CharField(max_length=101, blank=True, null=True)
house_use = models.CharField(max_length=101, blank=True, null=True)
house_area = models.CharField(max_length=101, blank=True, null=True)
earthquake_resistance = models.CharField(max_length=101, blank=True, null=True)
id = models.ForeignKey(Ownership, models.DO_NOTHING, db_column='id')
class Meta:
db_table = 'residence'
class ServiceDetail(models.Model):
radio = models.BooleanField(primary_key=True)
television = models.BooleanField(blank=True, null=True)
telephone = models.BooleanField(blank=True, null=True)
computer = models.BooleanField(blank=True, null=True)
internet = models.BooleanField(blank=True, null=True)
motorcycle = models.BooleanField(blank=True, null=True)
car = models.BooleanField(blank=True, null=True)
refrigerator = models.BooleanField(blank=True, null=True)
washing_machine = models.BooleanField(blank=True, null=True)
heater = models.BooleanField(blank=True, null=True)
id = models.ForeignKey(Ownership, models.DO_NOTHING, db_column='id')
class Meta:
db_table = 'service_detail'
my form.html file is here:
<html>
<head>
<title>form</title>
<style type="text/css">
table {
width:100%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: left;
}
table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color: #fff;
}
table#t01 th {
background-color: black;
color: white;
}
</style>
</head>
<body>
<form method="POST" action='/formSubmit'>
{% csrf_token %}
<h3>Ownership Detail</h3>
Name: <input type="text" name="name"><br><br>
Ward: <input type="text" name="ward"><br><br>
tole name: <input type="text" name="tname"><br><br>
House number: <input type="text" name="hnumber"><br><br>
Gender: <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="male">Female<br><br>
Religeous: <select name="religeous">
<option>Select</option>
<option>Hindu</option>
<option>Buddhist</option>
<option>Islam</option>
<option>Isai</option>
</select>
<br><br>
language: <input type="text" name="language"> <br><br>
<h3>Residence Detail</h3>
Owner type: <select name="ownertype"><option>select</option><option>Own</option><option>Lease</option><option>Corporation</option></select><br><br>
House type: <select name="housetype">
<option>select</option>
<option>Khar</option>
<option>Tin</option>
<option>Cement</option>
<option>Stone</option>
</select><br><br>
Land type: <input type="text" name="landtype"><br><br>
Total room: <input type="text" name="totalroom"><br><br>
House used: <input type="text" name="houseused"><br><br>
House area: <input type="text" name="housearea"><br><br>
Earthquake resistance: <input type="text" name="earthquake"><br><br>
<h3>Service Detail</h3>
<table>
<tr>
<th>Facilities</th>
<th>Yes/no</th>
</tr>
<tr>
<td>Radio</td>
<td><select name="radio"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>TV</td>
<td><select name="tv"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>Mobile</td>
<td><select name="mobile"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>computer</td>
<td><select name="computer"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>Internet</td>
<td><select name="internet"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>MoterCycle</td>
<td><select name="motercycle"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>Car</td>
<td><select name="car"><option>Yes</option><option>No</option></select></td>
</tr><tr>
<td>Hitar</td>
<td><select name="hitar"><option>Yes</option><option>No</option></select></td>
</tr>
</table>
<br><br>
<p align="center"><button type="submit" name="submit">Submit Data</button></p>
</form>
</body>
</html>
my views.py file is here:
from .models import Form, Residence, Ownership, ServiceDetail
# Create your views here.
def index(request):
form = Form.objects.all()
context = {
'form': form
}
return render(request, 'index.html', context)
def form(request):
return render(request, 'form.html')
def submit(request):
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
info = Form(name=name, email=email, password=password)
info.save()
return render(request, 'submit.html')
def formSubmit(request):
name = request.POST['name']
ward = request.POST['ward']
tname = request.POST['tname']
hnumber = request.POST['hnumber']
gender = request.POST['gender']
religeous = request.POST['religeous']
language = request.POST['language']
ownertype = request.POST['ownertype']
housetype = request.POST['housetype']
landtype = request.POST['landtype']
totalroom = request.POST['totalroom']
houseused = request.POST['houseused']
housearea = request.POST['housearea']
earthquake = request.POST['earthquake']
radio = request.POST['radio']
tv = request.POST['tv']
computer = request.POST['computer']
mobile = request.POST['mobile']
internet = request.POST['internet']
motercycle = request.POST['motercycle']
car = request.POST['car']
hitar = request.POST['hitar']
def count(n):
for i in range(n):
return i
if i == n:
return n+1
ownership = Ownership(house_no=hnumber, ward_no=ward, tole=tname, house_owner=name, gender=gender, religion=religeous, language=language)
ownership.save()
residence = Residence(ownership_type=ownertype, house_type=housetype, land_type=landtype, total_room=totalroom, house_use=houseused, house_area=housearea, earthquake_resistance=earthquake)
residence.save()
serviceDetail = ServiceDetail(radio=radio, television=tv, computer=computer, internet= internet, motorcycle=motercycle, car=car, heater=hitar)
serviceDetail.save()
return render(request, 'submit.html')
my urls.py file is here:
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('form', views.form, name = 'form'),
path('submit', views.submit, name = 'submit'),
path('formSubmit', views.formSubmit, name= 'formSubmit')
]
Related
I wanted to save text and images in my database in django but when i used
enctype='multipart/form-data'
it is not storing the image.
When i do it without
enctype='multipart/form-data'
it is storing the name of image
this is my index.html
`
<form method="POST" action="/index" enctype='multipart/form-data'>
{% csrf_token %}
<div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div>
<div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div>
<div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div>
<div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div>
<div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div>
<div>Dish image: <input name="dish_image" type="file"></div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
this is my views.py
def index(request):
if request.method == "POST":
dish_name = request.POST.get('dish_name')
dish_size = request.POST.get('dish_size')
dish_price = request.POST.get('dish_price')
dish_description = request.POST.get('dish_description')
dish_image = request.POST.get('dish_image')
dish_category = request.POST.get('dish_category')
item = dish(dish_name = dish_name, dish_size = dish_size, dish_price = dish_price, dish_description = dish_description,dish_category=dish_category, dish_image = dish_image, dish_date = datetime.today())
item.save()
dishs = dish.objects.all()
params = {'dish': dishs}
return render(request, "card/index.html", params)
this is my models.py
class dish(models.Model):
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
# dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()
def __str__(self):
return self.dish_name
this is my urls.py
urlpatterns = [
path('/index', views.index),
path('', views.index),
path('/', views.index),
path('index/', views.index),
path('index', views.index),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
this is my settings.py
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
`
using this my text is saving but image is not saving
In your html file, use this: enctype='multipart/form-data'
In your post method, you should use:
dish_image = request.FILES.get('dish_image')
This will return a file, which you can then save it to the model.
how to save data from html table in django without using form.py. I am currently creating table in html with add button and after adding all rows in table i want to save it but i am not using form.py only view.py,html,model.py
my view code is below
views.py
school_name = request.POST['school_name']
m_pass_out = request.POST['m_pass_out']
medicalschool = MedicalSchool(school_name=school_name, m_pass_out=m_pass_out)
medicalschool.save()
my model code is below
models.py
class DoctorProfile(models.Model):
user_guid = models.OneToOneField(
'EgdEradUsers', models.DO_NOTHING, db_column='user_guid', primary_key=True)
doctor_guid = models.UUIDField(unique=True)
featured_doctor_id = models.BooleanField()
primary_speciality = models.ForeignKey(DSpecialtyType, models.DO_NOTHING)
# This field type is a guess.
secondary_speciality = models.TextField(blank=True, null=True)
years_experience = models.IntegerField()
# This field type is a guess.
education = models.TextField(blank=True, null=True)
license_number = models.CharField(max_length=1000, blank=True, null=True)
npi_number = models.CharField(max_length=1000, blank=True, null=True)
revalidation_cme = models.IntegerField(blank=True, null=True)
# This field type is a guess.
states_to_practice = models.TextField(blank=True, null=True)
# This field type is a guess.
board_certification = models.TextField(blank=True, null=True)
# This field type is a guess.
honors_awards_recognition = models.TextField(blank=True, null=True)
# This field type is a guess.
publications = models.TextField(blank=True, null=True)
description = models.CharField(max_length=1000, blank=True, null=True)
# This field type is a guess.
hospital_privileges = models.TextField(blank=True, null=True)
phone_code = models.IntegerField(blank=True, null=True)
primary_contact_number = models.CharField(max_length=45)
phone_code2 = models.IntegerField(blank=True, null=True)
secondary_contact_number = models.CharField(
max_length=45, blank=True, null=True)
resume_url = models.CharField(max_length=1000, blank=True, null=True)
avatar_url = models.CharField(max_length=1000, blank=True, null=True)
additional_comments = models.CharField(
max_length=1000, blank=True, null=True)
class Meta:
managed = True
db_table = 'doctor_profile'
class MedicalSchool(models.Model):
school_name = models.CharField(max_length=100)
m_pass_out = models.DateField(max_length=100)
doctor_profile = models.ForeignKey(DoctorProfile, on_delete=models.CASCADE)
created_at = models.DateTimeField()
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'medical_school'
my html code is below
html
<div class="container-lg">
<div class="table-responsive">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-8">
<h2>Medical School</h2>
</div>
<div class="col-sm-4">
<button type="button" id="medical" class="btn btn-info add-
new"><i class="fa fa-plus"></i> Add New</button>
</div>
</div>
</div>
<table id="medicaltable" class="table table-bordered">
<thead>
<tr>
<th>Name of School</th>
<th>Year of Graduation</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td id="medicaltext" name="school_name"></td>
<td id="medicaldate" name="m_pass_out"></td>
<td>
<a id="medicaladd" class="add" title="Add" data-
toggle="tooltip"><i class="material-icons"></i></a>
<a id="medicaledit" class="edit" title="Edit" data-
toggle="tooltip"><i class="material-icons"></i></a>
<a id="medicaldelete" class="delete" title="Delete" data-
toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
you can access to your each html form inputs by their name in view. see below code:
models
from django.db import models
from django import forms
class MedicalSchool(models.Model):
school_name = models.CharField(max_length=100)
m_pass_out = models.DateField(max_length=100)
doctor_profile = models.ForeignKey(DoctorProfile, on_delete=models.CASCADE)
created_at = models.DateTimeField()
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'medical_school'
class MedicalSchoolForm(forms.ModelForm):
class Meta:
model = MedicalSchool
fields = ['school_name', 'm_pass_out', 'doctor_profile']
views
from django.contrib import messages
from django.shortcuts import redirect, render
from . import models
def MedicalSchool(request):
url = request.META.get('HTTP_REFERER') # get last url
if request.method == 'POST':
form = models.MedicalSchoolForm(request.POST) # access to ModelForm
if form.is_valid():
data = models.MedicalSchool() # create a instance of your Model
data.school_name = form.cleaned_data['school_name'] # 'school_name' is the name that we specified in html form input
data.m_pass_out = form.cleaned_data['m_pass_out'] # 'm_pass_out' is the name that we specified in html form input
data.doctor_profile_id = form.cleaned_data['doctor_profile'] # 'doctor_profile' is the name that we specified in html form input
data.save()
return redirect(url)
else:
messages.warning(request, form.errors)
return redirect(url)
context = {'DoctorProfile': models.DoctorProfile.objects.all()}
return render(request, 'MedicalSchool.html', context)
urls
from django.urls import path
from . import views
app_name = 'School'
urlpatterns = [
path('', views.MedicalSchool, name='MedicalSchool'),
...
]
MedicalSchool.html
<form action="{% url 'School:MedicalSchool' %}" method="POST">
{% csrf_token %}
<input type="text" name="school_name" placeholder="school name" required>
<input type="text" name="m_pass_out" placeholder="m pass out" required>
<select name='doctor_profile'>
{% for dr in DoctorProfile %}
<option name="doctor_profile" value="{{ dr.id }}">{{ dr.title}}</option> <!-- Match your code with {{ dr.title}} -->
{% endfor %}
</select>
<button type="submit"> Submit </button>
</form>
let me know if there was a problem
I have a contact and an event model where the event model has a foreign key to contact. The first half of my html obviously works, but for some reason when I display the list of other events that the contact has done, I can't get the list to show up. Is it because I'm calling {{event.whatever}} twice on the same page but in two differrent context?
views.py
class EventDetail(DetailView):
template_name = 'crm/eventdetail.html'
model = Event
models.py
class Contact(models.Model):
firstname = models.CharField(max_length=20, null=True, blank=True)
lastname = models.CharField(max_length=20, null=True, blank=True)
email = models.CharField(max_length=40, null=True, blank=True)
phone = models.CharField(max_length=15, null=True, blank=True)
title = models.CharField(max_length=20, null=True, blank=True)
notes = models.CharField(max_length=400, null=True, blank=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["lastname"]
def __str__(self):
return self.firstname
class Event(models.Model):
event_type = models.CharField(max_length=20, choices = event_types)
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
should_follow_up = models.BooleanField(default=False)
date = models.DateField()
notes = models.CharField(max_length=400)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('events_detail', kwargs={'pk': self.pk})
eventdetail.html
<div id="container">
<h1> Event: {{event.event_type}} </h1>
<ul>
<li>Event Contact: {{event.contact}}</li>
<li>Created By: {{event.created_by}}</li>
<li>Date: {{event.date}}</li>
<li>Note: {{event.notes}}</li>
</ul>
<h1>Events for {{event.contact}}</h1>
<table class="table">
<tr>
<th scope="col">Event Type</th>
<th scope="col">Date</th>
<th scope="col">3</th>
</tr>
{% for event in contact.event_set.all %}
<tr>
<td> {{event.event_type}}</td>
<td> {{event.date}}</td>
<td> </td>
</tr>
{% endfor %}
</table>
<p>This event was inputted on {{event.created}} and last edited on {{event.updated}}</p>
</div>
The for loop which is supposed to display all the other events the contact has done is not showing up. Any help is appreciated
Changes my view
class EventDetail(DetailView):
def get(self, request, *args, **kwargs):
event = get_object_or_404(Event, pk=kwargs['pk'])
events = event.contact.eventss.all()
context = {'event': event, 'events':events}
return render(request, 'crm/eventdetail.html', context)
Added a related_name to my model
contact = models.ForeignKey(Contact, related_name='eventss', on_delete=models.CASCADE)
Here is the html file that finally worked
{% for events in event.contact.eventss.all %}
<tr>
<td>{{events.event_type}}</td>
<td>{{events.date}}</td>
<td> </td>
</tr>
{% endfor %}
I am creating a project management app
Each user has multiple projects and each project has a set of data
When first logged in the user sees a list of all the projects only he created.i am able to do this.
Then when clicked on the project the data related only to that project is to be shown.
How do i do that in django?
My projects model
class projectsmodel(models.Model):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True,on_delete=models.SET_NULL)
projects=models.CharField(max_length=300)
def save_model(self,request,obj,form,change):
obj.added_by=request.User
super().save_model(request,obj,form,change)
def __str__(self):
return self.projects
My BOQ Model,it is the model that needs to be filtered based on project it is redirected from
class boqmodel(models.Model):
project_name = models.ForeignKey(projectsmodel, null=True, blank=True, on_delete=models.SET_NULL)
code = models.IntegerField()
building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True)
level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True)
activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True)
subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True)
duration = models.IntegerField()
linkactivity = models.CharField(max_length=300, null=True, blank=True)
linktype = models.CharField(choices=choicestype, max_length=300, null=True, blank=True)
linkduration = models.IntegerField(default=0)
plannedstart = models.DateField(null=True, blank=True)
plannedfinish = models.DateField(null=True, blank=True)
actualstart = models.DateField(null=True, blank=True)
actualfinish = models.DateField(null=True, blank=True)
html page of projects
<tbody>
<tr>
<td style="vertical-align: top;">Projects<br>
</td>
<td>Open</td>
<td>Edit</td>
<td>Delete</td>
</tr>
{% for projectsmodel in projects1 %}
<tr>
<td>{{projectsmodel.projects}}</td>
<td><a href="{% url 'projecthome' %}"<button class="btn btn-warning">Open</button></td><a></button>
<td>Edit</button></button>
<td>Delete</button></button>
</td>
</tr>
{% endfor %}
<a class="btn btn-primary" href="createprojects/">Create Projects</a>
{% endblock %}
my views for project
#login_required
def projects(request):
projects1 = projectsmodel.objects.filter(added_by =request.user)
context = {'projects1': projects1}
return render(request, 'projectslist.html',context )
Ok what i have understood. You need a structure like this.
models.py
class Project(models.Model):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True,on_delete=models.CASCADE)
project_name = models.CharField(max_length=255)
code = models.IntegerField()
building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True)
level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True)
activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True)
subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True)
duration = models.IntegerField()
linkactivity = models.CharField(max_length=300, null=True, blank=True)
linktype = models.CharField(choices=choicestype, max_length=300, null=True, blank=True)
linkduration = models.IntegerField(default=0)
plannedstart = models.DateField(null=True, blank=True)
plannedfinish = models.DateField(null=True, blank=True)
actualstart = models.DateField(null=True, blank=True)
actualfinish = models.DateField(null=True, blank=True)
urls.py
from yourapp.views import project_details
#Add this url to your url patterns
url(r'^project-details/(?P<projectId><pk>[0-9]+)/$',project_details,name='project_details')
views.py
from yourapp.models import Project
#login_required
def project_list(request):
user_projects = Project.objects.filter(added_by=request.user)
context = {'projects': user_projects}
return render(request, 'projectslist.html',context )
#login_required
def project_details(request,projectId):
context = {}
project_required = Project.objects.get(id=int(projectId))
context['project']= project_required
return render(request,"yourapp/projectDetails.html",context)
This is projectlist.html .You can add button to open project details. For the sake of simplicity i have not added any extra html element.
{% for project in projects %}
<tr>
<td> {{project.project_name}}</td>
</tr>
{% endfor %}
projectDetails.html
<p>Project Name : {{ project.project_name }} </p>
<p>Project Link Activity: {{ project.linkactivity }} </p>
<!-- and so on -->
P.S: where "yourapp" is the django app you have in your django project
I am building an application that allows a user to create a scenario, then create associated emails, t, calls and trades to the scenario.
There is a 1:many relationship with the scenario and the communications. The issue I am having is I want the user to be able to click the scenario, it then shows the filtered list of communications, each communication source is a tab. The way I am filtering the communication is based on the id of the foreign key on the object. However if there is no entry for the datasource I receive a "no reverse match" because I am using the scenario id from the first object and that doesnt exist if there is no communication for that scenario.
I am stumped on what the best way to do this, besides removing tabs which I like.
Please let me know if I am missing anything, I am relatively new to programming and very new to Django.
models.py
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
class Scenario(models.Model):
name = models.CharField(max_length=256, blank=False, null=False, unique=True)
description = models.TextField(max_length=1000)
def get_absolute_url(self):
return reverse('scenarios:detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.name
class Email(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE )
recipient_email = models.EmailField()
sender_email = models.EmailField()
subject = models.CharField(blank=True, null=False, max_length=256)
body = models.TextField(blank=True, null=False, max_length=2048)
# timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
# updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def get_absolute_url(self):
return reverse('scenarios:email-index')
def __unicode__(self):
return self.sender_email + ' ' + self.recipient_email + ' ' + self.subject
class InstantMessage(models.Model):
NETWORKS = (
('Yahoo', 'Yahoo'),
('MSN', 'MSN'),
('Skype', 'Skype')
)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
description = models.CharField(max_length=256, null=False, blank=False)
network = models.CharField(max_length=50, null=False, blank=False, choices=NETWORKS)
room = models.CharField(max_length=100, null=False, blank=False)
starttime = models.TimeField(blank=False, null=False)
endtime = models.TimeField(blank=False, null=False)
participant1 = models.CharField(max_length=256, null=False, blank=False)
participant2 = models.CharField(max_length=256, null=False, blank=False)
chatcsv = models.FileField(upload_to='chatfiles')
def get_absolute_url(self):
return reverse('scenarios:im-index')
def __unicode__(self):
return "Network=" + self.network + " Description:" + self.description
class VoiceCall(models.Model):
DIRECTION = (
('outbound', 'Outbound'),
('inbound', 'Inbound')
)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
description = models.CharField(max_length=256, null=False, blank=False)
direction = models.CharField(choices=DIRECTION, null=False, blank=False, default="Outbound", max_length=15)
starttime = models.TimeField(blank=False, null=False)
endtime = models.TimeField(blank=False, null=False)
traderid = models.CharField(max_length=50,blank=False, null=False)
diallednumber = models.BigIntegerField(blank=True, null=True)
cli = models.BigIntegerField(blank=True, null=True)
nameofcaller = models.CharField(max_length=100, blank=True, null=True)
nameofline = models.CharField(max_length=100, blank=True, null=True)
wavfile = models.FileField(upload_to='voice')
transcript = models.FileField(blank=True, null=True, upload_to='voice')
bagofwords = models.FileField(blank=True, null=True, upload_to='voice')
def get_absolute_url(self):
return reverse('scenarios:call-index')
def __unicode__(self):
return self.description
class Trade(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
tradeprefix = models.CharField(max_length=6, null=False, blank=False)
trader = models.CharField(max_length=256, null=False, blank=False)
sales = models.CharField(max_length=256, null=False, blank=False)
counterpartyid = models.CharField(max_length=256, null=False, blank=False)
counterpartyname = models.CharField(max_length=256, null=False, blank=False)
brokerid = models.CharField(max_length=256, null=False, blank=False)
brokername = models.CharField(max_length=256, null=False, blank=False)
isevent = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('scenarios:trade-index')
# def __unicode__(self):
# return self.description
class Mobile(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
displayname = models.CharField(max_length=100, null=False, blank=False)
email = models.EmailField()
tonumber = models.BigIntegerField(blank=True, null=True)
fromnumber = models.BigIntegerField(blank=True, null=True)
message = models.CharField(blank=True, null=False, max_length=1024)
def get_absolute_url(self):
return reverse('scenarios:mobile-index')
views.py
class IMScenarioList(generic.ListView):
model = InstantMessage
template_name = 'scenarios/im_filtered.html'
context_object_name = 'scenario_ims'
def get_queryset(self):
return InstantMessage.objects.filter(scenario=self.kwargs['pk'])
class CallScenario(generic.ListView):
model = VoiceCall
template_name = 'scenarios/call_filtered.html'
context_object_name = 'scenario_calls'
def get_queryset(self):
return VoiceCall.objects.filter(scenario=self.kwargs['pk'])
class MobileScenario(generic.ListView):
model = Mobile
template_name = 'scenarios/mobile_filtered.html'
context_object_name = 'scenario_mobiles'
def get_queryset(self):
return Mobile.objects.filter(scenario=self.kwargs['pk'])
class TradeScenario(generic.ListView):
model = Trade
template_name = 'scenarios/trades_filtered.html'
context_object_name = 'trades'
def get_queryset(self):
return Trade.objects.filter(scenario=self.kwargs['pk'])
urls.py
url(r'^(?P<pk>[0-9]+)/email/$', views.EmailScenarioList.as_view(), name='email-scenario'),
# Instant Messages
url(r'^im/$', views.IMList.as_view(), name='im-index'),
url(r'^im/add/$', views.IMCreate.as_view(), name='im-create'),
url(r'^im/(?P<pk>[0-9]+)/update/$', views.IMUpdate.as_view(), name='im-update'),
url(r'^im/(?P<pk>[0-9]+)/delete/$', views.IMDelete.as_view(), name='im-delete'),
url(r'^(?P<pk>[0-9]+)/im/$', views.IMScenarioList.as_view(), name='im-scenario'),
# Voice Calls
url(r'^calls/$', views.CallList.as_view(), name='call-index'),
url(r'calls/add/$', views.CallCreate.as_view(), name='call-create'),
url(r'^calls/(?P<pk>[0-9]+)/update/$', views.CallUpdate.as_view(), name='call-update'),
url(r'^calls/(?P<pk>[0-9]+)/delete/$', views.CallDelete.as_view(), name='call-delete'),
url(r'^(?P<pk>[0-9]+)/voice/$', views.CallScenario.as_view(), name='call-scenario'),
# trades
url(r'^trades/$', views.TradeList.as_view(), name='trade-index'),
url(r'^trades/add/$', views.TradeCreate.as_view(), name='trade-create'),
url(r'^trades/(?P<pk>[0-9]+)/update/$', views.TradeUpdate.as_view(), name='trade-update'),
url(r'^trades/(?P<pk>[0-9]+)/delete/$', views.TradeDelete.as_view(), name='trade-delete'),
url(r'^(?P<pk>[0-9]+)/trade/$', views.TradeScenario.as_view(), name='trade-scenario'),
# mobile
url(r'^mobile/$', views.MobileList.as_view(), name='mobile-index'),
url(r'^mobile/add/$', views.MobileCreate.as_view(), name='mobile-create'),
url(r'^mobile/(?P<pk>[0-9]+)/update/$', views.MobileUpdate.as_view(), name='mobile-update'),
url(r'^mobile/(?P<pk>[0-9]+)/delete/$', views.MobileDelete.as_view(), name='mobile-delete'),
url(r'^(?P<pk>[0-9]+)/mobile/$', views.MobileScenario.as_view(), name='mobile-scenario'),
Templates
trade_index.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<table id="myTable" class="tablesorter tablesorter-bootstrap">
<thead>
<tr>
<th class="first-name filter-select" data-placeholder="Select a Scenario">Scenario</th>
<th></th>
<th>Trade Prefix</th>
<th>Trader</th>
<th>Sales</th>
<th>Counterparty ID</th>
<th class="first-name filter-select" data-placeholder="Select Counterparty">Counterparty Name</th>
<th>Broker ID</th>
<th></th>
<th class="first-name filter-select" data-placeholder="Select Broker">Broker Name</th>
<th class="first-name filter-select" data-placeholder="IsEvent">IsEvent</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for trade in trades %}
<tr>
<td data-toggle="tooltip" title="Description: {{trade.scenario.description}}">{{trade.scenario}}</td>
<td></td>
<td>{{trade.tradeprefix}}</td>
<td>{{trade.trader}}</td>
<td>{{trade.sales}}</td>
<td>{{trade.counterpartyid}}</td>
<td>{{trade.counterpartyname}}</td>
<td>{{trade.brokerid}}</td>
<td></td>
<td>{{trade.brokername}}</td>
<td>{{trade.isevent}}</td>
<td>
<a href="{% url 'scenarios:trade-update' trade.id %}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-pencil" />
</button>
</a>
</td>
<td><form action="{% url 'scenarios:trade-delete' pk=trade.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="call_id" value="{{ trade.id}}"/>
<button type="submit" class="btn btn-default btn-sm" onclick="return confirm('Are you sure you want to delete {{trade.description}}?')">
<span class="glyphicon glyphicon-trash" />
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{% url 'scenarios:trade-create' %}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-plus" />
</button>
</a> Add Trade
<br>
<button type="button" class="btn btn-default btn-sm" value="Back" onClick="javascript:history.go(-1);">
<span class="glyphicon glyphicon-backward" />
</button>
</div>
{% endblock %}
trades_filtered.html
{% extends 'scenarios/trade_index.html' %}
{% block content %}
{% with trades|first as first_trade %}
<ul class="nav nav-pills">
<li class="active">trades</li>
<li>emails</li>
<li>instant messages</li>
<li>voice</li>
<li>mobile</li>
</ul>
{% endwith %}
{{ block.super }}
{% endblock %}
Right now in trades_filtered.html you take the ID of a given scenario and use that ID to manually construct your five URLs. If it were me, I'd use a custom model method to determine whether or not we need to generate a URL first.
class Scenario(models.Model):
name = models.CharField(max_length=256, blank=False, null=False, unique=True)
description = models.TextField(max_length=1000)
def generate_trade_url(self):
if self.trade_set.exists():
return reverse('scenarios:trade-scenario', kwargs={'pk':self.pk})
return None
def generate_email_url(self):
...
You would need one method like this for each URL you want to generate. You can this use this logic either in the view (preferable) or in your template (simpler but slower) to dynamically generate your URLs only when they are valid.
EDIT: I just looked at this answer a second time. I included null=False in the name field definition because it was in the original, but be aware that it doesn't actually do anything useful on a CharField. Django doesn't use null values for those fields, instead storing them as '' (empty string).