How do I use the onsubmit function in Django to switch pages? - html

I'm trying to create a page that, once a form submit button is clicked, will redirect to the home page. I'm using the 'onsubmit' function for that, but it isn't working.
HTML code
{% extends 'base.html' %}{% load static %}
{% block head %}
<link rel="stylesheet" href="{% static 'login.css' %}" />
<script src="{% static 'login.js'}"></script>
{% endblock %}
<!-- page code -->
{% block pagename %}
<p>SIGN IN</p>
{% endblock %}
{% block content %}
<div class="contentContainer">
<p>Please enter your competition ID:</p>
<form class="form" onsubmit="pageSwitch()">
<input type="text" id="entry" placeholder="ID ENTRY HERE...">
<input type="submit" id="entrySubmit" value="SUBMIT">
</form>
</div>
{% endblock %}
JS Code
function pageSwitch(){
window.location.replace("{% url 'home' %}");
}
urls.py Code
from django.contrib import admin
from django.urls import path
from files import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('test/', views.test, name='test'),
path('', views.login, name='login'),
path('home/', views.home, name='home'),
path('leaderboard/', views.lboard, name='lboard'),
path('scorecard/', views.score, name='score'),
path('submit/', views.submit, name='submit'),
path('base/', views.base, name='base'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
'views.py' Code
from django.shortcuts import render
# Create your views here.
def test(request):
return render(request, 'test.html')
def base(request):
return render(request, 'base.html')
def login(request):
return render(request, 'login.html')
def home(request):
return render(request, 'home.html')
def lboard(request):
return render(request, 'leaderboard.html')
def score(request):
return render(request, 'score.html')
def submit(request):
return render(request, 'submit.html')
def base(request):
return render(request, 'base.html')
I'm not really sure what else to try, I've been messing around with either using anchors and 'onclick' instead, but that hasn't worked either, so I'm a bit stuck. This is my first time using Django, so all of the other explanations I've found have been a bit too complex for me to understand, including things that aren't in my code that have thrown me off a bit.

When using a form's onsubmit event to call a function and redirect to another page, it's important to prevent the default form submission behavior, which can interfere with the redirect. One solution is to add an event parameter to the function, and then use event.preventDefault() to stop the form submission. For example:
<form onsubmit="myFunction(event)">
...
</form>
<script>
function myFunction(event) {
event.preventDefault();
window.location.replace('https://example.com');
}
</script>
This way, the preventDefault() method will be called before the form is submitted, ensuring that the redirect will happen immediately.

Related

Input fields are makred always RED in Djano UserRegistrationForm

I am creating a User authentication system in Django. The first page I set is to Register a new user. For that, my views.py is below:
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from .forms import UserRegisterForm
from django.contrib import messages # To give an alert when a valid data is received
# Create your views here.
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created!')
return redirect('login')
else:
form = UserRegisterForm(request.POST)
return render(request, 'Agent/register.html', {'form': form})
and the html file is given below:
register.html
{% extends "client_management_system/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted ">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
and the URL pattern for register page is given below:
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from Agent import views as agent_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('client_management_system.urls')),
path('register/', agent_views.register, name='register'),
]
But my Register fields are always RED as shown below:
Does anyone has an idea how to make them normal? and make the field RED when it is left empty and Sign Up button is pressed.
In the else: clause you should initialize a new form, not with request.POST data (which you don't have)
else:
form = UserRegisterForm()
(moreover the else is unnecessary there)

Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/<int:pk>'] Like buttton error in django

registration and login page is working properly but mine like button is not working .. I don't know why...
Can somebody help me to solve this issue …
it will be great help
please help
Thank you!
views.py`
from django.shortcuts import render, get_object_or_404
from datasecurity.models import Post
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login required
# Create your views here.
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
return render(request, 'datasecurity/data.html',context=context)
def blogHome(request, slug):
post=Post.objects.filter(slug=slug).first()
context={"post":post}
return render(request, "datasecurity/blogHome.html", context)
#login_required
def likes(request, pk):
post=get_object_or_404(Post, id=request.POST.get('post_id'))
post.likes.add(request.user)
return HttpResponseRedirect(reverse('datasecurity:blogHome', args=str(pk)))
urls.py
from django.conf.urls import url
from . import views
app_name = 'datasecurity'
urlpatterns = [
url(r'^$', views.datasecurity, name="datasecurity"),
url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'),
url(r'^likes/<int:pk>', views.likes, name = "likes"),
]
data.html
{% extends 'careforallapp/navbar.html' %}
{% block body_block %}
{% load static %}
Welcome to Data Security
{% for post in allPosts %}
<div class="line-dec"></div>
<span
>This is a Bootstrap v4.2.1 CSS Template for you. Edit and use
this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.</span
>
</div>
<div class="left-image-post">
<div class="row">
<div class="col-md-6">
<div class="left-image">
{% if post.img %}
<img src="{{ post.img.url }}" alt="" />
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="right-text">
<h4>{{post.title}}</h4>
<h6>Article by {{post.author}}</h6>
<h2>{{post.datetime}}</h2>
<p>
{{post.content|safe | truncatechars:280}}
</p>
<from action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
{% csrf_token %}
<button type="submit" name="post_id" value = "{{ post_id }}" class="btn"> Like
</button>
</form>
<div class="white-button">
Read More
</div><br>
</div>
{% endfor %}
error msg <from action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/int:pk']
this msg was highlighted when I debug the the code. So can someone tell me please what i missed in my code...
Thank You!
You are not taking the pk argument from view. Change your view to:
#login_required
def likes(request, pk):
post=get_object_or_404(Post, id=pk)
and the url to:
url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"),
notice the used regular expression in the url.

Django filter form not displaying

I'm using django filters but I can't get the filter form to actually render on the page, only the submit button is showing. If I inspect the element, nothing else seems to be being sent to the template. THere is no error message or anything, I don't know where to go from here, how do I get the actual form to show,
filter.py
from django.contrib.auth.models import User
import django_filters
from .models import Project
class ProjectFilter(django_filters.FilterSet):
class Meta:
model = Project
fields = ['user', 'title']
views.py:
def search_view(request):
project_list = Project.objects.all()
project_filter = ProjectFilter(request.GET, queryset=(project_list)
return render(request, 'project_portal/filter.html', {'filter': project_filter})
urls.py:
path('search/', search_view, name='search'),
html:
{% load crispy_forms_tags %}
<!DOCTYPE html>
<div>
<form method="get">
{{ filter.form.as_p }}
<input type="submit"/>
</form>
{% for user in filter.qs %}
{{ user.title }}
{% endfor %}
</div
i think your error ...
==> project_filter = ProjectFilter(request.GET, queryset=(project_list)
must be :
project_filter = ProjectFilter(request.GET, queryset=project_list)

NoReverseMatch at / Reverse for 'store' not found. 'store' is not a valid view function or pattern name

I am trying to make a simple home page which will have a link to another page named store.html.
views.py
from django.shortcuts import render, get_object_or_404, redirect
def home(request):
return render(request, 'store/home.html')
def store(request):
return render(request, 'store/store.html')
urls.py
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.home, name ='home'),
path('store/', views.store, name = 'store'),
]
home.html
Here I have put href="{% url 'home' %}" but I found reverse not match error and other than everything is looking good.
{% extends './base.html' %}
{% block content %}
<body>
<h1>home</h1>
<a class = 'btn' href="{% url 'store' %}">store</a>
</body>
{% endblock %}
Please help me how to use fix this to make the link so that when clicking on that it will open another page. I am new to django and using version 2.1.7.
As per your error suggests, store is not a valid view function, because you have added app_name in your urls.py,
<body>
<h1>home</h1>
<a class = 'btn' href="{% url 'store:store' %}">store</a>
</body>
Url will always need app_name when you have mentioned it in the urlpatterns. To learn more chack Django Namespace

Django unable to render form in table format

I have a django formset and I am trying to render it row by row. Instead, the form is being render column by column (like a vertical form instead of horizontal). I am using django's form.as_table but it is still not rendering correctly. Any ideads?
form.html:
<form id="formset" class="original" action="{% url 'inventory:requests' inventory.id %}" method="post">{% csrf_token %}
<!-- Add New Row -->
{{formset.management_form}}
{% for form in formset.forms %}
{{ form.non_field_errors }}
{{ form.errors}}
<div class='item'>
<table>{{ form.as_table }}</table>
<p style=""><a class="delete" href="#">Delete</a></p>
</div>
{% endfor %}
<p><a id="add" href="#">Add another item</a></p>
<input type="submit" name="submit" value="Request Blocks" id="submitButton">
</form>
The form's as_table method just uses <tr></td> instead of <div> to render your form - but it will be rendered visually the same way.
To easily get control over your form, consider using django-crispy-forms. Here is is how you would make your form render horizontally:
In your forms.py, add this (in addition to your normal code):
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class ExampleFormSetHelper(FormHelper):
def __init__(self, *args, **kwargs):
super(ExampleFormSetHelper, self).__init__(*args, **kwargs)
self.form_method = 'post'
self.render_required_fields = True
self.template = 'bootstrap/table_inline_formset.html'
self.add_input(Submit("submit", "Save"))
Next, in your views.py:
from .forms import ExampleFormsetHelper, YourFormSet
def formset_view(request):
formset = YourFormSet()
helper = ExampleFormSetHelper()
return render(request, 'template.html',
{'formset': formset, 'helper': helper})
Finally, in your template, all you need is:
{% load crispy_forms_tags %}
{% crispy formset helper %}
For more details, the documentation has the specifics.