How to resolve Django model form does not saving - html

Hello I am trying to implement a Django model form when I try to now submit the form it does not save my data can I please get help I do not know where I can be going wrong with this implementation:
Code Below: models.py
class Videos(models.Model):
lecturer = models.CharField(max_length=100, blank=False, null=False)
module = models.CharField(max_length=100, blank=False, null=False)
video = models.FileField(upload_to='lectures/')
date = models.DateField(default=datetime.datetime.now())
Code Below: form.py
class LectureVideos(forms.ModelForm):
class Meta:
model= Videos
fields = '__all__'
Code Below:view.py
def LectureVideoForm(request):
form = LectureVideos()
if form.is_valid():
form.save()
return redirect('upload-success')
return render(request, 'forms.html', {'form':form})
Code Below:forms.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Upload Video">
</form>
</body>
</html>

You never passed the data to the form. In case of a POST request, you pass the request.POST (and request.FILES) to the form:
def LectureVideoForm(request):
if request.method == 'POST':
form = LectureVideos(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('upload-success')
else:
form = LectureVideos()
return render(request, 'forms.html', {'form':form})
Note: Functions are normally written in snake_case, not PerlCase, therefore it is
advisable to rename your function to lecture_video_form, not LectureVideoForm.

Related

Unable to populate select option from database in Django

I am a beginner to Django and unable to populate the items from my database table to <option></option>.
From models.py:
from django.db import models
from django.db.models.fields.related import ForeignKey
# Create your models here.
class Tbl_Category(models.Model):
cat_Id = models.AutoField(primary_key=True)
cat_Name = models.CharField(max_length=20, unique=True)
# def __str__(self):
# return [self.cat_Id, self.cat_Name]
class Tbl_Item(models.Model):
item_Id = models.AutoField(primary_key=True)
item_Name = models.CharField(max_length=30, unique=True)
cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE)
item_Price = models.IntegerField()
From views.py:
from django.shortcuts import render
from orderapp.models import Tbl_Item
# Create your views here.
def displayMain(request):
return render(request,'index.html')
def ct(request):
options = Tbl_Item.objects.filter(cat_Idf=1)
context = {'alloptions' : options}
return render(request, 'index.html', context)
From index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'css.css' %}">
<title>DATA COLLECTION</title>
</head>
<body>
<div class="container">
<div class="order-screen">
<div class="element">
<label for="coffee-tea">Coffee-Tea</label>
<select name="coffee-tea" id="coffee-tea">
{% for opt in alloptions %}
<option value="{{opt.item_Id}}">{{opt.item_Name}}</option>
{% endfor %}
</select>
</div>
<div class="cart-screen">CART-SCREEN</div>
</div>
</body>
</html>
I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you.
If I understand you question correctly you want to have a dropdown for different options in a form. In Django this would be done on the model with choices
example
OWNERSHIP=[
('current owner', 'Current Owner'),
('past owner','Past Owner'),
]
class Post(models.Model):
title = models.CharField(max_length=100)
ownership = models.CharField(max_length=100, choices=OWNERSHIP)
then just render the form field as {{ form.ownership }} and it will give you a dropdown

django queryset not showing accurate result (building a news app)

I am creating a news app using django. It consists of search by date option. When i choose the date(ex:29-11-2020) and click submit, It should take me to the news of that particular day. When i try the below code instead of showing the details it is giving me a blank page.
views.py
from django.shortcuts import render
from .models import *
from django.views.generic.detail import DetailView
from django.views.generic import ListView
def index(request):
return render(request,'newspaperapp/index.html')
class nowlist(ListView):
model = newsmodel_1
template_name = 'newspaperapp/index.html'
class newslist(DetailView):
model = newsmodel_1
template_name = 'newspaperapp/home.html'
context_object_name = 'newspaperapp'
# search by giving date in index and search date
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
if query:
postresult = newsmodel_1.objects.filter(date_published__contains=query)
result = postresult
else:
result = None
return result
urls.py
from django.urls import path
app_name = 'newspaperapp'
from .views import newslist,SearchView,nowlist
from newspaperapp import views
urlpatterns = [
path('',views.index,name='index'),
path('date/',nowlist.as_view(),name = "date"),
path('<int:pk>',newslist.as_view(),name = "home"),
path('results/', SearchView.as_view(), name='search'),
]
newspaperapp/home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Today's Paper</p>
{{newspaperapp.date_published}}
{{newspaperapp.category}}
</body>
newspaperapp/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- this page has search option and different categories of news -->
<!-- to create search option we write views code and continue -->
<form class="form-inline my-2 my-lg-0" method="GET" action="{% url 'newspaperapp:search' %}">
<input class="form-control mr-sm-2" type="date" placeholder="Search" aria-label="Search"
name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
{%for newspaperapp in object_list %}
<li>{{newspaperapp.title}}
{{newspaperapp.date_published}}
{%endfor%}
</ul>
</body>
</html>
newspaperapp/search.html
{% block content %}
{% for newspaperapp in all_search_results %}
<h3></h3>
{% empty %}
<h2>No results found</h2>
{% endfor %}
{% endblock %}
Contain usually translated to LIKE in sql typically is used to search for a specified text pattern in a column.
If you want to filter date, you could convert query it to datetime object, and search the objects in that particular date range using gte and lt lookups.
from datetime import datetime, timedelta
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
# query is of type 'str', convert to datetime
start_day = datetime.fromisoformat(query)
end_day = start_day + timedelta(days=1)
if query:
postresult = newsmodel_1.objects.filter(
date_published__gte=start_day,
date_published__lt=end_day
)
result = postresult
else:
result = None
return result
Note: add more logic to handle query is None

