in Django show String on UI when file is ready - python

I would like do next,
When press on submit button, Django generate some file (it takes some time, about a minute)
I would like that next to submit button will appear another button to download (locally) this file when generating was finished.
screen shot:
image
HTML:
{% load bootstrap %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Create SWM Client Environment</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<h4 style="color: aliceblue;">Create SWM client environment</h4>
</nav>
<div style="padding: 20px;">
<form method="post">
{% csrf_token %}
<div class="form-group container w-25">
{{ form|bootstrap }}
</div>
<div class="container w-25">
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</body>
</html>
Forms:
class ContactForm(forms.Form):
swm_server = forms.CharField(
label='server',
widget=forms.TextInput(attrs={'placeholder': 'Server IP or Server DNS'}))
def clean(self):
cleaned_data = super(ContactForm, self).clean()
swm_server = cleaned_data.get('swm_server')
Views:
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})

Related

No Reverse Match at /showing file i just got the error of it

got an error while doing the code.I want to redirect by button to other page but it is showing me the error I have not done any more coding just the simple code that we use to do I had written it nothing more
NoReverseMatch at /showing
Reverse for '<WSGIRequest: GET '/showing'>' not found. '<WSGIRequest: GET '/showing'>' is not a valid view function or pattern name.
my code of views.py
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate,login
from user.forms import *
from django.contrib import messages
from user.models import *
from user.models import Orders
# Create your views here.
def home(request):
return render(request,'home.html')
def login(request):
if request.method=='POST':
username=request.POST['username']
password=request.POST['password']
userm=authenticate(user=username,passe=password)
if userm is not None:
login(request,userm)
messages.success(request,"You have login successfully...")
return redirect("home")
else:
messages.error(request,"Invalid Username or password...")
return redirect("login")
else:
return render(request,'base.html')
def register(request):
if request.method=='POST':
fm=Userregistration(request.POST)
if fm.is_valid():
fm.save()
else:
fm=Userregistration()
return render(request,'register.html',{'form':fm})
def Orderreg(request):
if request.method=='POST':
fm=Orderbook(request.POST)
if fm.is_valid():
pi=fm.cleaned_data['parcel_info']
pq=fm.cleaned_data['parcel_qty']
pw=fm.cleaned_data['parcel_weight']
um=fm.cleaned_data['unit_mass']
d=fm.cleaned_data['desti']
ord=Orders(parcel_info=pi,parcel_qty=pq,parcel_weight=pw,unit_mass=um,desti=d)
ord.save()
fm=Orderbook()
return redirect('service')
else:
fm=Orderbook()
u=Orders.objects.all()
return render(request,'service.html',{'form':fm,'us':u})
def contact(request):
return render(request,'contact.html')
def about(request):
return render(request,'about.html')
def show(request):
return redirect(request,'showing.html')
urls.py
from django.urls.conf import path
from user import views
urlpatterns = [
path('',views.home,name='home'),
path('home',views.home,name='home'),
path('login',views.login,name='login'),
path('register',views.register,name='register'),
path('about',views.about,name='about'),
path('service',views.Orderreg,name='service'),
path('contact',views.contact,name='contact'),
path('showing',views.show,name='show'),
]
my showing.html page is empty
code of service.html
{% extends 'base.html' %}
{% block body %}
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
</head>
<body>
<form action="" method="POST">
{% csrf_token %}
<section class="" style="background-color: #b6977d;">
<div class="container h-200">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-lg-12 col-xl-11">
<div class="card text-black my-5" style="border-radius: 35px;">
<div class="card-body p-md-5">
<div class="row justify-content-center">
<div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1">
<p class="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">Place order</p>
{{form.as_p}}
<input type="submit" class="btn btn-success btn-block" value="Order">
Show my Order
</div>
<div class="col-md-10 col-lg-6 col-xl-7 d-flex align-items-center order-1 order-lg-2">
<img src="/static/user-registration-removebg-preview.png" class="img-fluid" alt="Sample image">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'js/poper.js' %}"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
</body>
</html>
{% endblock body %}

How to update user password and store inside the database using django

