My question is about django app, i have one app in one model in class employee ,i want to display how many employee register in fronted side in template.
In below app user count is successfully worked.
I want output like 4 employee register from template form and in template display 4 Employee registered at frontside
Front end side - image
views.py
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django_adminlte.forms import EmployeeForm
from django_adminlte.models import Employee
def emp(request):
if request.method == "POST":
form = EmployeeForm (request.POST) # here "form" is one varible
if form.is_valid():
try:
form.save()
return redirect("/show")
except:
pass
else:
form = EmployeeForm()
return render(request,"employee/employee_index.html",{'form':form})
#i want like this below code(this code is working for count user in front side)
def home(request):
count = User.objects.count()
return render(request,'index.html',{
'count' : count
})
model.py
from django.db import models
class Employee(models.Model):
eid = models.CharField(max_length=20)
ename = models.CharField(max_length=20)
eemail = models.EmailField()
econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"
def __str__(self):
return self.ename
HTML Template
{% extends 'adminlte/base.html' %}
{% block content %}
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3>{{ count }}</h3>
<p>User Registrations</p>
</div>
<div class="icon">
<i class="fas fa-user-plus"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3></h3>
<p>Total Employee</p>
</div>
<div class="icon">
<i class="fas fa-user-plus"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
Just do the same as you did for User
def home(request):
user_count = User.objects.count()
employee_count = Employee.objects.count()
return render(request,'index.html',{
'user_count' : user_count,
'employee_count' : employee_count,
})
And put it in your template for user:
<div class="inner">
<h3>{{ user_count }}</h3>
<p>User Registrations</p>
</div>
and for Employee:
<div class="inner">
<h3>{{ employee_count }}</h3>
<p>Total Employee</p>
</div>
Related
I am trying to display my stat update form in my Django template, however it isn't displaying. My stats below show up correctly, just not the form.
{{ stats.user }} | {{ stats.weight }} | {{ stats.date }}
Template:
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>My Health</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="col-auto text-center p-3 form-group">
<form method="post" style="margin-top: 1.3em;">
{{ update_form }}
{% csrf_token %}
<button type="submit" class="btn btn-signup btn-lg">Submit</button>
</form>
</div>
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<p class="text-center"> {{ stats.user }} | {{ stats.weight }} | {{ stats.date }} </p>
</div>
</div>
</div>
{% endblock content %}
forms.py:
class StatUpdateForm(forms.Form):
class Meta:
model = Stats
fields = ('user', 'weight', 'date')
models.py:
class Stats(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
weight = models.DecimalField(max_digits=5, decimal_places=2)
class Meta:
db_table = 'health_stats'
ordering = ['-date']
def __str__(self):
return f"You currently weigh {self.weight}, {self.user}"
views.py:
from django.shortcuts import render
from .models import Stats
from .forms import StatUpdateForm
from django.views import generic, View
from django.shortcuts import get_object_or_404
# from django.contrib.auth import authenticate
# from django.core.exceptions import ValidationError
# from .forms import RegistrationForm, LoginForm
def home(request):
return render(request, 'home.html')
class MyHealth(View):
def get(self, request, *args, **kwargs):
stats = Stats
context = {
'stats': stats,
"update_form": StatUpdateForm(),
'user': stats.user,
'weight': stats.weight,
'date': stats.date,
}
return render(request, 'MyHealth.html', context)
I've tried redefining the form in my views.py, but I'm unsure why it isn't pulling through, as the other parts of the context are.
Any help would be appreciated!
In the form, since you are using a model, you must extend from forms.ModelForm instead forms.Form, try to change that line in the forms.py
class StatUpdateForm(forms.ModelForm): # extends from forms.ModelForm
class Meta:
model = Stats
fields = ('user', 'weight', 'date')
I assume the form fields are rendering and the fields just aren't loaded with the correct values.
do this: StatUpdateForm(instance=stats) to make it an edit form
I'm trying to make a user active when I tap a button, and I'm using a DetailView.
views.py
from .models import Model
from django.contrib.auth.models import User
from django.shortcuts import redirect
class UserInspectView(DetailView):
model = Model
template_name = 'user-inspect.html'
# Make the user is_active = True
def accept (request, pk):
user = User.objects.get(id=pk)
user.is_active
return redirect('home')
...
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('inspect/<slug:slug>/', views.UserInspectView.as_view(), name='user-inspect'),
path('inspect/<int:pk>/accept/', views.accept, name="user-accept"),
...
]
user-inspect.html
{% extends 'base.html' %}
{% block title %} <title>User Inspection</title> {% endblock %}
{% block content %}
<div class="d-flex justify-content-center">
<div class="container d-flex flex-column">
<div class="ms-5 ps-5" >
<h3><strong>User:</strong> {{model.user}}</h3>
<br>
<h3><strong>Name:</strong> {{model.name}}</h3>
</div>
</div>
</div>
<br><br><br>
<div class="d-flex justify-content-center">
<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group me-2 me-5 pe-5" role="group" aria-label="First group">
<form method="post" action="{% url 'user-accept' model.user.pk %}">
{% csrf_token %}
<button type="submit" class="btn btn-primary">Accept</button>
</form>
</div>
<div class="btn-group me-2 me-5 ps-5" role="group" aria-label="First group">
Back
</div>
</div>
</div>
{% endblock %}
models.py
from django.db import models
from django.contrib.auth.models import User
class Model(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
slug = models.SlugField(unique=True, blank=False, null=False)
Before my accept view looked like this
def accept (request, pk):
user = User.objects.get(id=pk)
user.is_active()
user.save()
return redirect('home')
but I changed it, because I got this error
TypeError at inspect/30/accept/
'bool' object is not callable
When I tap the Accept button, it takes me to the redirect that I have in the accept view, but the user is still inactive.
user.is_active is a boolean not a function.
def accept (request, pk):
user = User.objects.get(id=pk)
user.is_active = True
user.save()
return redirect('home')
I am building a portfolio and i am just learning django i tried to bring data from About in sql and since i have only single piece of data i dont need for loop so i tried putting it directly but is seems i cannot do that. Any suggestion on how i can do it
<section id="about">
<div class="container">
<div class="about-large d-none d-lg-block text-uppercase">About</div>
<div class="about-me row mt-5">
<div class="my-image col-md-5">
<img src="{{ about.image }}" />
</div>
<div class="my-description col-md-6">
<h3>About Me</h3>
<h4>I am {{about.name}}</h4>
<p>{{ about.description }}</p>
<p>{{ about.description_two }}</p>
<div class="cv-hire d-flex flex-start">
<button type="button" class="btn btn-dark font-weight-bold">
Download <i class="fas fa-download pl-2"></i>
</button>
</div>
</div>
</div>
</div>
</section>
My Views .py
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import *
class HomeTemplateView(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['about'] = About.objects.first()
context['services'] = Service.objects.all()
context['works'] = RecentWork.objects.all()
return context
My models.py
from django.db import models
class About(models.Model):
image = models.ImageField(upload_to="static/img")
name = models.CharField(max_length=100,verbose_name="My Name")
description = models.CharField(max_length=500, verbose_name="Description")
description_two = models.CharField(max_length=500, verbose_name="Description", blank=True)
cv = models.FileField(upload_to="static/document")
class Meta:
verbose_name = "About Me"
verbose_name_plural = "About Me"
def __str__(self):
return "About Me"
I'd make some checks:
What returns About.objects.first() in Django shell?
Make template with {{ about.cv }} only to avoid other influences.
Then I can see if expected data exist and what incomes to template.
I need to assign reports only to the users that I authorise from Django Admin. They should not be able to see all the reports in the database. Here's my code:
Models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Match(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length = 100)
url = models.CharField(max_length = 1000)
Views.py:
from django.shortcuts import render
from .models import Match
from django.http import HttpResponse
# Create your views here.
def index(request):
all_matches = Match.objects.all()
return render(request, 'landing.html' , {"all_matches" : all_matches})
def upload(request):
return render(request, 'upload.html')
HTML:
{% if user.is_authenticated %}
<body>
<div class="container-fluid">
<div style="float: right;" class="row">
<div class="col-xl-3 sidenav">
<h1 style="color: #ffffff; text-align: center">All Matches</h1><br>
<form class="form-inline">
<input class="form-control mr-sm-2 input-mysize" type="search" placeholder="Search" aria-label="Search">
</form><br>
{% for match in all_matches %}
<li style="list-style: none ; text-align: center">{{match.name}}</li>
<hr class="new1">
{% endfor %}
</div>
<div class="col-md-9">
<iframe name="iframe1" width="1060" height="730" frameborder="0" allowFullScreen="true"></iframe>
</div>
</div>
</div>
</body>
{% else %}
<meta http-equiv="refresh" content="0; url=/login" />
{% endif %}
</html>
Please help me in a way I can do this.
I found the simple solution.
I had to add an M2M User field to the matches model like so:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Match(models.Model):
name = models.CharField(max_length = 100)
user = models.ManyToManyField(User)
url = models.CharField(max_length = 1000)
def __str__(self):
return self.name
I had to then filter the views so that every user gets to see only the matches assigned to him from the M2M field like so:
from django.shortcuts import render
from .models import Match
# Create your views here.
def index(request):
all_matches = Match.objects.filter(user=request.user)
return render(request, 'landing.html' , {"all_matches" : all_matches})
Voila!
I am new to django, I created my custom user(auth_user) model. I need to create student registration form using custom user model according to my custom object
I have two models Title, User like this:
from django.db import models
#from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
class Title(models.Model):
value = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.value
class Meta:
db_table = 'title'
class User(AbstractUser):
title = models.ForeignKey(Title, on_delete=models.CASCADE, null=True, blank=True)
class Meta:
db_table = 'user'
settings.py:
AUTH_USER_MODEL = 'student.User'
Here i have ForeignKey title field and User default fields first_name, last_name, email,password
My forms.py:
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.core import validators
from student.models import User
from student.models import Title
class StudentRegistrationForm(forms.Form):
filenumber = forms.CharField(label='Filenumber', max_length=45)
class StudentNewRegistrationForm(forms.ModelForm):
title = forms.CharField(required=True)
username = forms.CharField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
email = forms.EmailField(required=True)
password1 = forms.CharField(required=True)
password2 = forms.CharField(required=True)
def __init__(self, *args, **kwargs):
super(StudentNewRegistrationForm, self).__init__(*args, **kwargs)
self.fields['title'] = forms.ModelChoiceField(queryset=Title.objects.all(), empty_label='Choose a title',required=False)
class Meta:
model = User
fields = ['title','username', 'first_name', 'last_name','email' 'password1', 'password2']
def save(self, commit=True):
user = super(StudentNewRegistrationForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
user.title = self.cleaned_data['title']
user.password1 = user.set_password(self.cleaned_data['password1'])
user.password2 = user.set_password(self.cleaned_data['password2'])
if commit:
user.save()
return user
Here i have api response like below:
{"candidate":{"firstname":"Testuser","lastname":"test","salutation":10000,"email":"testing#gmail.com","username":"test"}}
This response coming form studentregistrationview:
from django.shortcuts import render, redirect
from django.urls import reverse
from student.forms import RegistrationForm
from django.contrib.auth import get_user_model
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .forms import StudentRegistrationForm, StudentNewRegistrationForm
import requests
from django.http import JsonResponse
from django.http import HttpResponse
#from django.contrib.auth import get_user_model
from student.models import User
from student.models import Title
import json
import urllib
from django.conf import settings
from django.contrib import messages
def studentregistration(request):
form = StudentRegistrationForm()
if request.method == 'POST':
form = StudentRegistrationForm(request.POST)
if form.is_valid():
data = form.cleaned_data
inputdata = data.get('filenumber')
url = 'https://myapiurl/' + inputdata
result = requests.get(url)
finalresult = result.json()
studentapires = {'studentres': finalresult}
request.session['studentapires'] = studentapires
return redirect('/student/studentnewregistration')
else:
form = StudentRegistrationForm()
return render(request, 'student/studentregister.html', {'form': form})
I am creating new user object like below and i tried to persist object, here issue object is not persisting to user table
student_new_registration view i tried to create new User object like below
student_new_registration.py:
def student_new_registration(request):
studentapires = request.session.get('studentapires', None)
jsonresult = studentapires['studentres']['candidate']
user = User()
if jsonresult['salutation'] == 100000000:
salutation = 'Mister'
elif jsonresult['salutation'] == 100000002:
salutation = 'Madam'
title = Title.objects.get(value=salutation)
user.title = title
user.first_name = jsonresult['firstname']
user.last_name = jsonresult['lastname']
user.email = jsonresult['email']
user.username = jsonresult['username']
if request.method == 'POST':
form = StudentNewRegistrationForm(request.POST, instance=user)
if form.is_valid():
form.save()
return HttpResponse("Registration Completed")
return HttpResponse("Please Check Your Registration Form")
else:
form = StudentNewRegistrationForm(instance=user)
args = {'form': form}
return render(request, 'student/studentnewregistrationform.html', args)
Error:
full_clean() missing 1 required positional argument: 'self', form is not submitting (means form not going inside form.is_valid())
studentnewregistrationform.html:
{% extends 'base.html' %}
{% block head %}
<title>Student Profile Form</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm-4">
<h3> Student Profile Form</h3>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.title.label }}</div>
<div class="col-sm-3">{{ form.title }}</div>
<div class="col-sm-4">{{ form.title.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.first_name.label }}</div>
<div class="col-sm-3">{{ form.first_name }}</div>
<div class="col-sm-4">{{ form.first_name.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.last_name.label }}</div>
<div class="col-sm-3">{{ form.last_name }}</div>
<div class="col-sm-4">{{ form.last_name.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.email.label }}</div>
<div class="col-sm-3">{{ form.email }}</div>
<div class="col-sm-4">{{ form.email.errors }}</div>
</div>
<br>
<br>
<div class="row">
<div class="col-sm-2">{{ form.username.label }}</div>
<div class="col-sm-3">{{ form.username }}</div>
<div class="col-sm-4">{{ form.username.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2"><label for="{{ form.password1.label }}">Password</label></div>
<div class="col-sm-3">{{ form.password1 }}</div>
<div class="col-sm-4">{{ form.password1.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2"><label for="{{ form.password2.id_for_label }}">ConfirmPassword</label></div>
<div class="col-sm-3">{{ form.password2 }}</div>
<div class="col-sm-4">{{ form.password2.errors }}</div>
</div>
<br><br>
<div class="row">
<div class="col-sm-2 col-sm-offset-2"> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/></div>
<div class="col-sm-2"></div>
</div>
</form>
</div>
{% endblock %}
here issue is i am able to render all fields to registration form but i am not able to persist data and while persisting custom object i am getting this error
Manager isn't available; 'auth.User' has been swapped for 'student.User'
please help me any one, Thanks in advance...
You need to change User model inside your views.py file and in any other files where you are using User class. To new model. For this try to add following import:
from django.contrib.auth import get_user_model
User = get_user_model()
Instead of
from django.contrib.auth.models import User