Django IntegrityError at /doctor-add-notes NOT NULL constraint failed: - django

I am a newbie.
Enhancing a project For the current user, there are different members, for each member I want to add Notes with the current time & date. so I am using Django in-built user model.
for example
User1
Member1 Notes Date & Time
Member2 Notes Date & Time
Member3 Notes Date & Time
**User2**
Member1 Notes Date & Time
Member2 Notes Date & Time
Member3 Notes Date & Time
for now just trying to add user1, member1 Notes & Date but after submitting the form getting an error. how to correct that,
IntegrityError at /doctor-add-notes
NOT NULL constraint failed: hospital_notes.user_id
Request Method: POST
Request URL: http://127.0.0.1:8000/doctor-add-notes
Django Version: 3.0.7
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: hospital_notes.user_id
Exception Location: C:\Users\user1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396
Python Executable: C:\Users\user1\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.3
Python Path:
['C:\\Users\\user1\\PycharmProjects\\Project\\hospitalmanagement',
'C:\\Users\\user1\\PycharmProjects\\Project\\hospitalmanagement',
'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\user1\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Thu, 31 Dec 2020 03:37:51 +0000
Here is part of relevant code
**Models**
class Notes(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE)
report = models.TextField(max_length=500)
NoteDate = models.DateField(auto_now=True)
**View:**
def doctor_add_notes_view(request):
appointmentForm=forms.PatientNotesForm()
mydict={'appointmentForm':appointmentForm,}
print(mydict)
if request.method=='POST':
appointmentForm=forms.PatientNotesForm(request.POST)
if appointmentForm.is_valid():
appointment=appointmentForm.save(commit=False)
appointment.save()
return HttpResponseRedirect('doctor_add_notes')
else:
return render(request, 'hospital/doctor_view_patient.html',{'alert_flag': True})
return render(request,'hospital/doctor_add_notes.html',context=mydict)
**Forms:**
class PatientNotesForm(forms.ModelForm):
class Meta:
model=models.Notes
fields=['report']
**doctor_add_notes.html**
{% extends 'hospital/doctor_base.html' %}
{% load widget_tweaks %}
{% block content %}
<head>
<style media="screen">
a:link {
text-decoration: none;
}
.note {
text-align: center;
height: 80px;
background: -webkit-linear-gradient(left, #0072ff, #8811c5);
color: #fff;
font-weight: bold;
line-height: 80px;
}
.form-content {
padding: 5%;
border: 1px solid #ced4da;
margin-bottom: 2%;
}
.form-control {
border-radius: 1.5rem;
}
.btnSubmit {
border: none;
border-radius: 1.5rem;
padding: 1%;
width: 20%;
cursor: pointer;
background: #0062cc;
color: #fff;
}
.menu {
top: 50px;
}
</style>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<br><br>
<form method="post">
{% csrf_token %}
<div class="container register-form">
<div class="form">
<div class="note">
<p>Patient Notes Details</p>
</div>
<div class="form-content">
<div class="row">
<div class="col-md-12">
<div class="form-group">
{% render_field appointmentForm.report class="form-control" placeholder="Description" %}
</div>
</div>
</div>
<button type="submit" class="btnSubmit">Book</button>
</div>
</div>
</div>
</form>
{% endblock content %}

Related

Insert multi selected option text into pg using django

For instance, I used Django to pull certain unique number data from my database.
Then I created dropdown with search using select2. And used jQuery for search functionality. With this I could select multiple unique number at a time and with output printed in textarea field.
my question is, how to insert multiple selected options in Postgrel using Django.
I need help in backend as i m newbie in django
I tried to served everywhere but I could see only php guide.
this is my frontend code
enter code here
Search Models for CId
{% csrf_token %}
{% for x in searchmodels %}
{{ x.cid }}
{% endfor %}
You can add multiple CID and click Add
-->
<br>
<div class="resultbox">
<h2>Selected CIDs</h2>
<textarea name="" id="cidresult" cols="70" rows="15"></textarea><br><br>
<input type="button" id="addcid" value="Submit" onclick="searchresult();">
</div>
</form>
</tr>
<style>
.resultbox{
position: fixed;
left: 30%;
top: 10px;
width: 550px;
background-color: antiquewhite;
padding-left: 30px;
padding-right: 10px;
}
</style>
Now here is my jQuery code
$(document).ready(function()
{
$('#selectedcid').select2({
placeholder:'Search CID...',
closeOnSelect:false
});
$('#selectedcid').on('change',function()
{
var resultdisplay=$('#selectedcid option:selected').text();
$('#cidresult').val(resultdisplay).join(',');
})
});
this is how it looks nowenter image description here

How to show the information in the same page where I am submitting form in django

I am trying to submit a form and get the result in the same page where I have created the form . But , can't get the values in the same page . But , whenever I am trying to take the value in a different page it's working.
My views.py file :
def home(request):
words = request.GET['text']
count = len(words.split())
context = {'count':count}
return render(request,'index.html',context)
My index.html file:
<div class="container">
<h3 style="display:inline-block; text-transform: capitalize; padding-top: 10px; border-bottom: 2px solid #e5e5e5;">Word counting app</h3>
<h5 style="padding-top: 40px;text-transform: capitalize;">enter your word below to count</h5>
<div class="row">
<div class="col-lg-6">
<form method="" action="">
<textarea name="text" cols="30" rows="7"></textarea>
<button type="submit" style="padding: 6px 28px; border: none; background:orange; margin-top: 10px;">Submit</button>
</form>
<p>{{count}</p>
</div>
</div>
</div>
Add form method 'GET' to your html and remove action attribute. If there are no action provided in the form element, it will be posted to same url as your page.
<form method="GET">

django-recaptcha returning "Error: Missing required parameters: sitekey"

I followed the django-recaptcha directions to add a field to my contact form. When it renders (in my local test), it has a field that says "Captcha:" but no actual captcha rendered. The dev console in chrome says
Uncaught Error: Missing required parameters: sitekey
in https://www.gstatic.com/recaptcha/api2/v1531759913576/recaptcha__en.js
This answer says to add render=explicit to the javascript, but a) I'm not sure that's even the problem, b) I would think the Django package would handle it.
Django 1.11.8, Django recaptcha 1.4.0.
Django form is
class ContactForm(forms.Form):
contacter = forms.EmailField(required=True,
label=_('Your Email (optional)'),
widget=forms.widgets.TextInput(
attrs={'size': '50'}))
contact_text = forms.CharField(required=True,
widget=forms.widgets.Textarea(
attrs={'rows': '10',
'cols': '70',
'class': 'defaultText',
'title':
_('Type a message here')}))
captcha = ReCaptchaField()
The rendered Django form is below.
<form action="/contact/"
method="post" id="new-contact">
<input type='hidden' name='csrfmiddlewaretoken' value='...' />
<fieldset id="contact">
<legend>Contact Us</legend>
<tr><th><label for="id_contacter">Your Email (optional):</label></th><td><input type="text" name="contacter" required id="id_contacter" size="50" /></td></tr>
<tr><th><label for="id_contact_text">Contact text:</label></th><td><textarea name="contact_text" rows="10" title="Type a message here" id="id_contact_text" required cols="70" class="defaultText">
</textarea></td></tr>
<tr><th><label for="id_captcha">Captcha:</label></th><td><script src="https://www.google.com/recaptcha/api.js?hl=en"></script>
<div class="g-recaptcha" data-sitekey="" data-required="True" data-id="id_captcha" ></div>
<noscript>
<div style="width: 302px; height: 352px;">
<div style="width: 302px; height: 352px; position: relative;">
<div style="width: 302px; height: 352px; position: absolute;">
<iframe src="https://www.google.com/recaptcha/api/fallback?k="
frameborder="0" scrolling="no"
style="width: 302px; height:352px; border-style: none;">
</iframe>
</div>
<div style="width: 250px; height: 80px; position: absolute; border-style: none;
bottom: 21px; left: 25px; margin: 0px; padding: 0px; right: 25px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response"
class="recaptcha_challenge_field"
style="width: 250px; height: 80px; border: 1px solid #c1c1c1;
margin: 0px; padding: 0px; resize: none;" value="">
</textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge" />
</div>
</div>
</div>
</noscript></td></tr>
</fieldset>
<input type="submit" value="Submit" />
</form>
I also filed this issue here.
Setting RECAPTCHA_PRIVATE_KEY and RECAPTCHA_PUBLIC_KEY to empty strings as directed produces this error. If instead those variables are completely unset (in the Django settings for the dev environment), the library uses the test keys, and all is well.

How to use GeoDjango Pointfield in Form?

I wanted to know to to use the PointField widget that is automatically generated from a Django form.
I am using the generic views for this (CreateView)
This is what my model looks like.
from django.contrib.gis.db import models
class Post(models.Model):
title = models.CharField(max_length=60)
text = models.CharField(max_length=255)
location = models.PointField(geography=True, null=True, blank=True)
objects = models.GeoManager()
The form is then automatically generated for me and I just call it in my view. As such:
{{ form.as_p }}
This is the output of that piece of code.
<form method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='wVZJIf7098cyREWe3n3jiZinPdbl8nEe' />
<p><label for="id_title">Title:</label> <input id="id_title" maxlength="60" name="title" type="text" /></p>
<p><label for="id_text">Text:</label> <input id="id_text" maxlength="255" name="text" type="text" /></p>
<p><label for="id_location">Location:</label> <style type="text/css">
#id_location_map { width: 600px; height: 400px; }
#id_location_map .aligned label { float: inherit; }
#id_location_div_map { position: relative; vertical-align: top; float: left; }
#id_location { display: none; }
.olControlEditingToolbar .olControlModifyFeatureItemActive {
background-image: url("/static/admin/img/gis/move_vertex_on.png");
background-repeat: no-repeat;
}
.olControlEditingToolbar .olControlModifyFeatureItemInactive {
background-image: url("/static/admin/img/gis/move_vertex_off.png");
background-repeat: no-repeat;
}
</style>
<div id="id_location_div_map">
<div id="id_location_map"></div>
<span class="clear_features">Delete all Features</span>
<textarea id="id_location" class="vSerializedField required" cols="150" rows="10" name="location"></textarea>
<script type="text/javascript">
var map_options = {};
var options = {
geom_name: 'Point',
id: 'id_location',
map_id: 'id_location_map',
map_options: map_options,
map_srid: 4326,
name: 'location'
};
var geodjango_location = new MapWidget(options);
</script>
</div>
</p>
<input type="submit" value="Create" />
</form>
In the head tags I import an OpenLayers script from
http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js
However, the page will not show anything for the pointfield. (The other fields work just fine).
In chromedevtools it shows this error
Uncaught ReferenceError: MapWidget is not defined
For this line of code
var geodjango_location = new MapWidget(options)
Basically I want to know if there is someother javascript library I should be linking to or am I missing something else?
I've looked through the documentation on GeoDjango forms, but don't know what else to try
https://docs.djangoproject.com/en/dev/ref/contrib/gis/forms-api/
Add this to the head section:
<head>
{{ form.media }}
</head>
I have a related problem with my Admin UI. My solution is just a reference for your problem. Firefox browser was blocking the loading of mix http/https http://openlayers.org/api/2.13/OpenLayers.js because my geodjango site forces https.
One solution is to download the OpenLayer.js into my geodjango project static directory, and add the following line to my CustomGeoModelAdmin:
class MyCustomGeoModelAdmin(....):
openlayers_url = '/static/mygeodjangoproject/OpenLayers.js'
#property
def media(self):
"Injects OpenLayers JavaScript into the admin."
media = super(MyCustomGeoModelAdmin, self).media
media.add_js([self.openlayers_url])
return media
and voilĂ , my admin site now shows a Geographical Map for the Point Field.

Trouble getting django-chosen ChosenSelect widget to work

I'm trying to set up a ModelForm in Django that will use the django-chosen ChosenSelect widget for one of the fields. I have installed django-chosen and this is the code I have:
class TestForm(ModelForm):
class Meta:
model = Test
widgets = {
'field': chosenwidgets.ChosenSelect(),
}
However, the specifying the widgets has no effect and the form is outputted the same regardless of whether I define it. Any suggestions?
Are you including the form media in your template?
The example template below assumes that your base template has blocks extrastyle and extrahead where you include CSS and scripts respectively, and that you have included jquery 1.4+ in your base template.
# my_template.html
{% extends "base.html" %}
{% block extrastyle %}
{{ block.super }}
{{ form.media.css }}
{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ form.media.js }}
{% endblock %}
{% block content %}
<form action="." method="post">
<table>
{{ form }}
</table>
<p><input type="submit" value="Update" />
</form>
{% endblock %}
Here is my solution with using chosen.js directly. I installed it with bower and then included it in my admin class Media:
class MyModelAdmin(LockableAdmin, admin.ModelAdmin):
form = MyModelForm # has phase_id field
class Media:
js = ('components/chosen_v1.1.0/chosen.jquery.min.js', 'admin_tools/js/chosen_admin.js')
css = {'all': ('components/chosen_v1.1.0/chosen.min.css', 'admin_tools/css/chosen_admin.css')}
The additional chosen_admin.js and chosen_admin.css files contain my init script and css for making the select look more like django admin. Here are the contents:
chosen_admin.js:
/* Create own jquery namespace */
var django = {
"jQuery": django.jQuery.noConflict(true)
};
var jQuery = django.jQuery;
var $=jQuery;
$( document ).ready(function() {
$('#id_phase_id').chosen();
});
chosen_admin.css (optional):
a.chosen-single {
box-shadow: none;
border-radius: 0px;
background: white;
background-image: none;
}
a.chosen-single span{
line-height: 18px !important;
}
.vTextField{
width: 24em;
}
a.chosen-single, .chosen-container.chosen-container-single, .chosen-container-single.chosen-single{
position: absolute;
box-shadow: none !important;
border-radius: 0px !important;
background: white !important;
background-image: none !important;
font-size: 11px !important;
height: 18px !important;
padding-left: 2px !important;
}
.chosen-container-single .chosen-single div b {
background-position: 0px 0px;
}
I got some insights here and made corrections as needed. Also see chosen.js. Hope this helps :)