I am trying to allow the admin to update the staff password, email address and username but the new password, email address and username is not updated into my database, did I do anything wrong in the code?
The images below is how the main page looks like:
This images show the next page which is the page that the staff password, username and email address will be updated:
views.py
def update(request, id):
context = {}
user = get_object_or_404(User, id=id)
if request.method == "POST":
user.save()
return redirect("/allstaff")
return render(request, 'allstaff.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
#path('', views.index, name='index'),
#path('login/', views.login_view, name='login_view'),
path('register/', views.register, name='register'),
path('adminpage/', views.admin, name='adminpage'),
path('customer/', views.customer, name='customer'),
path('logistic/', views.logistic, name='logistic'),
path('forget/', views.forget, name='forget'),
path('newblock/', views.newblock, name='newblock'),
path('quote/', views.quote, name='quote'),
path('profile/', views.profile, name='profile'),
path('adminprofile/', views.adminprofile, name='adminprofile'),
path('', views.login_user, name='login'),
path('home/', views.home, name='home'),
path('allstaff/', views.allstaff, name='allstaff'),
path('delete/<int:id>/', views.delete, name='delete'),
path('update/<int:id>/', views.update, name='update'),
path('logout/', views.logout_view, name='logout'),
path('register/', views.register_view, name='register'),
path('edit-register/', views.edit_register_view, name='edit_register'),
]
updatestaff.html
<!doctype html>
{% extends "home.html" %}
{% block content %}
{% load static %}
<html lang="en">
<head>
<style>
.button {
background-color: #38d39f;
border-color: #38d39f;
color: white;
padding: 10px 20px;
text-align: center;
display: inline-block;
margin: 4px 2px;
cursor: pointer;
border-radius: 16px;
width: 275px;
}
</style>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}">
<link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<!-- Style -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<title>Forget Password</title>
</head>
<body>
<div class="content">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6 contents">
<div class="row justify-content-center">
<div class="col-md-25">
<div class="form-block">
<div class="mb-3">
</div>
<h2>Password reset</h2>
<br/>
<form method="post">
{% csrf_token %}
<h4>Having trouble signing in?</h4>
<p>Follow the steps below to get started</p>
<label for="Username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="Email">Email:</label><br>
<input type="text" id="Email" name="Email"><br>
<label for="password">Password:</label><br>
<input type="text" id="password" name="password"><br>
<label for="con-pass">Confirm Password:</label><br>
<input type="text" id="con-pass" name="con-pass"><br><br>
<button class="button" >Submit</button>
<br>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'js/popper.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/main.js' %}"></script>
</body>
</html>
{% endblock %}
First of all, there is a dedicated type for password input in HTML you should consider using for storing passwords in post reqeusts.
<input type="password">
To your question,
In order to update user password, you should use user.set_password method.
Check this documentation here.
The link above also shows you how to change other properties of a user.
In your views.py file, you are not accepting requested data from the form.
So, do this. Here's how:
def update(request, id):
context = {}
user = get_object_or_404(User, id=id)
if request.method == "POST":
# getting form input values from your HTML Form.
username = request.POST.get('username')
email = request.POST.get('Email')
password = request.POST.get('password')
user.username = username
user.email = email
user.set_password(password)
user.save()
return redirect("/allstaff")
return render(request, 'allstaff.html', context)
I hope this is your answer.

Users are not highlighted when they presses the like button and also doesn't show the count of likes ..in django. Can You suggest me any solution

registration and login page is working properly but mine like button is not working it doesn't highlight users who presses like button and also doesn't show the count of like .. 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, redirect
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.
#login_required
def likes(request, pk):
post = get_object_or_404(Post, id=pk)
post.likes.add(request.user)
return HttpResponseRedirect(reverse('datasecurity:datasecurity', args=str(pk)))
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
def __init__(self, *args, **kwargs):
stuff = get_object_or_404(Post, id = self.kwargs['pk'])
total_likes = stuff.total_likes()
context['total_likes'] = total_likes
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)
2.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/(?P<pk>\d+)/', views.likes, name = "likes"),
]
Models.py
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
sno=models.AutoField(primary_key=True)
title=models.CharField(max_length=255)
author=models.CharField(max_length=14)
slug=models.CharField(max_length=130)
timeStamp=models.DateTimeField(blank=True)
content=RichTextField(blank=True, null=True)
img = models.ImageField(blank=True, null=True, upload_to="dataimage/")
likes = models.ManyToManyField(User, related_name='likes')
#property
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + " by " + self.author
data.html
<html lang="en" dir="ltr">
<head>
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900"
rel="stylesheet"
/>
<meta charset="utf-8">
<title></title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/datasecurity.css' %}">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?
family=Bebas+Neue&family=PT+Sans&display=swap" rel="stylesheet">
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/cover/">
<script async defer crossorigin="anonymous"
src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v9.0"
nonce="noEcH88O"></script>
<script async defer crossorigin="anonymous"
src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v3.2"></script>
</head>
<body>
<!-- End header -->
<div id="page-wraper">
<!-- Sidebar Menu -->
<div class="responsive-nav">
<div class="top-navbar">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<marquee><ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="{% url 'careforallapp:base'
%}">Home</a></li>
</ul></marquee>
</div>
</div>
</nav>
</div>
<section class="section about-me" data-section="section1">
<div class="container">
<div class="section-heading">
<h2>Welcome to Data Security</h2>
{% 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" class="btn"> Like </button> - {{
total_likes }} likes
</form><br><br>
<div class="white-button">
Read More
</div><br>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{% endfor %}
There is no error when I debug the code .. may be it is logical error .. I really don't know .. can someone help me to find out the error
Thank you

