So I'm trying to make a form to appear after the user is authenticated. When the user authenticated then the form appears on the home page but it never appears. I'm pretty sure I'm doing something wrong either in paths or view but can't figure this out. When I do the same code to external new template it works fine but I want the form to appear on the same page. Here is the code:
views.py
def vpn(request):
form = vpn_form(request.POST or None)
if form.is_valid():
form.save()
context ={
'form': form
}
return render(request, 'loginas/home.html', context)
urls.py
urlpatterns = [
# /
path('', views.home, name='home'),
# TEMPORARY
path('signin', views.sign_in, name='signin'),
path('signout', views.sign_out, name='signout'),
path('callback', views.callback, name='callback'),
path('', views.vpn, name='vpn'),
models.py
class VPN(models.Model):
name = models.CharField(max_length=125)
surname = models.CharField(max_length=125)
description = models.TextField()
date_to = models.DateField()
date_from = models.DateField()
forms.py
from .models import VPN
class vpn_form(forms.ModelForm):
class Meta:
model = VPN
fields = ('name', 'surname', 'description', 'date_to', 'date_from')
home template
{% extends "loginas/layout.html" %}
{% load static %}
{% block content %}
<div class="container">
<h1 class="d-flex justify-content-center"> </h1>
<p class="d-flex justify-content-center"></p>
{% if user.is_authenticated %}
<form>
{{form.as_p}}
</form>
{% else %}
<div class="d-flex justify-content-center">
Login
</div>
{% endif %}
{% endblock %}
And the page just loads empty no form present no errors in the console. Any help how to do this would be great
Related
I'm trying to implement profile picture field for users. The following is the code for each file for the implementation I tried, forms.py, models.py, views.py, and urls.py.
I use a IDE (vscode) to debug django, and I placed a breakpoint on the user.avatar = form.cleaned_data['avatar'] line in views.py below, to quickly check if cleaned_data['avatar'] is filled as user input, as I expect.
However, even after I upload a file on the url, submit, the line shows None while expected a image object, and of course it doesn't save anything so no change to the database either.
#
# forms.py
# accounts/forms.py
#
from accounts.models import UserProfile
# ..
class UserProfileForm(forms.ModelForm):
avatar = forms.ImageField(label=_('Avatar'))
class Meta:
model = UserProfile
fields = [
'avatar',
]
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
self.fields['avatar'].required = False
#
# models.py
# accounts/models.py
#
from django.contrib.auth.models import User
from PIL import Image
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to="images", blank=True, null=True)
# note: I also did "python manage.py makemigrations accounts; python manage.py migrate accounts;"
#
# views.py
# accounts/views.py
#
class UserProfileView(FormView):
template_name = 'accounts/profile/change_picture.html'
form_class = UserProfileForm
def form_valid(self, form):
user = self.request.user
user.avatar = form.cleaned_data['avatar']
user.save()
messages.success(self.request, _('Profile picture has been successfully updated'))
return redirect('accounts:change_profile_picture')
#
# urls.py
# accounts/urls.py
#
from .views import UserProfileView
urlpatterns = [
# ..
path('change/profile_picture/', UserProfileView.as_view(), name='change_profile_picture'),
]
What is wrong with the code? Thanks.
edit
as requested, the html accounts/profile/change_picture.html
{% extends 'layouts/html.html' %}
{% load static %}
{% load bootstrap4 %}
{% load i18n %}
{% block content %}
{% include 'head.html' %}
<body>
{% include 'navbar.html' %}
<div id="content" name="content" class="main container">
<div class="w-100 p-3"></div>
<h2>{% trans 'Change profile picture' %}</h2>
<form method="post">
{% csrf_token %}
{% bootstrap_form form %}
<button class="btn btn-success">{% trans 'Change' %}</button>
</form>
<div class="w-100 p-3"></div>
</div>
{% include 'footer.html' %}
</body>
{% endblock %}
Add enctype="multipart/form-data" to the form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
<button class="btn btn-success">{% trans 'Change' %}</button>
</form>
I am trying to show the data on the webpage but I am not able to figure out why the data is not populated on the webpage
my model is this
class Staff(models.Model):
staffid = models.BigAutoField(primary_key=True)
firstname = models.CharField(max_length=20)
lastname = models.CharField(max_length=20)
phonenumber = models.CharField(max_length=15, unique=True)
def __str__(self):
return self.firstname
def staff_name(self):
return "{} {}".format(self.firstname, self.lastname)
def get_absolute_url(self): # new
return reverse('staffdetail', args=[str(self.staffid)])
my views for this is
class StaffListView(ListView):
model = Staff
template_name = 'staffview.html'
and the template is
{% extends 'base.html' %}
{% block content %}
<p>Add a new Staff member</p>
{% if staff %}
There are {{ staff|length }} records:
{% for s in staff %}
<div class="client-entry">
<p>{{ s.staffid }}</p>
</div>
{% endfor %}
{% else %}
There are no staff in the system
{% endif %}
{% endblock content %}
The output on the web page just gives me the else statement. I checked in Django admin and found that there is data in the staff table. Not sure what I am doing wrong. Any help would be appreciated.
UPDATE:
The urls.py file is
from django.urls import path
from .views import HomePageView, ClientListView, ClientCreateView, ClientDetailView, ClientUpdateView, ClientDeleteView, ProjectCreateView, ProjectDetailView, StaffListView, StaffCreateView, StaffDetailView, StaffUpdateView, StaffDeleteView
urlpatterns = [
path('staffview/<int:pk>/staffdetail/staffdelete', StaffDeleteView.as_view(), name='staffdelete'),
path('staffview/<int:pk>/staffdetail/staffupdate', StaffUpdateView.as_view(), name='staffupdate'),
path('staffview/<int:pk>/staffdetail', StaffDetailView.as_view(), name='staffdetail'),
path('staffview/staffnew', StaffCreateView.as_view(), name='staffnew'),
path('staffview/', StaffListView.as_view(), name='staffview'),
path('client/<int:pk>/projectexisting/', ProjectDetailView.as_view(), name='projectdetail'),
path('projectexisting/', ProjectDetailView.as_view(), name='projectdetail'),
path('client/<int:pk>/projectnew/', ProjectCreateView.as_view(), name='projectnew'),
path('client/<int:pk>/delete/', ClientDeleteView.as_view(), name='clientdelete'),
path('client/<int:pk>/update/', ClientUpdateView.as_view(), name='clientupdate'),
path('client/<int:pk>/', ClientDetailView.as_view(), name='clientdetail'),
path('client/new/', ClientCreateView.as_view(), name='clientnew'),
path('clientview/', ClientListView.as_view(), name='clientview'),
path('', HomePageView.as_view(), name='home')
]
Try This
class StaffListView(ListView):
model = Staff
template_name = 'staffview.html'
context_object_name = "staff"
i want to create a todolist app with django.
i created a form for list model but when the user click on submit to submit a list, the form is'nt saved, why?
this is views.py
i have created an instance of the form and set the user field to it and then save the instance but fact it does'nt
def index(request):
if request.user.is_authenticated:
user_ = User.objects.get(username=request.user.username)
lists = user_.user.all()
form = listForm()
if request.method == "POST":
form = listForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return HttpResponseRedirect(reverse("index"))
context = {'lists':lists, 'form':form}
return render(request, 'todolists/index.html', context)
else:
return render(request, 'todolists/login.html')
this is index template
{% extends "todolists/layout.html" %}
{% block body %}
{% if user.is_authenticated %}
<div class="center-column">
<form method="POST" action="{% url 'index' %}">
{% csrf_token %}
{{form.title}}
<input type="submit" class="btn btn-info">
</form>
<div class="todo-list">
{% for list in lists %}
<div class="item-row">
<a class="btn btn-sm btn-info" href="{% url 'update' list.id %}">update</a>
<a class="btn btn-sm btn-danger" href="{% url 'update' list.id %}">delete</a>
<span>{{list}}</span>
</div>
{% endfor %}
</div>
</div>
{% endif %}
{% endblock %}
this is urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name='index'),
path('update/<str:id>/', views.update, name='update'),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
]
this is models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
pass
class list(models.Model):
title = models.CharField(max_length=200)
finished = models.BooleanField(default=False)
timestamps = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
def __str__(self):
return self.title
here is the form code
class listForm(forms.ModelForm):
title= forms.CharField(label=mark_safe("<span style='color:white;'>Title:</span>"),
widget= forms.TextInput(attrs={'placeholder':'Add new task...', 'class':'form-control'}))
finished= forms.BooleanField(label=mark_safe("<span style='color:white;'>Finished:</span>"),
widget= forms.CheckboxInput(attrs={'style':'width:25px;'}))
class Meta:
model = list
fields = '__all__'
Try updating your template file {{ form.title }} to {{ form }} as mentioned in django docs here is the link
Update your forms.py file if want only title field in the HTML
class listForm(forms.ModelForm):
title= forms.CharField(label=mark_safe("<span style='color:white;'>Title:</span>"),
widget= forms.TextInput(attrs={'placeholder':'Add new task...', 'class':'form-control'}))
class Meta:
model = list
fields = ('title', )
I cannot save the data taken from the form to database. The form is displayed properly and it seems that I can submit. Whenever I was redirected to "project_list.html", I cannot see the new project.
I also checked the admin site to whether new instance is saved to model but it seems that something is wrong with my code.
Here is my files:
model.py
class Project(models.Model):
project_id = models.CharField(max_length=30)
project_name = models.CharField(max_length=100)
view.py
def projects_list(request):
projects = Project.objects.all()
table = ProjectTable(Project.objects.all())
RequestConfig(request, paginate={'per_page':25}).configure(table)
return render(request, 'portal/project/list.html', {'projects':
projects, 'table': table})
def project_add(request):
if request.method == 'POST':
form = ProjectAddForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_list',)
else:
form = ProjectAddForm()
return render(request, 'portal/project/add.html', {'form': form})
forms.py
from django import forms
from .models import Project
class ProjectAddForm(forms.ModelForm):
class Meta:
model = Project
fields = ['project_id', 'project_name',]
add.html
{% extends 'portal/base.html' %}
{% block title %}Add Project{% endblock title %}
{% block content %}
<div class="col-sm-10 offset-sm-1 text-center">
<form action="{% url 'portal:projects_list' %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</div>
{% endblock content %}
projects_list.html
{% extends 'portal/base.html' %}
{% load render_table from django_tables2 %}
{% block content %}
<h1>Projects List</h1>
{% render_table table %}
{% endblock content %}
urls.py
from django.urls import path
from . import views
app_name = 'portal'
urlpatterns = [
path('', views.homepage, name='homepage'),
path('password_generator/', views.password_generator,
name='password_generator'),
path('projects_list/', views.projects_list, name='projects_list'),
path('project/<str:project_id>/', views.project_detail,
name='project_detail'),
path('add/', views.project_add, name='project_add'),
]
I found the issue in my code. In my project_add view, I was trying to redirect to "project_list" url but it didnt exists. That was the mistake....
I have been struggling for the past couple of days trying to get my forms to save into my database. As of right now it is creating the object in the database but all of the fields inside the object are empty. I'm trying to save data from a ModelForm into the model.
Models.py
class ContactForm(models.Model):
Name = models.CharField(max_length= 50)
Email = models.EmailField()
Phone = models.CharField(max_length= 50)
Message = models.CharField(max_length= 200)
def __str__(self):
return self.Name
forms.py
class ContactForm(ModelForm):
name = forms.CharField(max_length=50)
email = forms.EmailField(required=True)
phone = forms.CharField(max_length=15)
message = forms.CharField(max_length=50)
class Meta:
model = ContactForm
fields = ['name','email','phone','message']
views.py
def contact(request):
if request.method=='POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = ContactForm()
args = {'form': form}
return render(request, 'home/contact.html', args)
urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^buy-now/$', views.buyNow, name='buy-now'),
url(r'^buy-form/$', views.buyForm, name='buy-form'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^login/$', login, {'template_name': 'home/login.html'}, name='login'),
url(r'^logout/$', logout, {'template_name': 'home/logout.html'}, name='logout'),
url(r'^account/$', views.account, name='account'),
url(r'^register/$', views.register, name='register'),
]
template contact.html
{% extends 'base.html' %}
{% block head %}
<title>Aeviternus | Contact </title>
{% endblock %}
</head>
<body>
{% block body %}
<!-- Section: Contact -->
<section>
<div class="container">
<div class="row">
<div class="col s12 m6">
<div class="card-panel teal white-text center">
<i class="material-icons">email</i>
<h5>Contact Us</h5>
<p>If you have any comments or suggestions for any upcoming content or features you would like to see added, We want to hear about it.</p>
</div>
<ul class="collection with-header">
<li class="collection-header">
<h4>Location</h4>
</li>
<li class="collection-item">CSCI 152 Development Lab</li>
<li class="collection-item">5241 N Maple Ave</li>
<li class="collection-item">Fresno, CA 93740</li>
</ul>
</div>
<div class="col s12 m6">
<div class="card-panel grey lighten-3">
<h5>Please fill out this form</h5>
<form method ="post">
{% csrf_token %}
{{ form }}
<button type="submit" class="waves-effect waves-light btn-large">Submit</button>
</form>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
<!--JavaScript at end of body for optimized loading-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script>
// Sidenav
const sideNav = document.querySelector('.sidenav');
M.Sidenav.init(sideNav, {});
</script>
</body>
</html>
Any help would be greatly appreciated.
Both your model name and form name are same. So, probably it's causing the problem.
change your form class name to ContactModelForm. Then your form class becomes
class ContactModelForm(forms.ModelForm):
name = forms.CharField(max_length=50)
email = forms.EmailField(required=True)
phone = forms.CharField(max_length=15)
message = forms.CharField(max_length=50)
class Meta:
model = ContactForm
fields = ['name','email','phone','message']
or
class ContactModelForm(forms.ModelForm):
class Meta:
model = ContactForm
fields = ['Name','Email','Phone','Message']
and replace ContactForm with ContactModelForm in your views.