how save user from custom form in database - python

Below is my code comprising of django forms.py and views.py file.
I want save new user. How to achieve this?
forms.py
from django import forms
class SignUpForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'first'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'first'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'first'}))
password = forms.CharField(widget = forms.PasswordInput(attrs={'class':'first'}))
re_password = forms.CharField(widget = forms.PasswordInput(attrs={'class':'first'}))
views.py
from django.shortcuts import render
from django.http import HttpResponse
import datetime
from . import forms
def regform(request):
form=forms.SignUpForm()
if request.method=='POST':
form=form.SignUpForm(request.POST)
else:
html="welcome"
return render(request,'home/home.html', {'html':html, 'form':form})

Have a look at thiswill be resourceful. Also, read Django Official docs on User management

Related

send a contact form to mail id and PostgreSQL database using Django

I would like to send a contactform to an emailid as well as save it to postgresql database.The following code helps me to send it to the mail id but can't save it in the database. can anyone please help me to solve this one which would be very much appreciated
urls.py
from django.contrib import admin
from django.urls import path
from.import views
urlpatterns = [
path('email/', views.email, name='email'),
path('success/', views.success, name='success')
]
models.py
from django.db import models
from django.forms import ModelForm
class Comment(models.Model):
what_about = models.CharField(max_length=255)
contact_email = models.EmailField(max_length=255)
content = models.TextField()
Name = models.CharField(max_length=255)
Phone_Number = models.CharField(max_length=255)
def __str__(self): # __unicode__ on Python 2
return self.what_about
forms.py
from django.forms import ModelForm
from django import forms
from .models import Comment
class MyCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['what_about', 'content', 'contact_email', 'Name', 'Phone_Number']
views.py
from django.shortcuts import render, redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from django.utils import timezone
from.forms import MyCommentForm
def email(request):
if request.method == 'GET':
form = MyCommentForm()
else:
form = MyCommentForm(request.POST)
if form.is_valid():
form.save()
cd = form.cleaned_data
subject = form.cleaned_data['what_about']
from_email = form.cleaned_data['contact_email']
message = 'contact_email: "{}"\n Phone_Number: "{}"\n Name: "{}"\n content: "{}"'.format(cd['contact_email'],
cd['Phone_Number'],
cd['Name'],
cd['content'])
try:
send_mail(subject, message, from_email, ['prasanth#interloggg.net'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
You need to import your models in the views and make "Comment.save()"
You're importing ur forms but it isn't ur database, place it in the moment where you think suit the best, save every answer to the right column.

How to put the username of the logged-in user in the databse each time a form is submitted

I have an application where a user can submit a form which goes into the database (POSTGRES).
I want to be able to automatically send the username of the user logged in to the same database, so i can keep track of who is submitting. (I do not want to put a form line with the username, i want this to be dealt with in the back-end).
what I managed to do is get the user-id, but it stays null, and I do not know how to get the username in the database and to complete it at each submission.
I hope I am clear,
thanls guys.
Here is my code
models.py
from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models
class Fertidb(models.Model):
user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
area = models.IntegerField()
plot = models.FileField(upload_to='KML_FILES', blank=True)
def __str__(self):
return f' Parcelles de {self.user.username}'
forms.py
from django import forms
from django.contrib.auth.models import User
from .models import Fertidb
class FertidbForm(forms.ModelForm):
class Meta:
model = Fertidb
labels = {
"plot": "Importez votre fichier KML"
}
fields = ['culture', 'area', 'plot']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User
title = 'FERTISAT'
#login_required
def fertisatmap(request):
mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
if request.method == "POST":
o_form = FertidbForm(request.POST, request.FILES)
if o_form.is_valid():
o_form.save(commit=False)
o_form.user = request.user.username()
messages.success(request, f'Vos informations ont été envoyées')
return redirect('fertisat-map')
else:
o_form = FertidbForm()
context = {'title': title, 'o_form': o_form}
return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})
Try to update your view like so:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User
title = 'FERTISAT'
#login_required
def fertisatmap(request):
mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
if request.method == "POST":
o_form = FertidbForm(request.POST, request.FILES)
if o_form.is_valid():
fertidb = o_form.save(commit=False)
fertidb.user = request.user
fertidb.save()
messages.success(request, f'Vos informations ont été envoyées')
return redirect('fertisat-map')
else:
o_form = FertidbForm()
context = {'title': title, 'o_form': o_form}
return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})
(commit=False) use for creating the model instance without submit to database, then assign current user to your new model instance fertidb.user = request.user and then call .save() to commit your data to database
Btw, mapbox_access_token suppose to stay inside settings.py in case you want to load it from environment variable when deploy production. like so:
settings.py
MAPBOX_ACCESS_TOKEN="pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w"
views.py
from django.conf import settings
...
def fertisatmap(request):
mapbox_access_token = settings.MAPBOX_ACCESS_TOKEN
Hope that helps!
There are two issues here:
1. In your Model, you want a User, but in your form, you are assigning it the username, which I think is a string.
user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
and
o_form.user = request.user.username()
Just change the second line to o_form.user = request.user.
2. You are not saving the user anyway.
You have to save your model again after you assign the user.
Thanks fo the help guys.
#Toan Quoc Ho thank you I made the modifications but I still have a problem.
The database displays the user_id, but I would like it to display the username.
I guess my problem is in the model file. How do I modify the following, so I get the username in the database.
user=deb_models.ForeignKey(User,on_delete)models.CASCADE) puts the user_id -> I would like to have the username. How do I call it ?
models.py
*from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models
class Fertidb(models.Model):
user = db_models.ForeignKey(User, on_delete=models.CASCADE)
culture = models.CharField(max_length=50)
area = models.IntegerField()
plot = models.FileField(upload_to='KML_FILES', blank=True)
def __str__(self):
return f' Parcelles de {self.user.username}'*

