Django Using Default Form & File Submission with Drag and Drop functionality - django

I have a django application that allow user to upload their image and then another dialog opens to collect user data related to them. After the dialog form has been submitted, I have added the javascript eventlistener to successfully submit the form with data and it redirects to the form's action attribute.
I wanna implement the same functionality, if user drop their image in the browser then dialog opens to collect user data, then do the same as above and redirect to the form's action attribute.
How can I achieve it?
Here is my code
#--urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('success/', views.success_function, name='success page'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#--views.py
def index(request):
form = userForm()
return render(request, 'polls/hello_world.html', {'form': form})
def success_function(request):
if request.method == 'POST':
form = userForm(request.POST, request.FILES)
user_files = request.FILES.getlist('django_image_field')
if form.is_valid():
images_data = []
for eachfile in user_files:
#handle_uploaded_file(eachfile)
file_path = file_upload(eachfile)
img_details = {'file_path': file_path, 'file_name': eachfile.name}
images_data.append(img_details)
return render(request, 'polls/success.html', {'data': images_data})
else:
print(form.errors)
return HttpResponse("Not valid form")
else:
return HttpResponse("Not a valid method")
--under forms.py
class NameForm(forms.Form):
your_name = forms.CharField(required=False, label='Your name', max_length=100)
django_image_field = forms.ImageField(required=True,
label="",
widget=forms.ClearableFileInput(attrs={
'multiple': True,
'id':'file-input'
}))
--#inside index
<form enctype="multipart/form-data" action="{% url 'success' %}" id="myform" method="POST">
{% csrf_token %}
{{ form.django_image_field }}
<dialog id="user_dialog">
<form method="dialog" id="more_details">
</h6>
<p>Enter Name: </p>
{{ form.your_name.label_tag }}
{{ form.your_name }}
<button id="submit_btn" type="submit">Submit</button>
</form>
</dialog>
</form>

Related

My view does not redirect after processing a form. Used HttpResponseRedirect

