I'm trying to make a post request, I have created the models as well, but for some reason, it is giving me the following error
I understand that this mean there is some mistyped, but when I check the html and views.py, I don't see any mistake, everything should be in order
financiamiento.html
{% extends "Portafolio/layout.html" %}
{%block content %}
<br>
<div class="text-center">
<form action="{% url 'financiamiento'%}" method="POST" style="max-width:800px;margin:auto;">
{% csrf_token %}
<h1 class="mt-5">Perspectiva Financiera</h1>
<h1 class="h3 mb-10 mt-2">Financiamiento</h1>
<label class="sr-only"></label>
<input name= "MontoProyecto" type="text" id="MontoProyecto" placeholder="Monto Aporte Proyecto"class="form-control">
<label class="sr-only"></label>
<input name= "MontoPropio" type="text" id="MontoPropio" placeholder="Monto Aporte Propio"class="form-control">
<label class="sr-only"></label>
<input name="MontoBanca" type="text" id="MontoBanca" placeholder="Monto Aporte Banca"class="form-control">
<label class="sr-only"></label>
<input name="MontoPublico" type="text" id="MontoPublico" placeholder="Monto Aporte Publico"class="form-control">
<div class="d-grid gap-2 mt-3">
<input type="submit" class="btn btn-lg btn-primary">
</div>
</form>
</div>
{% endblock %}
views.py
from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .models import Proyecto, Financiamiento
# Create your views here.
def index(request):
return render (request, "Portafolio/index.html",{
"financiamiento":Financiamiento.objects.all()
})
def registroproyecto(request):
if request.method == 'POST':
NombreProyecto = request.POST.get('NombreProyecto')
ResponsableProyecto = request.POST.get('ResponsableProyecto')
EvaluadorProyecto = request.POST.get('EvaluadorProyecto')
DescripcionProyecto = request.POST.get('DescripcionProyecto')
Proyecto.objects.create(NombreProyecto=NombreProyecto, ResponsableProyecto=ResponsableProyecto, EvaluadorProyecto=EvaluadorProyecto, DescripcionProyecto=DescripcionProyecto)
return redirect("/Portafolio")
return render (request, "Portafolio/RegistroProyecto.html")
def financiamiento(request):
if request.method == 'POST':
MontoProyecto = request.POST.get('MontoProyecto')
MontoPropio = request.POST.get('MontoPropio')
MontoBanca = request.POST.get('MontoBanca')
MontoPublico = request.POST.get('MontoPublico')
Financiamiento.objects.create(MontoProyecto=MontoProyecto, MontoPropio=MontoPropio, MontoBanca=MontoBanca, MontoPublico=MontoPublico)
return redirect("/Portafolio")
return render (request, "Portafolio/Financiamiento.html")
Also, something draw my attention, when I made the Financiamiento table, when I checked with the django admin, it didn't me allow to put input data, that is normal?
models.py
from django.db import models
# Create your models here.
class Proyecto(models.Model):
NombreProyecto = models.CharField(max_length=64)
ResponsableProyecto = models.CharField(max_length=64)
EvaluadorProyecto = models.CharField(max_length=64)
DescripcionProyecto = models.CharField(max_length=500)
class Financiamiento(models.Model):
MontoProyecto = models.IntegerField
MontoPropio = models.IntegerField
MontoBanca = models.IntegerField
MontoPublico = models.IntegerField
admin.py
from django.contrib import admin
from .models import Proyecto, Financiamiento
# Register your models here.
admin.site.register(Proyecto)
admin.site.register(Financiamiento)
In models.py all fields you have are IntegerFields. So, in your views.py you should convert the elements from string to integers first:
def financiamiento(request):
if request.method == 'POST':
MontoProyecto = int(request.POST.get('MontoProyecto'))
MontoPropio = int(request.POST.get('MontoPropio'))
MontoBanca = int(request.POST.get('MontoBanca'))
MontoPublico = int(request.POST.get('MontoPublico'))
Financiamiento.objects.create(MontoProyecto=MontoProyecto, MontoPropio=MontoPropio, MontoBanca=MontoBanca, MontoPublico=MontoPublico)
return redirect("/Portafolio")
return render (request, "Portafolio/Financiamiento.html")
Related
I am creating a simple django models of doctors and department. there is not link between them and when I try to update the department then it is show me this error IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name this error is new for me. I check other similar question also but didn't get much. so pls help me.
here is my view.py file
from django.shortcuts import render
from .forms import Doctorslist,Departmentform
from .models import Department, Doctor
from django.shortcuts import redirect
from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView)
from django.contrib.messages import constants as messages
import os
# Create your views here.
def add_show(request):
form = Doctorslist()
if request.method == "POST":
form = Doctorslist(request.POST, request.FILES)
form.save()
return redirect('/')
else:
form = Doctorslist()
stud = Doctor.objects.all
context = {'form':form,
'stu':stud
}
return render(request, 'main/index.html', context)
def update_data(request, id):
prod = Doctor.objects.get(id=id)
if request.method == "POST":
prod.doc_image = request.FILES['doc_image']
prod.kycdocument = request.FILES['kycdocument']
prod.name = request.POST.get('name')
prod.phone_number = request.POST.get('phone_number')
prod.email = request.POST.get('email')
prod.city = request.POST.get('city')
prod.speciality = request.POST.get('email')
prod.save()
messages.success(request, "Product Updated Successfully")
return redirect('/')
context = {'prod':prod}
return render(request, 'main/update_doc.html', context)
def delete_data(request,id):
if request.method =='POST':
pi = Doctor.objects.get(pk = id)
pi.delete()
return redirect('/')
def add_show_dept(request):
form = Departmentform()
if request.method == "POST":
form = Departmentform(request.POST)
form.save()
return redirect('/')
else:
form = Departmentform()
dept = Department.objects.all
context = {'form':form,
'stu':dept
}
return render(request, 'main/pages-profile.html', context)
def update_dept_data(request, id):
prod = Department.objects.get(id=id)
if request.method == "POST":
prod.dept_name = request.POST.get('dept_name')
prod.dept_Email = request.POST.get('dept_Email')
prod.save()
messages.success(request, "Product Updated Successfully")
return redirect('/')
context = {'prod':prod}
return render(request, 'main/update_dept.html', context)
here is model.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
import os
# Create your models here.
import datetime
def get_file_path(request, filename):
filename_original = filename
nowTime = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
filename = "%s%s" % (nowTime, filename_original)
return os.path.join('uploads/', filename)
class Doctor(models.Model):
name = models.CharField(max_length=20)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
email = models.EmailField(max_length = 100)
city = models.CharField(max_length=100)
speciality = models.CharField(max_length=50)
doc_image = models.ImageField(upload_to = get_file_path)
kycdocument = models.ImageField(upload_to = get_file_path, null = True, blank = True)
class Department(models.Model):
dept_name = models.CharField(max_length=20)
dept_Email = models.EmailField(max_length=100)
dept_password = models.CharField(max_length=200)
here is forms.py file
from django import forms
from phonenumber_field.modelfields import PhoneNumberField
from .models import Doctor,Department
class Doctorslist(forms.ModelForm):
class Meta:
model = Doctor
fields = ('name','phone_number','email', 'city', 'speciality', 'doc_image', 'kycdocument')
# widgets = {
# 'name': forms.TextInput(attrs = {'class': 'form-control'}),
# 'email': forms.EmailInput(attrs={'class': 'form-control'}),
# 'city': forms.CharField(attrs={'class': 'form-control'}),
# 'speciality': forms.CharField(attrs={'class': 'form-control'}),
# }
class Departmentform(forms.ModelForm):
class Meta:
model = Department
fields = ('dept_name','dept_Email','dept_password')
widgets = {'dept_password': forms.PasswordInput()}
here is update_dept.html file
{% extends 'base.html' %}
{% block content %}
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h2 class="fw-bold">Edit Product</h2>
</div>
<div class="card-body">
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label for="" class="form-label">Name</label>
<input type="text" Required name="name" value="{{ prod.dept_name }}" class="form-control">
</div>
<div class="mb-3">
<label for="" class="form-label">Email</label>
<input type="text" Required name="price" value="{{ prod.dept_Email }}" class="form-control">
</div>
<button type="submit" class="btn btn-warning">Update</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Your HTML form uses the wrong names, and therefore request.POST does not contain any entries like dept_name and dept_Email. You should specify name="dept_name" instead of name="name" and name="dept_Email" instead of name="price":
<div class="mb-3">
<label for="" class="form-label">Name</label>
<input type="text" Required name="dept_name" value="{{ prod.dept_name }}" class="form-control">
</div>
<div class="mb-3">
<label for="" class="form-label">Email</label>
<input type="text" Required name="dept_Email" value="{{ prod.dept_Email }}" class="form-control">
</div>
That being said, I would strongly advise that you use a ModelForm, you can make a second ModelForm for the department where you leave out the dept_password.
You can see the Rendering fields manually section of the documentation that shows how you can render you Django form with custom HTML.
I'm new to dajngo projects and I have created a blog which has app named as "blog".Everything went all right and I stuck at conatct from.when I sumbmit details in contact from and go to djando admin database the contact details are not saved here.
This is my contact.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>contact us</title>
</head>
{% load static %}
<body style="background-image: url('{% static " img/contact.jpg" %}');background-size: cover;">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<div class="container my-3" style="padding:70px 0">
<h3>Contact Us</h3>
<form method="post" action="{% url "contact" %}" > {% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email">
</div>
<div class="form-group" >
<label for="name">Phone</label>
<input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number">
</div>
<div class="form-group" >
<label for="desc">How May We Help You?</label>
<textarea class="form-control" id="desc" name='desc' rows="3"></textarea>
</div>
<button style=" margin-top: 25px;" type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</body>
</html>
This is post_detail.html
{% extends 'base.html' %} {% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 left top">
<div class="card-body">
<h1>{% block title %} {{ post.title }} {% endblock title %}</h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
<p class="card-text ">{{ post.content | safe }}</p>
</div>
</div>
{% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %}
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
<!-- comments -->
<h2>{{ comments.count }} comments</h2>
{% for comment in comments %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
{{ comment.name }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="post" style="margin-top: 1.3em;">
<!--{{ comment_form.as_p }}-->
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
This is admin.py
from django.contrib import admin
from .models import Post,Comment
from .models import Contact
from django_summernote.admin import SummernoteModelAdmin
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status', 'created_on')
list_filter = ("status",)
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name', 'body', 'post', 'created_on', 'active')
list_filter = ('active', 'created_on')
search_fields = ('name', 'email', 'body')
actions = ['approve_comments']
def approve_comments(self, request, queryset):
queryset.update(active=True)
class PostAdmin(SummernoteModelAdmin):
summernote_fields = ('content',)
admin.site.register(Post, PostAdmin)
admin.site.register(Contact)
This is models.py
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
from django.urls import reverse
return reverse("post_detail", kwargs={"slug": str(self.slug)})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
class Contact(models.Model):
msg_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
email = models.CharField(max_length=70, default="")
phone = models.CharField(max_length=70, default="")
desc = models.CharField(max_length=500, default="")
def __str__(self):
return self.name
This is urls.py
from . import views
from django.urls import include
from django.urls import path
from .feeds import LatestPostsFeed, AtomSiteNewsFeed
urlpatterns = [
path("feed/rss", LatestPostsFeed(), name="post_feed"),
path("feed/atom", AtomSiteNewsFeed()),
path("<slug:slug>/", views.post_detail, name="post_detail"),
path("", views.PostList.as_view(), name="home"),
path("about.html",views.about,name='about'),
path("contact.html",views.contact,name='contact'),
path("blb.html",views.blb,name='blb '),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
This is view.py
from .models import Post
from django.views import generic
from .forms import CommentForm
from django.shortcuts import render, get_object_or_404
from .models import Contact
def about(request):
return render(request,'about.html',{})
def contact(request):
return render(request,'contact.html',{})
def blb(request):
return render(request,'blb.html',{})
def Contact(request):
if request.method == "POST":
name = request.POST.get['name','']
email = request.POST.get['email','']
phone = request.POST.get['phone','']
content = request.POST.get['content','']
contact = Contact(name=name, email=email, phone=phone, content=content)
contact.save()
return render(request, "contact.html")
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by("-created_on")
template_name = "index.html"
paginate_by = 3
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
This is project urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
sitemaps = {
"posts": PostSitemap,
}
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("blog.urls"), name="blog-urls"),
path("summernote/", include("django_summernote.urls")),
path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
enter image description here
[1]: https://i.stack.imgur.com/RCOt4.png
First of all you shoudn`t put the name of your html template in urls.py of your app.
i mean these three lines :
path("about.html",views.about,name='about'),
path("contact.html",views.contact,name='contact'),
path("blb.html",views.blb,name='blb '),
you have to for example replace them with
path('contact/',...)
and for better and cleaner code , it`s better to use forms in your app . create forms.py in your app DIR and import your model in your forms.py like this for example :
from django import forms
from .models import Profile
class {model name (Table name)}(forms.ModelForm):
class Meta:
model = {model name (Table name)}
fields = '__all__'
Replace {model name (Table name)} with your model in your models.py.
then in each input filed in your HTML template, for name attr , you shoud use the same name that uses in your models.py fields.
And in your views.py you should do like this:
form = **{form name}**(request.POST or None, request.FILES)
if form.is_valid():
form.save()
return redirect('**{ somewhere :) }**')
return render(request, 'contact.html', {'form': form})
Hope this Answer could help you ;-)
I have a model in models.py like this:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.DO_NOTHING)
phone_number = models.CharField(max_length=50, default='')
Birthday = models.CharField(max_length=50, default='')
city = models.CharField(max_length=50, default='')
school = models.CharField(max_length=100, default='')
course = models.CharField(max_length=50, default='')
I want to allow my users to make edits, so I made a function like this in my views.py:
if request.method == 'POST':
profil = UserProfile.objects.get(user=request.user)
profil.phone_number = models.CharField(max_length=50, default='')
profil.Birthday = models.CharField(max_length=50, default='')
profil.city = models.CharField(max_length=50, default='')
profil.school = models.CharField(max_length=100, default='')
profil.course = models.CharField(max_length=50, default='')
profil.save()
return redirect('profile')
return render(request, 'edit_profile.html')
My template is:
<form action="." method="post">
{% csrf_token %}
Phone Number:
<input type="text" name="phone_number" value="{{ profil.phone_number }}" /><br />
Birthday:
<input type="text" name="Birthday" value="{{ profil.Birthday }}" /><br />
city:
<input type="text" name="city" value="{{ profil.city }}" /><br />
school:
<input type="text" name="school" value="{{ profil.school }}" /><br />
course:
<input type="text" name="course" value="{{ profil.course }}" /><br />
<input type="submit" value="Save Changes" name="save" />
<input type="reset" value="Cancel" name="cancel" />
<br/>
</form>
I do not know why, but after filling the form I get an error saying page not found. And if I check the existing user profile nothing got updated. Help please.
you have an error
profil = UserProfile.objects.get(user=request.user)
profil.phone_number = models.CharField(max_length=50, default='')
you get an UserProfile object and then instead of saving str into phone_number you try to save an object models.CharField.
use ModelForm to achieve what you need.
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = '__all__'
then in your view you can use:
userprofile_form = UserProfileForm(request.POST if request.POST else None, instance = UserProfile.objects.get(user=request.user))
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('profile')
return render(request, 'edit_profile.html', context={'userprofile_form': userprofile_form)
and in html use:
<form action="." method="post">
{% csrf_token %}
Phone Number: {{ userprofile_form.phone_number }}
Birthday: {{ userprofile_form.Birthday }}
city: {{ userprofile_form.city }}
school: {{ userprofile_form.school }}
course: {{ userprofile_form.course }}
<input type="submit" value="Save Changes" name="save" />
<input type="reset" value="Cancel" name="cancel" />
<br/>
</form>
or just
<form action="." method="post">
{% csrf_token %}
{{ userprofile_form }}
<input type="submit" value="Save Changes" name="save" />
<input type="reset" value="Cancel" name="cancel" />
<br/>
</form>
if you want to use upload files, don't forget to put your files into form you can do it
UserProfileForm(request.POST, request.FILES, instance = UserProfile.objects.get(user=request.user))
and in html you need to put <form enctype="multipart/form-data" method="post" action="...">
Reproduce these steps, you might need slight modifications:
1. Create a UserEditForm
in forms.py
from .models import UserProfile
from django.forms import ModelForm
class UserEditForm(ModelForm):
class Meta:
model = UserProfile
fields = '__all__' # or ['phone_number', 'Birthday', 'city', 'only_fields_you_want_to_edit']
2. Create a View:
in views.py
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404
from django.urls import reverse
from django.forms.models import model_to_dict
from .models import UserProfile
from .forms import UserEditForm
def userEdit(request, user_id):
user = get_object_or_404(Question, pk=user_id)
if request.method == "GET":
form = UserEditForm(initial=model_to_dict(user))
return render(request, 'yourapp/useredit_form.html', {'form':form)
elif request.method == "POST":
form = UserEditForm(request.POST, instance=user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('user_profile', kwargs={'uid':user.id}))
else:
return HttpResponseRedirect(reverse('some_fail_loc'))
3. Create template
in yourapp/useredit_form.html
<form method="POST">
{% csrf_token %}
{{form}}
<button type="submit">Submit</button>
</form>
4. Set a URL:
in urls.py
urlpatterns += [
path('edit_user/<int:user_id>/', views.userEdit, name='user_edit'),
]
Now try visiting yourapp.com/edit_user/1. You are good to go. :D
when I try to add details using this form it is not updating to my database.
please help me to solve this issue.
There is no error but the database is not updated.
club.html
{% extends "base.html" %}
{% block content %}
{%ifequal request.user.Isclubmember True%}
<div class='container'>
</div>
{%else%}
<div class="container">
<form action="." method="POST">
{%csrf_token%}
Profile Pic:
<input name="image" accept=".png,.jpg,.jpeg" type="file" value=selectimage>
Phonenumber:
<input name="userphonenumber" type="number" placeholder="+91 9876543210" >
<input type="submit" value="submit" class="btn btn-success">
</form>
</div>
{%endifequal%}
{% endblock content %}
views.py
from django.conf import settings
from django.contrib import messages
from django.shortcuts import redirect
from django.contrib.auth.models import User
from .models import UserProfile, Clubmember
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.http import HttpResponseRedirect
def club(request):
if request.method == 'POST':
if request.user.is_authenticated:
Clubmember.user = request.user
Clubmember.phone_number = request.POST.get('userphonenumber')
Clubmember.userphoto = request.FILES.get('image')
request.user.Isclubmember = True
request.user.save()
Clubmember.save()
return redirect(request,'core:home')
else:
return redirect(request,'login_url')
else:
return render(request,'core:club')
models.py
class Clubmember(models.Model):
user = models.ForeignKey(UserProfile,default=1, on_delete=models.CASCADE)
userphoto = models.ImageField(upload_to="userphotos/%Y/%m",default=False)
phone_number = models.IntegerField(default=False)
usermoney = models.FloatField(default=0.0)
Change the view like this, it should work.
def club(request):
if request.method == 'POST':
if request.user.is_authenticated:
club_member = Clubmember()
club_member.user = request.user
club_member.phone_number = request.POST.get('userphonenumber')
club_member.userphoto = request.FILES.get('image')
request.user.Isclubmember = True
request.user.save()
club_member.save()
return redirect(request,'core:home')
else:
return redirect(request,'login_url')
else:
return render(request,'core:club')
and a better approach is
def club(request):
if request.method == 'POST':
if request.user.is_authenticated:
club_member = Clubmember(
user=request.user,
phone_number=request.POST.get('userphonenumber'),
userphoto=request.FILES.get('image')
)
club_member.save()
request.user.Isclubmember = True
request.user.save()
return redirect(request,'core:home')
else:
return redirect(request,'login_url')
else:
return render(request,'core:club')
I am working width Django now. But I don't make sense about that.
I want to get id and password from the form and check if the password from form is correct to compare with the password of database.
Following are the my codes.
Please help me.
models.py
from django.db import models
class Doctor(models.Model):
doctor_id = models.CharField(max_length=16, primary_key=True)
clinic_id = models.ForeignKey(Clinic)
doctor_email = models.CharField(max_length=64)
doctor_password = models.CharField(max_length=32)
doctor_name = models.CharField(max_length=32)
create_date = models.DateTimeField(auto_now_add=True)
modify_date = models.DateTimeField(auto_now=True)
forms.py
from django import forms
from .models import Doctor
class LoginForm(forms.Form):
class Meta:
model = Doctor
fields = ('doctor_id', 'doctor_password',)
views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .forms import LoginForm
from .models import Doctor
#ensure_csrf_cookie
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
_id = form.cleaned_data['doctor_id']
_password = form.cleaned_data['doctor_password']
b = Doctor.objects.all().filter(doctor_id=_id)
if _password is doctor_password:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'apiv1/login.html', {'form': form})
login.html
{% extends "base.html" %}
{% load staticfiles%}
{% block title%}Title{% endblock %}
{% block remoshincss %}/static/css/style.css{% endblock %}
{% block content %}
<div class="container">
<div align="center" class="imgtop"><img id="profile-img" class="profile-img-card" src="/static/img/remoshinlogo.png" /></div>
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" action="{% url 'login' %}" method="post">{% csrf_token %}
<input type="user" id="userid" name="userid" class="form-control inputUser" placeholder="USER-ID" autofocus>
<input type="password" id="password" name="password" class="form-control inputPassword" placeholder="PASSWORD">
<input type="hidden" name="next" value="{{ next }}" />
<br>
<div align="center"><button style="width: 200px;" class="btn btn-lg btn-primary btn-block btn-signin" type="submit"><font color="#708090">Login</font></button></div>
</form>
</div>
</div>
{% endblock %}
Import check_password
from django.contrib.auth.hashers import check_password
check password
pass_ = check_password(_password, b.doctor_password)
if pass_ is False:
return HttpResponse('Invalid login')
Code:
#ensure_csrf_cookie
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
_id = form.cleaned_data['doctor_id']
_password = form.cleaned_data['doctor_password']
docter = Doctor.objects.filter(doctor_id=_id).last()
if docter is None:
return HttpResponse('Invalid login')
pass_ = check_password(_password, docter.doctor_password)
if pass_ is False:
return HttpResponse('Invalid login')
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'apiv1/login.html', {'form': form})