I have my code setup to send me emails every time someone is filling up a form but the email reports are being cut off.
This is what I have in my database as an input example from a user:
awd wda aawd awd awd aaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awd
And this is what shows up in the email report:
awd wda aawd awd awd aaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd awd awdaawd
I don't have any styling in my email template other than the regular tags to separate the answer output.
Is there any limitation on what you can output?
This is my CF code:
<cfquery name="fullResults" datasource="#variables.dsn#">
select s.id, s.name surveyname, q.question, subq.answer subquestion, isnull(isnull(isnull(isnull(a.answer, r.textboxmulti),r.other),r.textbox),r.truefalse) as selectedanswer, a.*, r.*
from results r
join questions q on r.questionidfk = q.id
left join answers subq on r.itemidfk = subq.id
left join answers a on r.answeridfk = a.id
join surveys s on q.surveyidfk = s.id
where owneridfk = <cfqueryparam value="#arguments.ownerid#" cfsqltype="CF_SQL_VARCHAR" maxlength="255">
order by s.id, owneridfk, q.rank, subq.rank desc
</cfquery>
#fullResults.selectedanswer#
You should check your Data Source setup in the ColdFusion Administrator and make sure that the Long Text Buffer is set to a long enough value to allow you to pull out the data you need.
The issue was that inisnull(isnull(isnull(isnull(a.answer, r.textboxmulti),r.other),r.textbox),r.truefalse) as selectedanswer the a.answer was set to 225 character and everything else was trimmed down to that. After I added a convert function around it everything works fine.
Related
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
telefoon = models.CharField(max_length=10, blank=True)
telefoon_mobiel = models.CharField(max_length=10, blank=True)
woonplaats = models.CharField(max_length=20, blank=True)
postcode = models.CharField(max_length=6, blank=True)
straat = models.CharField(max_length=20, blank=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
form.py
class ProfileForm(forms.ModelForm):
straat = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
postcode = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
woonplaats = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
telefoon = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
telefoon_mobiel = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = Profile
fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat')
views.py
#login_required
#transaction.atomic
def profiel(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, ('Profiel aangepast'))
return redirect('user')
else:
messages.error(request, ('Los ondestaande probleem op'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'public/profiel.html', {
'user_form': user_form,
'profile_form': profile_form,
})
template:
<div class="card-body">
<h5 class="card-title">Profiel {{ user.get_full_name }}</h5>
<hr>
<div class="container">
<div class="row">
<div class="col-sm">
{{ user.first_name }} {{ user.last_name }}
</div>
<div class="col-sm">
{{ straat }}
</div>
</div>
<br/>
<div class="row">
<div class="col-sm">
<label>Achternaam:</label>
</div>
<div class="col-sm">
{{ user_form.last_name }}
</div>
</div>
When I call for example the field straat I am getting an editable field and I just want to show the value of it as text.
When im deleting from customer table and employee table im getting this error:
DoesNotExist at /delete/2 Customer matching query does not exist.
Below is the view function code to that wrote to delete the row in each table.
Please, can any one help me to get out from this, any help would be greatly appreciated.
def delete(request, user_id):
delCust = Customer.objects.get(user_id = user_id)
delEmp = Employee.objects.get(user_id = user_id)
delEmp.delete()
delCust.delete()
return redirect("/admins")
Employee table html code:
<table class="table table-responsive d-md-table mb-0">
<thead>
<tr>
<th scope="col" class="border-bottom-0">Job Id</th>
<th scope="col" class="border-bottom-0">Designation</th>
<th scope="col" class="border-bottom-0">Experience</th>
<th scope="col" class="border-bottom-0">Action</th>
</tr>
</thead>
<tbody>
{% for items in Customer %}
<tr>
<td nowrap="">{{items.user_id}}</td>
<td nowrap="">{{items.designation}}</td>
<td nowrap="" class="text-capitalize">{{items.experience}} years</td>
<td nowrap="" class="d-flex">
<button type="submit" class="btn btn-success mr-2 text-capitalize"
data-toggle="modal" data-target="#exampleModal">
Send request
</button>
<!--send request-->
<button type="button" class="btn btn-outline-info mr-2 text-capitalize"
data-toggle="modal" data-target="#studentdetailsmodal">
view
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
Here is my model for Customer and employee:
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
phone_number = models.CharField(max_length=20)
location = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
designation = models.CharField(max_length=20)
experience = models.IntegerField(null=True)
salon_name = models.CharField(max_length=20)
salon_category = models.CharField(max_length=20)
class Employee(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
phone_number = models.CharField(max_length=20)
designation = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
current_salary = models.IntegerField()
expected_salary = models.IntegerField()
work_experience = models.CharField(max_length=20)
salon_category = models.CharField(max_length=20)
Very new to Django.
I created a custom user model as below. I also created a page for the users to update their details. I want the two user 'groups' to use the same page 'account.html' to update their details. But if the user is an 'Employee' I want to display additional fields.
Simply put, I'm trying to achieve the following logic:
If users group = 'Client' then display fields A & B to update
If users group = 'Employee' then display fields A, B, C & D update
Any help much appreciated
Models.py
group_types = [('Client', 'Client'), ('Employee','Employee')]
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
groups = models.CharField(choices=group_types, default="client", max_length=60)
company_name = models.CharField(verbose_name='company name', max_length=30)
account.html
<form class="form-signin" method="post">{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Account Details</h1>
<p> Email Address </p>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus value={{account_form.initial.email}}>
<br>
<p> Username </p>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username" required autofocus value={{account_form.initial.username}}>
<br>
<p> Company Name </p>
<input type="text" name="company_name" id="inputCompany_Name" class="form-control" placeholder="Company Name" required autofocus value={{account_form.initial.company_name}}>
You can use modelform_factory to generate a form dynamically, you can pass different fields depending on the user
FIELDS = {
'Client': ['a', 'b', 'c'],
'Employee': ['a', 'b', 'c', 'd', 'e']
}
def view(request):
form_class = modelform_factory(Account, fields=FIELDS.get(request.user.groups))
form = form_class(instance=request.user)
...
I having a html form consisting of some fields with details and I want to post some details of the form to one model and some details to another model how this can be done?
my models.py
class room(models.Model):
id = models.IntegerField(primary_key=True)
image = models.ImageField(upload_to='images')
content = models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.content
# This is the model for goals
class goal(models.Model):
id=models.IntegerField(primary_key=True)
goal = models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.goal
# This is the model for designs
class design(models.Model):
id=models.IntegerField(primary_key=True)
image = models.ImageField(upload_to='images')
content = models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.content
# This is the model for furniture
class furniture(models.Model):
id=models.IntegerField(primary_key=True)
phrase=models.CharField(max_length=60,default='111111')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.phrase
# This is the users model
class user(models.Model):
username=models.CharField(max_length=20)
email=models.CharField(max_length=50,unique=True)
password=models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.username
class UserRequirement(models.Model):
id=models.IntegerField(primary_key=True)
user=models.ForeignKey(user,on_delete=models.CASCADE)
rooms = models.ForeignKey(room,on_delete=models.CASCADE)
goals = models.ManyToManyField(goal)
styles = models.ManyToManyField(design)
furn = models.ForeignKey(furniture,on_delete=models.CASCADE)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
My views.py for posting:
def user_register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
username=request.POST["username"]
email = request.POST['email']
password = request.POST['password']
rooms = request.POST['room']
g=goals=request.POST['goal']
g = g.split(',')
s=styles=request.POST['style']
s=s.split(',')
furn=request.POST['furn']
u = user(username=username,password=password,email=email)
u.rooms=room.objects.get(pk=rooms)
goals = goal.objects.filter(pk__in=g)
styles = design.objects.filter(pk__in=s)
u.furn = furniture.objects.get(pk=furn)
u.save()
u.goals.add(*goals)
u.styles.add(*styles)
messages.success(request,'Your project design has been registered')
return render(request,'register.html')
else:
messages.warning(request,'Cant be registered this email already exists')
return render(request,'register.html')
My form.html is
<form action="{% url 'modsy:user_register' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
<div id="uname_error"></div>
</div>
<div class="form-group">
<input type="hidden" name="room" id="name" value="">
</div>
<div class="form-group" >
<input type="hidden" name="goal" id="goal" value="">
</div>
<div class="form-group">
<input type="hidden" name="style" id="style" value=" ">
</div>
<div class="form-group" >
<input type="hidden" name="furn" id="furn" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required><br>
<div id="name_error" style="color:red;"></div></div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
<div id="pwd_error" style="color:red;"></div>
</div>
<div class="button"><input type="submit" value="Save the Project" style="background-color:#000080;" class="btn btn-secondary btn-block" onclick="return validation(form)">
</form>
Now here I want to post the username email and password to the user model and the user room goal furniture style should be stored in the user_requirement model how it can be done?
My forms.py
from django import forms
from . models import user
from django.contrib.auth.models import User
from . models import UserRequirement
from . models import room
from . models import goal
from . models import design
from . models import furniture
class UserForm(forms.ModelForm):
class Meta:
model = user
fields = ('email',)
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
# Check to see if any users already exist with this email as a username.
try:
match = User.objects.get(email=email)
except User.DoesNotExist:
# Unable to find a user, this is fine
return email
raise forms.ValidationError('This email address is already in use.')
class UserRequirementForm(forms.ModelForm):
class Meta:
model = UserRequirement
fields=(user,rooms,goals,styles,furn)
Option 1: Create a form with all the fields you need and override the save method to store the data where you need them. You can use your User model as the base model and add any extra fields you need for other models.
Option 2: Use two different forms and process them separately.
if request.method == 'POST':
user_form = UserForm(data=request.POST)
user_requirement_form = UserRequirementForm(data=request.POST)
if user_form.is_valid() and user_requirement_form.is_valid():
user = user_form.save()
user_requirement = user_requirement_form.save(commit=False)
# Set user
user_requirement.user = user
user_requirement.save()
user_requirement_form.save_m2m()
redirect(...)
else:
# Handle errors
messages.warning(request, 'Please correct the errors below')
else:
# GET
user_form = UserForm()
user_requirement_form = UserRequirementForm()
return render(request,'register.html', {'user_form': user_form, 'requirements_form': user_requirement_form})
Then make sure you actually show the errors in your template, using {{ user_form.errors }} or {{ user_form.email.errors }} depending whether you show all the errors at once or per field.
I think the following approach would help.
Forms.py
class UserForm(forms.ModelForm):
class Meta:
model = user
fields = ['email',]
class UserRequirementForm(forms.ModelForm):
class Meta:
model = UserRequirement
fields=['rooms','goals','styles','furn']
Then 2. Views.py
from .forms import UserForm, UserRequirementForm
from django.shortcuts import redirect, render
def register_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
user_requirement_form = UserRequirementForm(request.POST)
if user_form.is_valid() and user_requirement_form.is_valid():
user = user_form.save()
user_requirement = user_requirement_form.save(commit=False)
user_requirement.user = request.user # <- Setting the user to currently logged in user
user_requirement.save()
redirect('name_of_url_to_redirect_to')
else:
user_form = UserForm()
user_requirement_form = UserRequirementForm()
context = {
'user_form': user_form,
'user_requirement_form' : user_requirement_form,
}
return render(request, 'path_to_template.html', context)
Then finally in the template (.html file):
<form method="POST">
{{user_form.as_p}}
{{user_requirement_form.as_p}}
<button type="submit"> Submit</button>
</form>
That should render your form and save data correctly on submit
PS: Avoid adding id field on your models as Django already gives you an id field by default.
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')
]