I am new to Django and I am trying to use custom forms. My problem is that my form does not do anything after I submit it.
I am following the documentation here:https://docs.djangoproject.com/en/4.1/topics/forms/
I have the following files:
forms.py:
from django import forms
class TestForm(forms.Form):
text = forms.CharField(label='Text', max_length=50)
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
path('test', views.test_view, name='test')
]
views.py:
def index(request):
return render(request, 'index.html', context)
def test_view(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('home:index')
else:
form = TestForm()
return render(request, 'test.html', context={'form':form, 'text':'No text yet.',})
template: test.html
<div>
<form action="home:club-invite" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<hr>
<p>Your text: {{ text }}</p>
</div>
The problem is that the Submit button does nothing. I was expecting a redirect to the index page. But here is no error, no subsequent http request or redirect, nothing...
Am I missing something here?
PS:I also tried return redirect('home:index'). Still no success.

request.user.is_authenticated does not work after changing urls

So my code looked like this at first:
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Information
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .forms import MyForm
# rooms = [
# {'id': 1, 'name': 'Lets learn python!'},
# {'id': 2, 'name': 'Design with me'},
# {'id': 3, 'name': 'Frontend developers'},
# ]
def home(request):
q = request.GET.get('q') if request.GET.get('q') !=None else ''
information_search = Information.objects.filter(
Q(host__icontains=q) |
Q(hostname__icontains=q) |
Q(port__icontains=q) |
Q(platform__icontains=q) |
Q(username__icontains=q) |
Q(password__icontains=q) |
Q(groups__icontains=q)
)
sort_info = []
informations = Information.objects.all()
for i in informations:
if i.groups not in sort_info:
device_group = i.groups
sort_info.append(device_group)
information_count=information_search.count()
context = {'informations':informations, 'information_search':information_search, 'information_count':information_count, 'sort_info':sort_info}
return render(request, 'polls/home.html', context)
def view_data(request, pk):
information = Information.objects.get(id=pk)
context = {'information':information}
return render(request, 'polls/view_data.html', context)
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request, 'User does not exist')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, "Username or password does not exist")
context = {}
return render(request, 'polls/login_register.html', context)
def logoutUser(request):
logout(request)
return redirect('home')
def edit_data(request, pk):
information = Information.objects.get(id=pk)
form = MyForm(instance=information)
if request.method == 'POST':
form = MyForm(request.POST, instance=information)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request, 'polls/room_form.html', context)
def delete_data(request, pk):
information = Information.objects.get(id=pk)
if request.method == 'POST':
information.delete()
return redirect('home')
return render(request, 'polls/delete.html', {'obj': information})
def my_form(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = MyForm()
return render(request, 'polls/room_form.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.loginPage, name="login"),
path('logout/', views.logoutUser, name="logout"),
path('', views.home, name='home'),
path('view_data/<str:pk>/', views.view_data, name = "view_data"),
path('edit_data/<str:pk>/', views.edit_data, name = "edit_data"),
path('host/', views.my_form, name='my_form'),
path('delete/<str:pk>/', views.delete_data, name='delete_data')
]
login_register.html
{% extends 'main.html' %}
{% block content %}
<div>
<form method="POST" action="">
{% csrf_token %}
<label>Username:</label>
<input type="text" name="username" placeholder="Enter Username" />
<label>Password:</label>
<input type="password" name="password" placeholder="Enter Password">
<input type="submit" value="login">
</form>
</div>
{% endblock content %}
I wanted to change the authentication system so that the home view is only returned if the user is logged in. I was able to show home view after the user logs in by making small changes to urls.py and login_register.html as follows:
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Information
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .forms import MyForm
# rooms = [
# {'id': 1, 'name': 'Lets learn python!'},
# {'id': 2, 'name': 'Design with me'},
# {'id': 3, 'name': 'Frontend developers'},
# ]
def home(request):
q = request.GET.get('q') if request.GET.get('q') !=None else ''
information_search = Information.objects.filter(
Q(host__icontains=q) |
Q(hostname__icontains=q) |
Q(port__icontains=q) |
Q(platform__icontains=q) |
Q(username__icontains=q) |
Q(password__icontains=q) |
Q(groups__icontains=q)
)
sort_info = []
informations = Information.objects.all()
for i in informations:
if i.groups not in sort_info:
device_group = i.groups
sort_info.append(device_group)
information_count=information_search.count()
context = {'informations':informations, 'information_search':information_search, 'information_count':information_count, 'sort_info':sort_info}
return render(request, 'polls/home.html', context)
def view_data(request, pk):
information = Information.objects.get(id=pk)
context = {'information':information}
return render(request, 'polls/view_data.html', context)
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request, 'User does not exist')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, "Username or password does not exist")
context = {}
return render(request, 'polls/login_register.html', context)
def logoutUser(request):
logout(request)
return redirect('home')
def edit_data(request, pk):
information = Information.objects.get(id=pk)
form = MyForm(instance=information)
if request.method == 'POST':
form = MyForm(request.POST, instance=information)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request, 'polls/room_form.html', context)
def delete_data(request, pk):
information = Information.objects.get(id=pk)
if request.method == 'POST':
information.delete()
return redirect('home')
return render(request, 'polls/delete.html', {'obj': information})
def my_form(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = MyForm()
return render(request, 'polls/room_form.html', {'form': form})
login_register.html
{% extends 'main.html' %}
{% block content %}
<div>
<form method="POST" action="home/">
{% csrf_token %}
<label>Username:</label>
<input type="text" name="username" placeholder="Enter Username" />
<label>Password:</label>
<input type="password" name="password" placeholder="Enter Password">
<input type="submit" value="login">
</form>
</div>
{% endblock content %}
However the bar at navbar.html which shows logout option if the user is logged in stops working..
navbar.html
<a href="/polls">
<h1>LOGO</h1>
</a>
<form method="GET" action="{% url 'home' %}">
<input type="text" name="q" placeholder="Search Devices...">
</form>
{% if request.user.is_authenticated %}
Logout
{% else %}
Login
{% endif %}
<hr>
navbar is included in main.html as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>StudyBud</title>
</head>
<body>
{% include 'navbar.html' %}
{% block content %}
{% endblock %}
</body>
</html>
and main.html is extended by other templates. Here main.html and navbar.html are stored in the templates folder of the root directory while other templates are in the 'polls' app folder.
If it helps here are my other files.
models.py
from django.db import models
from django.contrib.auth.models import User
class Information(models.Model):
host = models.CharField(max_length=200, null=True, blank=False)
hostname = models.CharField(max_length=200, null=True, blank=False)
port = models.IntegerField()
platform = models.CharField(max_length=200, null=True, blank=False)
username = models.CharField(max_length=200, null=True, blank=False)
password = models.CharField(max_length=200, null=True, blank=False)
groups = models.CharField(max_length=200, null=True, blank=False)
def __str__(self):
return self.host
Here is home.html which extends main.html and is supposed to show the logout bar.
{% extends 'main.html' %}
{% block content %}
<h2>Inventory Management</h2>
<style>
.home-container{
display: grid;
grid-template-columns: 1fr 3fr;
}
</style>
<div class="home-container">
<div>
<h3>Browse Groups</h3>
<hr>
{% for i in sort_info %}
<div>
{{i}}
<br><br>
</div>
{% endfor %}
</div>
<div>
<h5>{{information_count}} devices registered</h5>
<hr>
Add Device
<hr>
{% for information in information_search %}
<span>#{{information.host}}</span>
<h3> view </h3>
Edit
Delete
<hr>
{% endfor %}
</div>
</div>
{% endblock content %}
</div>
Any insight please? I am a beginner and I was trying to make changes and implement my own features in the code i followed through a tutorial.

My edit function creates a new page instead of editing the previous page views.py

I edited my views.py but I am having a bug, each time I edit the previous entry, it creates a new entry with what i edited instead of editing that copy. I've tried to retouch the possible errors. please help
VIEWS.PY
class AddPageForm(forms.Form):
title = forms.CharField(max_length=20)
content = forms.CharField(widget=forms.Textarea(
attrs={
"class": "form-control",
"placeholder": "Tell us more!"
})
def edit_page(request, title):
if request.method == "GET":
content = util.get_entry(title)
form = AddPageForm(initial={"content": title})
return render(request, "encyclopedia/editpage.html",
{"form": form})
else:
form = AddPageForm(request.POST)
if form.is_valid():
content = form.cleaned_data['content']
util.save_entry(title, content)
return redirect('encyclopedia:entrypage', title)
return render(request, 'encyclopedia/editpage.html', {'form': form})
EDIT PAGE
{% block body %}
<h1>Edit {{ title }}</h1>
<form action="" method="post">
{% csrf_token %}
{% form %}
<input type="submit" value="Submit" class="btn btn-secondary">
</form>
ENTRY PAGE
{% block body %}
{{ content|safe }}
Update
{% endblock %}
URLS.PY
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.entry_page, name="entrypage"),
path("search", views.search, name="search"),
path("add_page", views.add_page, name="addpage"),
path("edit_page/<str:title>", views.edit_page, name="editpage")
]
UTILS.PY
def save_entry(title, content):
"""
Saves an encyclopedia entry, given its title and Markdown
content. If an existing entry with the same title already exists,
it is replaced.
"""
filename = f"entries/{title}.md"
if default_storage.exists(filename):
default_storage.delete(filename)
default_storage.save(filename, ContentFile(content))
def get_entry(title):
"""
Retrieves an encyclopedia entry by its title. If no such
entry exists, the function returns None.
"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None
I am using forms.Form because this is an assignment and the requirement states that we should use that instead of forms.Model

Input redirect me on the wrong view

Hello i'm a beginner at django and i got this problem. (i don't know if the code i put is enough)
When i decide to create a new comment, if i click on "create" instead of redirect me to "usercomments" and send the data to the database, it log me out and send me where log out is supposed to send me. i can't find a similar problem, i don't even know what kind of error it is, help
Thanks :)
Templates of "create comment" :
<div class="create-comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'usercomments:create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
Urls.py :
from django.conf.urls import url
from . import views
app_name = 'usercomments'
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
Views of create comment :
#login_required(login_url="/userprofile/login/")
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
# save article to db
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('usercomments:list')
else:
form = forms.CreateComment()
return render(request, 'usercomments/comments_create.html', { 'form': form })
Views of log out :
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/') <--- Where i get redirected when i press "create"
else:
pass
Urls of logout :
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

What is wrong with my CSV import code in Django?

I have overridden my admin change_list.html
{% extends "admin/change_list.html" %}
{% block object-tools-items %}
<li>
Import CSV
</li>
{{ block.super }}
{% endblock %}
When I click this Import CSV link, I would like to import CSV and save to my model.
App's name Auction. Objects of Auction:
forms.py
from django import forms
import csv
from auction.models import AuctionGroup, AuctionHouse, AuctionList
class DataInput(forms.Form):
file = forms.FileField()
def save(self):
records = csv.reader(self.cleaned_data["file"])
for line in records:
house = AuctionHouse()
house.house_name = line[0]
house.auction_type = line[1]
house.auction_day = line[2]
house.volume = line[3]
house.aleado_id = line[4]
house.aleado_photo_number = line[5]
house.house_region = line[6]
house.save()
views.py
def csv_import(request):
if request.method == "POST":
form = DataInput(request.POST, request.FILES)
if form.is_valid():
form.save()
success = True
context = {"form": form, "success": success}
return render_to_response("auction/importcsv.html", context,
context_instance=RequestContext(request))
else:
form = DataInput()
context = {"form": form}
return render_to_response("auction/importcsv.html", context,
context_instance=RequestContext(request))
urls.py
urlpatterns = patterns('',
url(r'/importcsv/$', views.csv_import, name='importcsv'),
)
project/urls.py
urlpatterns = patterns('',
url(r'^auction/', include('auction.urls')),
url(r'^admin/', include(admin.site.urls)),
)
importcsv.html
<!DOCTYPE html>
<html>
<form enctype="multipart/form-data" method="post" action=".">
{{ form }}
</form>
</html>
But it does not work. Please, help. Regards
Use the {% url %} tag in the link code:
Import CSV
If you want to use single template for multiple models then change_list.html has the cl.opts context variable which is a Model._meta of the current model.
So you can pass the app_label and model_name to your importcsv() view:
<a href="{% url 'importcsv' cl.opts.app_label cl.opts.model_name %}"
class="grp-state-focus addlink">Import CSV</a>
Change your urls.py:
urlpatterns = patterns('',
url(r'/importcsv/(\w+)/(\w+)/$', views.csv_import, name='importcsv'),
)
And the signature of the view function:
def csv_import(request, app_label, model_name):
...