how to fill an author field with current username

I have looked at a lot of different places but none of their solutions work. This is most likely to do them being for older versions of django or my own stupidity. So I am making a blog type of app that for some reason is called reviews instead of blog... anyway I need to automatically fill up an author field with the username of the logged in user. Here is my models.py:
from django.db import models
from django.contrib.auth.models import User
#vars
# Create your models here.
class reviews(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.PROTECT,)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True, blank=True)
and forms.py:
from django import forms
from django.forms import ModelForm
from .models import reviews
from django.contrib.auth.decorators import login_required
class CreatePost_form(ModelForm):
class Meta:
model = reviews
exclude = ['author']
fields = ['title', 'body',]
and views:
from django.shortcuts import render, render_to_response
from .forms import CreatePost_form
from django.http import HttpResponseRedirect
# Create your views here.
def reviewlist(request):
return render
def index(request, ):
return render(request, template_name="index.html")
def CreatePost(request):
form = CreatePost_form(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/reviews/succesfulpost')
return render(request, "reviews/CreatePostTemplate.html", {'form':form})
def succesfulpost(request):
return render(request, "reviews/succesfulpost.html")
def CreatePost(request):
form = CreatePost_form(request.POST)
if form.is_valid():
form.save(commit=False)
form.author = request.user
form.save()
return HttpResponseRedirect('/reviews/succesfulpost')
As simple as that. Rather than actually saving and committing the data, you simply save without committing then you're able to change the value of the excluded field.

How to associate users with posts in django and display data based on which user signed in?

I have the following code in django:
models.py
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.TextField(max_length=200,help_text="Put the ingredients required$")
instructions = models.TextField(max_length=500)
def __unicode__(self):
return self.title
forms.py
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import RecipeForm
def add(request):
if request.method == 'POST':
form = RecipeForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('app_name:url'))
else:
messages.error(request, "Error")
return render(request, 'page.html', {'form': RecipeForm()})
Does anyone know how do I associate a user id with it so that when it is saved in database, it also saves which user made this recipe and when a user logs in, he is able to see his recipes only and not the recipes saved by other users. Any suggestions?
You should add a ForeignKey field, pointing to the built-in User model, in your Recipe model:
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipes')
this field will contain the id of the user who created the recipe.
EDIT
And if you have an user object you can access all its recipes like this:
user.recipes.all()
and you'll get only the recipes of that user.

How to save the email and name fields in the Django deafult User table

I want to save the email and name fields in django default table called UserSignup
my models.py is:
from django.db import models
class UserSignup(models.Model):
mailid = models.CharField(max_length=100)
name = models.CharField(max_length=100)
my views.py is:
from django import views
from django.shortcuts import render_to_response
from django.template import RequestContext
from Deals.signup.forms import signup
from django.contrib.auth.models import User
from django.http import HttpResponse
def usersignup(request,form_class=signup):
form = form_class()
print form
if form.is_valid():
mail= UserSignup(mailid=request.POST['mailid'])
mail.save()
name= UserSignup(name=request.POST['name'])
name.save()
else:
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
and forms.py is
from django import forms
from django.contrib.auth.models import User
from Deals.signup.models import *
from django.utils.translation import ugettext_lazy as _
class signup(forms.Form):
email = forms.EmailField(widget=forms.TextInput(),
label=_("Email address:"))
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(),
label=_("Name:"))
def save(self,request,update):
name = self.cleaned_data['name']
name.save()
email = self.cleaned_data['email']
email.save()
Please help me in saving my forms input in database
Check the Django documentation properly http://docs.djangoproject.com/en/dev/topics/forms/
Just change your code in views.py.
def usersignup(request,form_class=signup):
if request.method == 'POST': #If its a form submission, the method is POST
form = form_class(request.POST)
if form.is_valid():
newuser = form.save()
else: #Else display the form
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
The 'save' function in your forms file is incorrect and is not needed.
On a side note, your "UserSignup" is not a default User Table. That would be the user model provided by Django. And that already has the fields that you are creating in UserSignup. Why don't you use that feature of Django?
It might be better to save the model elements in the form in one time.
def save(self):
new_user = User.objects.create_user(name = self.cleaned_data['name'],
email = self.cleaned_data['email'])
return new_user

Categories