Having two forms in one HTML page

I wanted to have a page for both sign up and login. However I couldn't handle the two forms. Here is my code.
I was wondering myself if it is possible to give names to the forms or handle it in another way?
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].label = "Display name"
self.fields["email"].label = "Email address"
url.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url('', views.SignUp.as_view(), name="signup"),
url('', auth_views.LoginView.as_view(template_name="index.html"),name='login'),
url('', auth_views.LogoutView.as_view(), name="logout"),
]
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="container">
<h1>Login</h1>
<form method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-default">
</form>
</div>
<div class="container">
<h1>Sign Up</h1>
<form method="POST" >
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-default">
</form>
</div>
</body>
</html>
Thank You very much
I believe this post has the answer you need. Here are my thoughts on the information:
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms. This will sometimes be a bit messy as some CBVs require a primary key and others do not, which may lead to conflicts.
Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons Django form? This is the one that I prefer as it's cleaner to implement.
Actually i want able to POST and my apologies. in short you have to use Fetch API for this

How to toggle password visibility while using flask and flask_wtf forms?

I just started learning flask, and i was wondering how can I toggle password field visibility by a button added in html and i can't figure it out.
app.py
from flask import Flask
from flask import render_template, url_for, flash, redirect
from forms import MyForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '40928745c948f3f1e67703b23b49b9c5'
#app.route('/', methods=('GET', 'POST'))
def home():
form = MyForm()
return render_template('home.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
forms.py
from flask_wtf import FlaskForm
from wtforms import PasswordField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
password = PasswordField('password', validators=[DataRequired()])
home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sample</title>
</head>
<body>
<form method="POST" action="/">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name(size=20) }}
<input type="submit" value="Go">
<button type="button" name="">Show Password</button> <! –– Using this button, toggle password visibilty -- !>
</form>
</body>
</html>
Now I know that {{ form.hidden_tag() }} is to hide input fields but how do I toggle the visibility?
You can use JavaScript
home.html
window.addEventListener("load", function(){
var checkbox = document.getElementById('{{form.check.id}}');
var x = document.getElementById(''{{form.password.id}}'');
checkbox.addEventListener('change', function() {
if(this.checked) {
x.type = 'text';
} else {
x.type = 'password';
}
});
});
forms.py
class MyForm(FlaskForm):
password = PasswordField('password', validators=[DataRequired()],id='password')
show_password = BooleanField('Show password', id='check')

Django form not being submitted

I have a Django model/view/form that is rendering correctly in the template, but it is not submitting the data that is input to the database. Any help with this would be greatly appreciated!
#models.py
from django.db import models
from django.forms import ModelForm
class UserRegistration(models.Model):
user_first = models.CharField(max_length=50)
user_last = models.CharField(max_length=50)
user_email = models.EmailField()
#user_fantasyhost = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s %s' % (self.user_first, self.user_last, self.user_email)
class RegForm(ModelForm):
class Meta:
model = UserRegistration
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.dc_django.models import UserRegistration
from acme.dc_django.models import RegForm
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/league_setup/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
#repage.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="/league/">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account"
</form><br /><br />
</body>
</HTML>
Thank you for your help,
dp
I tried your code. Your problem is that the action attribute of your html form tag is set to "/league/".
Unless reqPage url is actually "/league/", it won't work. When i changed action="/league/" to action="" as such:
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account" />
</form><br /><br />
</body>
</HTML>
The form did work:
In [3]: UserRegistration.objects.all()
Out[3]: [<UserRegistration: aoeu oeu oeu#aeou.com>]