I am new in Django and doing my first project in it. I had made a form in my index.html file and that form took an image, and sent it to a predictImage function in views.py file. The predictImage function applied YOLO model on the image and returned the image with labels to the same index.html page.
This was working fine and I was getting the required results. After the submit button was clicked, I was getting redirected to index.html/predictImage where the results were being shown. (I had conditions added in my index.html to show the results)
Then, I decided to add a Users Model and made a Login page for me, user was required to login before he could upload the image. For this, I added sessions as well.
Now, I created a Photo model, to store every photo that every user uploads. All of this was successfully made but now, when I tried to do the same thing again, i.e., upload the image and submit it, it didn't work and it instead redirected me to index.html
I tried to debug this, and I found out that I was not even going to views.predictImage when I clicked the submit button. I don't seem to understand why this was happening, even though the only two new things that I added in my index.html were a hidden input file (to get the value of username from session) and a Logout Button to log out from the session.
Here is my models.py file (I added Photos Model later on)
from django.db import models
import datetime
import os
# Create your models here.
class Users(models.Model):
username = models.CharField('User Name', null=False, max_length = 50)
password = models.CharField('User Password', max_length=50)
def __str__(self):
return self.username
def filepath(request, filename):
old_filename = filename
timeNow = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
filename = "%s%s" % (timeNow, old_filename)
return os.path.join('uploads/', filename)
class Photo(models.Model):
id = models.AutoField(primary_key=True)
image = models.ImageField(upload_to=filepath)
uploader = models.ForeignKey(Users, default=None, on_delete=models.CASCADE)
This is my urls.py file, no changes were made to this.
from django.contrib import admin
from django.urls import path, re_path
from firstApp import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
re_path('admin/', admin.site.urls),
re_path('index', views.index, name = 'index'),
re_path('login', views.login, name='login'),
re_path('logout', views.logout, name='logout'),
re_path('', views.login, name="Login"),
# re_path('', views.login_submit, name='Home'),
re_path('predictImage', views.predictImage, name='predictImage'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is my views.py file
@csrf_exempt
def login(request):
if request.session.has_key('is_logged'):
return redirect('index')
if request.POST:
if 'user_name' not in request.POST:
return render(request, 'login.html')
username_entry = request.POST['user_name']
password = request.POST['password']
count = Users.objects.filter(username=username_entry).count()
if count > 0:
user_password = Users.objects.values('password').filter(username=username_entry)[0]
if password == user_password['password']:
request.session['is_logged'] = True
request.session['user_id'] = request.POST['user_name']
return redirect('index')
else:
messages.error(request, "Invalid Password")
return render(request, 'login.html')
else:
messages.error(request, "Invalid Username")
return render(request, 'login.html')
else:
return render(request, 'login.html')
def index(request):
if request.session.has_key('is_logged'):
current_user_id= request.session['user_id']
return render(request, 'index.html', {'ID':current_user_id})
else:
return redirect('login')
# context = {'a':1}
# return render(request, 'index.html', context)
def predictImage(request):
username = request.POST.get('username')
print("HEREEEE: ", username) # was using to check if this function is being called or not
# All the below lines are irrelevant to the bug
# They are only saving the Image file and calling YOLO Model Function to get Resultant image
# All of this was worknig before as well
fileObj = request.FILES['filePath']
fs = FileSystemStorage()
filePathName = fs.save(fileObj.name, fileObj)
filePathName = fs.url(filePathName)
testimage = '.'+filePathName
img_result, resultant_array, total_objects = detect_image(testimage)
cv2.imwrite("media/results/" + fileObj.name, img=img_result)
context = {'filePathName':"media/results/"+fileObj.name, 'predictedLabel': list(resultant_array.keys()), 'values': list(resultant_array.values()), 'total_objects': total_objects}
#context = {}
return render(request, 'index.html', context)
def logout(request):
del request.session['is_logged']
return redirect('login')
And this is my index.html file (only containing the portion where the form exists, I can share the rest of the file if needed but that isn't linked to this problem as far as I know)
{% csrf_token %}
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light m-5 mx-5 justify-content-center">
<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
<i class="fa fa-bars"></i>
</button>
<!-- Topbar Search -->
<div class=" mx-5 font-weight-bold">
Uplaod Image
</div>
<input class=" " type="file" name="filePath">
<input hidden class = "" name="username" value="{{ ID }}">
<input type="submit" class="btn-lg btn-success" value="Submit">
<!-- Topbar Navbar -->
</form>
<a class="btn-lg btn-danger" href={% url 'logout' %}> Logout</a>
</nav>
<!-- End of Topbar -->