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

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.

Related

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

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>

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"),
]

Log out when sending a form

I've created an app where you can make comment (which sends a form to a database and saves it) if you're login on only, but when I press the button "Create" instead of redirecting me to the page where it show all the comments, it logs me out and bring me back to the "log out" view (which is / )
the create Template:
{% extends 'base.html' %}
{% block content %}
<div class="create_comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
The Views of Create:
#login_required(login_url='/userprofile/login/')
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
form.save()
return redirect('/usercomments')
else:
form = forms.CreateComment()
return render(request,'usercomments/comments_create.html', {'form':form})
Log out view:
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/')
else:
pass
usercomments Urls.py:
from django.conf.urls import url
from . import views
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"),
]
userprofile urls.py:
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"),
]

Django Widget not Loading

I using Django with widgets to get some user input but I can't seem to get it to display even thou the code seems almost identical to examples online.
forms.py
from django import forms
class PickerIDForm(forms.Form):
pickeID = forms.NumberInput()
views.py
def get_id(request):
template = loader.get_template('metrics/lance1.html')
def get(self, request):
form = PickerIDForm()
return render(request, 'self.template', {'form': form})
context ={
}
return HttpResponse(template.render(context,request))
urls.py
from django.urls import path
from . import views
from . import mark_views
app_name = 'metrics'
urlpatterns = [
path('', views.index, name='index'),
path('test/', views.get_id, name='get_id'),
]
test.html
{% extends 'base.html' %}
{% block content %}
<p>User Input</p>
<form method = "post" >
{% csrf_token %}
{{form.as_p}}
<button type="submit"> Submit </button>
</form>
{% endblock %}
I'm never directly calling the get function as defined in views.py that to me seems to be a possible source of the input fields not showing up when I load up test.html
At what point do you link the disparate parts together? Because it seems I'm missing something.
You have defined the widget instead of the field in your form.
To fix that replace pickeID = forms.NumberInput() with pickeID = forms.IntegerField()
And also write your view like this:
def get_id(request):
form = PickerIDForm()
return render(request, 'metrics/lance1.html', {'form': form})

Django: Troubles uploadind and handling an image (CSRF token missing or incorrect)

I'm just trying to practice with Django. I tried to make a simple app which allows you to upload an image and return the pixelated version of it.
I have two views: one to show the form and one to handle the image and return the result.
The problem is that a 'Forbidden (403)' is raised instead of the result. Reason given for failure: CSRF token missing or incorrect.
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^result/$', views.pixelate, name='pixelate')
]
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from .forms import UploadImageForm
from .pixelate import pixelate_image
def index(request):
form = UploadImageForm()
return render_to_response('pixelate/index.html', {'form': form})
def pixelate(request):
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
response = HttpResponse(content_type='image/png')
response['Content-Disposition'] = 'filename="image.png"'
img = pixelate_image(request.FILES['image'])
response.write(img)
return response
pixelate.py
from PIL import Image
from io import BytesIO
def pixelate_image(img, pixelSize=9):
buffer = BytesIO()
p = Image(buffer)
image = p.open(img)
image = image.resize((image.size[0]/pixelSize, image.size[1]/pixelSize), Image.NEAREST)
image = image.resize((image.size[0]*pixelSize, image.size[1]*pixelSize), Image.NEAREST)
image.save()
final_image = buffer.getvalue()
buffer.close()
return final_image
forms.py
from django import forms
class UploadImageForm(forms.Form):
image = forms.ImageField()
index.html
<form action="{% url 'pixelate:pixelate' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
index.html
<form action="{% url 'pixelate:pixelate' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>