How can I connect the Submit button to my .py file?

The goal of my program is to place the first and last name into my database upon it being entered and Submit button clicked by the user so that when I manually check in Terminal what’s in my database, I can see what the user has entered and submitted. I need to some how connect my Submit button to my views.py file so that it can go through , sort like an onClick() but this time, to go a .py file. (correct me if I’m wrong with this train of thought).
How would I go about making this happen?
Here's my views.py file:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Person
def index(request):
if request.method == 'POST':
first_name = request.POST.get('firstName')
last_name = request.POST.get('lastName')
if first_name and last_name:
user = Person.objects.create(firstName=first_name, lastName=last_name)
user.save()
return render(request, 'music/index.html')
def detail(request, user_id): # Testing out page 2
return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
</form>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</body>
</html>
your form should be declared as:
<form method="POST">
and your <button type="submit"> should be inside the <form></form>.
As the same view deals with the GET and POST methods, you should remove the action="#" attribute, that way action will point to the same view.

error when page is refreshed in django

I am learning to create a website using django. I have a homepage through which user can select city. The next page shows the list of hotels.It works properly,but when page is refreshed it gives me error
This is my html file for list page.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
<script type="text/javascript" src="../js/typeahead/0.11.1/typeahead.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
{% load static %}
<script src="/static/typeahead.js "></script>
</head>
<body>
<div >
<div style="float:left; background-color:#d9d9d9;margin-top:100px;width:30%;height:800px;">
<h2 style="text-align:center;">Filters</h2>
<div style="width:95%; margin-left: 10px; " >
<form method="post" data-ajax="false" action="{% url 'list' %}">
{% csrf_token %}
<div data-role="rangeslider" data-mini="true" style="width:100%">
<label for="range-1a">price:</label>
<input name="range-1a" id="range-1a" min="0" max="100" value="0" type="range">
<label for="range-1b">Rangeslider:</label>
<input name="range-1b" id="range-1b" min="0" max="100" value="100" type="range">
</div>
<input type="submit" value="Submit">
</form>
</div>
</div>
<div style=" float:right;margin-right:30px;margin-top:100px;width:60%;height:80%">
{% for hotel in city_list %}
{% load static %}
<div class="col-md-4" style="width:45%;border:0;position:relative;">
<div class="thumbnail" style="height:300px; background-color:black;border:0;border-radius:0;position:relative;box-shadow:0;" >
<a href="/w3images/lights.jpg" data-ajax="false">
<img src="{% static hotel.photo.url %}" style="border:0;height:85%;width:100%;" >
<div class="caption">
<p style="color:white;">Name</p>
</div>
</a>
</div>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
This is my views.py
def homepage(request):
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
def wholelist(request):
hotelvar=request.POST.get('service_type')
if hotelvar=='Hotels':
city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc'))
if not city_list:
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
pricemin=200
pricemax=800
context={'pmin':pricemin,'pmax':pricemax,'city_list':city_list}
return render(request, 'polls/list.html',context)
i get the following error when refreshed
UnboundLocalError at /polls/wholelist/
local variable city_list referenced before assignment
city_list is being passed from the homepage, but when page is reloaded it not being passed. Is there a way to pass it when page is refreshed?
when hotelvar not equal to 'Hotels', variable city_list is not set
def wholelist(request):
hotelvar=request.POST.get('service_type')
city_list = None
if hotelvar=='Hotels':
city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc'))
if not city_list:
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
pricemin=200
pricemax=800
context={'pmin':pricemin,'pmax':pricemax,'city_list':city_list}
return render(request, 'polls/list.html',context)

Categories

Resources