Commit 9c3728d1 authored by Rahul-chunduru's avatar Rahul-chunduru

added image upload facility

parent b7f7551d
*.pyc
logfile
\ No newline at end of file
......@@ -115,13 +115,13 @@ AUTH_PASSWORD_VALIDATORS = [
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
......
......@@ -4,6 +4,8 @@ from django.contrib.auth.models import User
from .models import *
from django.forms.widgets import Select, Widget,DateTimeInput,TimeInput
import datetime
from .models import QuestionImage
from django.forms import Textarea
# from datetimepicker.widgets import DateTimePicker
# class QuestionForm(forms.ModelForm):
......@@ -17,7 +19,7 @@ import datetime
# model = Options
# fields = ('option_value',)
VISIBILITY_CHOICES= ('1980', '1981', '1982')
#VISIBILITY_CHOICES= ('1980', '1981', '1982')
# class TestForm(forms.ModelForm):
# # start_time = forms.DateTimeField(widget=DateTimePicker(), initial=datetime.datetime.now())
......@@ -28,6 +30,11 @@ VISIBILITY_CHOICES= ('1980', '1981', '1982')
# model = Test
# exclude = ['test_ID', 'ownership']
class ImageFileUploadForm(forms.ModelForm):
q_id = forms.IntegerField(label='')
class Meta:
model = QuestionImage
fields = ['image' , 'imageDesc' ]
class TestForm(forms.ModelForm):
class Meta:
......
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-11-25 16:12
# Generated by Django 1.11.14 on 2018-11-25 21:41
from __future__ import unicode_literals
import django.core.validators
......@@ -81,7 +81,8 @@ class Migration(migrations.Migration):
('difficulty_set', models.CharField(max_length=20)),
('difficulty_observed', models.CharField(max_length=20)),
('question_text', models.CharField(max_length=1000)),
('image_link', models.CharField(max_length=200)),
('num_appeared', models.IntegerField(default=0)),
('num_correct', models.IntegerField(default=0)),
('visibility', models.CharField(max_length=20)),
('ownership', models.CharField(max_length=20)),
('faculty', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='ARFA_app.Faculty')),
......@@ -90,11 +91,11 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='QuestionImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image_id', models.AutoField(primary_key=True, serialize=False)),
('image', models.FileField(upload_to='QuestionImages/')),
('imageDesc', models.CharField(max_length=100)),
('orderNum', models.IntegerField(default=1)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ARFA_app.Question')),
('q_ID', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='ARFA_app.Question')),
],
),
migrations.CreateModel(
......
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-11-25 18:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ARFA_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='question',
name='num_appeared',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='question',
name='num_correct',
field=models.IntegerField(default=0),
),
]
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-25 18:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ARFA_app', '0003_auto_20181125_1102'),
]
operations = [
migrations.AddField(
model_name='question',
name='num_appeared',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='question',
name='num_correct',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='test',
name='max_marks',
field=models.IntegerField(null=True),
),
]
......@@ -4,6 +4,7 @@ from __future__ import unicode_literals
from django.db import models
from django.core.validators import MinLengthValidator
# Create your models here.
class arfa_user(models.Model):
......@@ -85,18 +86,17 @@ class Question(models.Model):
difficulty_set = models.CharField(max_length=20)
difficulty_observed = models.CharField(max_length=20)
question_text = models.CharField(max_length=1000)
image_link = models.CharField(max_length=200)
num_appeared = models.IntegerField(default=0)
num_correct = models.IntegerField(default=0)
visibility = models.CharField(max_length=20)
ownership = models.CharField(max_length=20)
class QuestionImage(models.Model):
image = models.FileField(upload_to='QuestionImages/' )
question = models.ForeignKey('Question' , on_delete=models.CASCADE)
image_id=models.AutoField(primary_key=True)
image = models.FileField(upload_to='ARFA_app/static/ARFA_app/QuestionImages/' )
imageDesc = models.CharField(max_length=100)
orderNum = models.IntegerField(default=1)
q_ID=models.ForeignKey('Question',null=True)
class Takes(models.Model):
student = models.ForeignKey('Student',models.SET_NULL,blank=True,null=True)
......
......@@ -18,7 +18,7 @@
height: 2px;
background: #e0e0e0;
position: absolute;
width: 80%;
width: 60%;
margin: 0 auto;
left: 0;
right: 0;
......@@ -44,6 +44,7 @@ span.round-tab {
z-index: 2;
position: absolute;
left: 0;
padding-top: 15px;
text-align: center;
font-size: 25px;
}
......@@ -65,7 +66,7 @@ span.round-tab:hover {
}
.wizard .nav-tabs > li {
width: 25%;
width: 33%;
}
.wizard li:after {
......
......@@ -12,6 +12,8 @@
<script type="text/javascript">
$(document).ready(function () {
$('#images').hide();
$('#id_q_id').hide() ;
//Initialize tooltips
$('.nav-tabs > li a[title]').tooltip();
......@@ -51,6 +53,8 @@ function prevTab(elem) {
<script type="text/javascript">
var question_data = {} ;
var options_details = {};
var id = -1 ;
var hasimage=0;
function addOption()
{
var n = document.getElementById("optno");
......@@ -65,11 +69,8 @@ function prevTab(elem) {
var label = document.createElement("label");
label.innerHTML = "Option "+x+":";
que.appendChild(label);
// que.className = "row" ;
var r = document.createElement("div") ;
r.className = "row" ;
// r.innerHTML = "<tr><input class = \"form-control\" size=\"30\" type=\"text\"><input class = \"form-control\" size=\"30\" type=\"text\"></tr>" ;
var input = document.createElement("input");
var check = document.createElement("input");
var check_ans = document.createElement("label");
......@@ -91,12 +92,6 @@ function prevTab(elem) {
r.appendChild(check) ;
r.appendChild(check_ans) ;
que.appendChild(r);
// var text = que.value ;
// text = text + "<input className='form-control' type='text' size='20' placeholder='Enter an option'>" ;
// document.getElementById('options').innerHTML = text ;
container.appendChild(que);
}
function deleteLastOption()
......@@ -135,42 +130,20 @@ function prevTab(elem) {
}
console.log(options_details) ;
document.getElementById('l3').click() ;
}
function step3()
{
$('#images').hide();
document.getElementById('l4').click() ;
}
function post()
{
// var xhttp = new XMLHttpRequest();
Data = { 'question_data': question_data , 'options_details' : options_details } ;
console.log(Data) ;
// D = {
// client_response : Data,
// csrfmiddlewaretoken: '{{ csrf_token }}'
// } ;
// console.log(D) ;
// var csrftoken = Cookies.get('csrftoken');
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// alert(this.responseText);
// }
// };
// xhttp.open("POST", "add_question", true);
// xhttp.send();
// $.post({
// url: "add_question",
// data: Data,
// "success": function(result) {
// console.log(result);
// }
// }) ;
// console.log( document.getElementById("upload").value ) ;
// document.getElementById("imageForm").submit();
// console.log("still") ;
$.ajax({
url : "add_question",
type : "POST",
......@@ -178,10 +151,6 @@ function prevTab(elem) {
client_response : JSON.stringify(Data),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
// data : Data ,
// headers: {
// csrfmiddlewaretoken: '{{ csrf_token }}'
// },
success : function(p) {
q = JSON.parse(p);
console.log(q) ;
......@@ -190,7 +159,9 @@ function prevTab(elem) {
alert('Reason'+' : '+q.reason)
}
else{
alert("Successfully added to database") ;
alert("Successfully added question to database") ;
console.log("Return from post" + q['q_ID']) ;
id = q['q_ID'] ;
}
},
error : function(xhr,errmsg,err) {
......@@ -199,9 +170,50 @@ function prevTab(elem) {
});
}
function intend_to_add_img(){
$('#images').show();
hasimage=1;
}
function uploadImage()
{
var data = new FormData($('form').get(0));
console.log("Need to add to question " + id) ;
document.getElementById('id_q_id').value = id ;
$('#imageForm').submit(function(e){
e.preventDefault();
$form = $(this)
var formData = new FormData(this);
i = 0 ;
console.log("adding here...") ;
$.ajax({
url: "addimage",
type: 'POST',
data: formData ,
success: function (response) {
$('.error').remove();
console.log(response)
if(response.error){
$.each(response.errors, function(name, error){
error = '<small class="text-muted error">' + error + '</small>'
$form.find('[name=' + name + ']').after(error);
})
}
else{
alert(response.message)
i = 1 ;
window.location = "" ;
console.log("Added image also") ;
}
},
cache: false,
contentType: false,
processData: false
});
});
document.getElementById('imageForm').submit() ;
console.log("Image ADDED.. hopefully") ;
}
......@@ -248,13 +260,6 @@ Create Question
</a>
</li>
<li role="presentation" class="disabled">
<a href="#complete" data-toggle="tab" aria-controls="complete" role="tab" title="Complete" id = "l4">
<span class="round-tab">
<i class="glyphicon glyphicon-ok"></i>
</span>
</a>
</li>
</ul>
</div>
......@@ -302,34 +307,26 @@ Create Question
<h3>Step 3 - Add some pictures</h3>
<p> Drop images in the order you want to display</p>
<ul class="list-inline pull-right">
<li><button type="button" class="btn btn-default prev-step" onclick="document.getElementById('l2').click() ;">Previous</button></li>
<li><button type="button" class="btn btn-default prev-step" onclick="document.getElementById('l2').click() ; ">Previous</button></li>
<li><button type="button" class="btn btn-default next-step" onclick="document.getElementById('l4').click() ;">Skip</button></li>
<li><button align="left" type="button" class="btn btn-primary" id="addsubjectiveque" onclick="intend_to_add_img() ; post()" >Add an image</button></li>
<li><button type="button" class="btn btn-primary btn-info-full next-step" onclick="step3()">Save and continue</button></li>
</ul>
<!-- <form method="post" action="addimage" enctype="multipart/form-data" id="imageForm">
{% csrf_token %}
<label for="upload">
<span class="glyphicon glyphicon-folder-open" aria-hidden="true"></span>
<input type="file" id="upload" style="display:none">
</label><br>
<button onclick="post()" class="btn btn-primary btn-info-full" >Post the Question</button>
</form> -->
</div>
<div class="tab-pane" role="tabpanel" id="complete">
<h3>Complete</h3>
<p>You have successfully completed all steps. Here's the preview</p>
<ul class="list-inline pull-right">
<li><button type="button" class="btn btn-default prev-step">Previous</button></li>
<li><button type="button" class="btn btn-primary btn-info-full next-step" onclick="post()">Post </button></li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</form>
<div id = "images" >
<form method="POST" enctype="multipart/form-data" id="imageForm" novalidate="">
{% csrf_token %}
{{ form.as_p }}
<button onclick="uploadImage()" class="btn btn-primary btn-info-full" >Post the Question</button>
</form>
</div>
</div>
</section>
</div>
......
......@@ -20,6 +20,8 @@ Total Time :<b > {{total_time.hours}} {{total_time.minutes}} </b>
var countDownDate = new Date( {{ end_time }} );
countDownDate.setMonth(countDownDate.getMonth() - 1) ;
countDownDate.setMonth(countDownDate.getMonth() - 1) ;
countDownDate.setMonth(countDownDate.getMonth() - 1) ;
console.log(countDownDate) ;
// Update the count down every 1 second
var x = setInterval(function() {
......@@ -52,7 +54,6 @@ var x = setInterval(function() {
<form class="exam-form" method="POST" action="/arfa/result">
<p style="margin-right: 5%"> <b> Questions </b></p>
{% csrf_token %}
<!-- {{ data }} -->
<input name="testID" value="{{testID}}" type="hidden" >
{% for question, options in questions.items %}
<div class="row" style="margin-top: 10px; margin-bottom: 10px">
......@@ -62,7 +63,6 @@ var x = setInterval(function() {
{% endfor %}
</div>
{% endfor %}
<button type="submit" class="btn btn-login" style="float: right;">Submit</button>
</form>
</font>
......
......@@ -21,10 +21,10 @@ My Tests
<p>{{t.test_name}}</p>
</div>
<div style="float:right">
<form method="POST" action="arfa/loadStudentTest">
<form method="POST" action="loadStudentTest">
{% csrf_token %}
<input name="testID" value="{{t.test_ID}}" type="hidden">
<button >Load Test</button>
<button type="submit" class="btn btn-login float-right" style="margin-top: 10px ;margin-right: 40px">Load Test</button>
</form>
</div>
{% endfor %}
......
......@@ -115,7 +115,7 @@ def get_all_questions(request):
# args = {'username':'mathura'}
cursor = connection.cursor()
cursor.execute(''' SELECT s.subject,q."q_ID" as q_ID,q.question_text,q.topic,q.subtopic,q.source,
q.difficulty_set,q.image_link,q.visibility,q.ownership,o."option_Value" as option_details,
q.difficulty_set,q.visibility,q.ownership,o."option_Value" as option_details,
o."is_Answer"
FROM "ARFA_app_question" as q,
"ARFA_app_options" as o,"ARFA_app_subject" as s
......
......@@ -23,6 +23,8 @@ from django.db import connection
from django.db import IntegrityError
from django.db.models import F
from .forms import TestForm
from .forms import ImageFileUploadForm
from django.http import JsonResponse
import datetime
def login(request):
......@@ -228,6 +230,7 @@ def studentTestHome(request):
return HttpResponse("Not a student")
now = datetime.datetime.now()
print now
activeTests = Test.objects.filter(start_time__gte = now - F('expected_time_for_completion'),
start_time__lte = now)
practiceTests = Test.objects.filter(start_time__lte = now - F('expected_time_for_completion'))
......@@ -262,6 +265,7 @@ def loadStudentTest(request):
testName = Test.objects.values('test_name').get(pk=test_ID)
st = Test.objects.values('start_time').get(pk=test_ID)
start_time = st['start_time']
# start_time = start_time + datetime.timedelta(hours=5,minutes=30)
M = Test.objects.values('max_marks').get(pk=test_ID)
total_time = Test.objects.values('expected_time_for_completion').get(pk=test_ID)
end_time = start_time + total_time['expected_time_for_completion']
......@@ -354,7 +358,12 @@ def result(request):
def create_question(request):
return render(request,'ARFA_app/create_question.html',request.session.get('args',None))
form=ImageFileUploadForm
arg1={'form': form}
args=request.session.get('args',None)
if args !=None:
arg1.update(args)
return render(request,'ARFA_app/create_question.html', arg1)
def view_personal_question(request):
......@@ -366,7 +375,7 @@ def view_personal_question(request):
args={'username':request.session['username']}
cursor = connection.cursor()
cursor.execute(''' SELECT s.subject,q."q_ID" as q_ID,q.question_text,q.topic,q.subtopic,q.source,
q.difficulty_set,q.image_link,q.visibility,q.ownership,o."option_Value" as option_details,
q.difficulty_set,q.visibility,q.ownership,o."option_Value" as option_details,
o."is_Answer"
FROM "ARFA_app_question" as q,
"ARFA_app_options" as o,"ARFA_app_subject" as s
......@@ -524,7 +533,7 @@ def add_question(request):
option = models.Options(q_ID=question,option_Value=options[str(i)]['option_Value'],
is_Answer=options[str(i)]['is_Answer'],option_ID=options[str(i)]['id'])
option.save()
return HttpResponse(json.dumps({'status':'Success'}))
return HttpResponse(json.dumps({'status':'Success' , 'q_ID' : question.q_ID}))
except:
return HttpResponse(json.dumps({'status':'Failed','reason':'input/database error'}))
......@@ -554,10 +563,21 @@ def view_personal_Test(request):
def addimage(request):
files = request.FILES
print files
print "hello"
return HttpResponse("success")
if request.method == 'POST':
form = ImageFileUploadForm(request.POST, request.FILES)
print form.data
print form.data['q_id']
if form.is_valid():
p=form.save()
p.q_ID = models.Question(q_ID = form.data['q_id'])
p.save()
print p.image_id
return JsonResponse({'error': False, 'message': 'Uploaded Successfully','id':p.image_id})
else:
return JsonResponse({'error': True, 'errors': form.errors})
else:
return redirect('/arfa')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment