Cannot Create New Users with Django - python

As the title states, I've been having a huge problem adding users to my Django server as of late. I was following this tutorial on setting up user registration with Django when I realized that there were no users being created when I checked the admin panel.
In my forms.py file:
from django import forms
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
In my views.py file:
def createUser(request):
form = RegisterForm(response.POST)
if request.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
context = {'form': form}
return render(request, "main/signup.html", context)
Here is a link to signup.html without all the Django functions.
In signup.html, I tried three things:
Replaced each <input> tags with its respective {{form.formfield}}
Placed {{form}} in the next line after the <form> tag
Removed all HTML, CSS, and JS from the signup page and unlinked it from the template page and made the signup page consist of only
<form method="POST" action="">
{% csrf_token %}
{{form.username.label}}
{{form.username}}
{{form.email.label}}
{{form.email}}
{{form.password1.label}}
{{form.password1}}
{{form.password2.label}}
{{form.password2}}
<input type="submit" name="Create User">
</form>
In all three of these attempts to get a user creation form that works, I ended up not only being unable to create a new user, but also was unable to create the form I needed. In my third attempt, all I got was a submit button with no form. Any help on this matter of mine would be greatly appreciated.

Related

How to take boolean field input from HTML into my Django model?

I have used Django forms for creating users and I extended the default User model by adding a boolean field, so I defined a new form for it. But I couldn't take input from HTML form to this boolean field. Shall I change my HTML form code?
Following are my code samples:
models.py
# accounts.models.py
from django.db import models
from django.contrib.auth.models import User
class SpecialUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
flag = models.BooleanField()
def __str__(self):
return self.title
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.widgets import CheckboxInput
from .models import SpecialUser
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
class SuperUserForm(forms.ModelForm):
class Meta:
model = SpecialUser
fields = ['flag']
widgets = {
'flag': CheckboxInput(attrs={'class': 'flag'}),
}
views.py
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
sp_form = SuperUserForm(request.POST)
if form.is_valid() and sp_form.is_valid():
user = form.save()
sp_form = sp_form.save(commit=False)
sp_form.user = user
sp_form.save()
messages.success(request, 'Account created!')
return redirect('login')
else:
form = RegisterForm()
sp_form = SuperUserForm()
messages.warning(request, 'Your account cannot be created.')
return render(request, 'register.html', {'form': form})
HTML form code:
<form method="post" class="form-group">
{% csrf_token %}
{{ form|crispy }}
<label for="flag">Special User: </label>
<input id="flag" class="flag" type="checkbox" name="flag">
<button type="submit" class="btn btn-success">Sign up</button>
</form>
In your views.py you're creating a local variable for a SpecialUser form, sp_form, that is neither loaded into the context data nor templated in the HTML form code.
You can load sp_form into the context data by adding it to the context dict passed to render(). This will allow the template to see the variable. For example:
return render(request, 'register.html', {'form': form, 'sp_form': sp_form})
And then you can render it in the template. For example, underneath the main form:
{{ form|crispy }}
{{ sp_form|crispy }}
For starters this is generally not how you would want to extend the user model in a Django application. You would want to inherit from AbstractUser and add your fields to that model and run migrations. At least in this case, that would be ideal, then you could simply define the field on your RegisterForm.fields and let {{ form|crispy }} render the form for you. Naturally, you could call form.save() and move on with your life.
To clarify why this may not be working, it is generally not good practice to render your own fields for a form unless absolutely necessary. If you insist on doing it this way, note that Django prefixes the id with id_ so in your case it would be <label for="id_name">...</label> and <input id="id_flag" ...

Unable to add data to databse from models forms django

I am trying to send data from django forms to backend sqlite3. But I am unable to do so. I am not also getting any error or warning that help me to sort it out.
Here is models.py file
from django.db import models
GENDER_CHOICES = [
('Male', 'M'),
('Female', 'F')]
class upload(models.Model):
name = models.CharField(max_length=100)
gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
phone = models.CharField(max_length=50,null=True)
email= models.EmailField(max_length=50,null=True)
file=models.FileField(upload_to='uploads/')
def __str__(self):
return self.name
here is forms.py file
from django.forms import ModelForm
from .models import upload
class uploadForm(ModelForm):
class Meta:
model = upload
fields = ['name', 'gender', 'phone', 'email','file']
Here is view.py file
from django.shortcuts import render
from .forms import uploadForm
from django.shortcuts import render
def home(request):
if request.method == 'POST':
form = uploadForm()
if form.is_valid():
form=form.save()
return HttpResponseRedirect('/')
else:
form = uploadForm()
return render(request,'home.html',{'print':form})
I am unable to understand where is the issue
This is how template file look like
<form method="post">
{% csrf_token %}
{{ print.as_p }}
<input type="submit" value="Submit">
</form>
EDIT
This issue is with FileField, I removed it, and it start saving in django database. What I want is to save file in media folder and other data in database
I also added enctype="multipart/form-data" in form
I don't think your actually sending anything to the database.
Where is says form = uploadForm() you need state you want the posted data to be sent. so this needs to be form = uploadForm(request.POST) it should then work I believe. Also when saving the form, remove the form=form.save() and leave it as form.save()
Try it out and let us know?
Solution to my post
For handling files, I need to add encryption type to my form as
enctype="multipart/form-data"
Once I added that, to access the files I should use request.FILES along with request.POST
So now I have this home function in views.py file
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = uploadForm()
return render(request,'home.html',{'print':form})
and my template form looks like
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ print.as_p }}
<input type="submit" value="Submit">
</form>
Credit : https://youtu.be/Rr1-UTFCuH4?t=244

login form keeps telling my username already exists django

So I am trying to make a login form for a django website using a forms.py file to generate a form in my html. I have already made a registration form using the same methods and that works fine but for some reason my login form keeps working like a registration form and saying that my username already exists. i assume it is just a litle mistake but I can't figure out what it is exactly.
forms.py
from django.contrib.auth.models import User
from django import forms
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
models.py
class LoginFormView(View):
form_class = LoginForm
template_name = 'intranet/login_form.html'
def get(self, request):
form = self.form_class(None)
return render(request,self.template_name,{'form': form})
def post(self,request):
form = self.form_class(request.POST)
if form.is_valid():
username = request.POST.get['username']
password = request.POST.get['password']
user = authenticate(username=username,password=password)
if user is not None:
if user.is_active:
login(request,user)
return redirect('werknemers_list')
return render(request, self.template_name, {'form': form})
login_form.html
<h1>Log in</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="log in" />
</form>
urls.py
from django.conf.urls import url
from intranet import views
urlpatterns = [
url(r'^$', views.LoginFormView.as_view(), name='login'),
url(r'^registreer$', views.UserFormView.as_view(), name='registreer')]
You shouldn't use a ModelForm for this. That will always call the model validation, which in this case checks for username uniqueness.
Use a standard Form class instead.

right username password not login django

I am developing a small website with django and I am using the built-in login view. When I register a standard user and then try to login with the right credentials it shows me the login error "please enter a correct username and password". This problem doesn't occurr with the superusers that I created. The can login with the right credentials without any error message showed.
This is the views.py with my registration view.
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth.models import User
from .forms import UserForm
def register_user(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
return redirect('user_profile', pk=user.pk)
else:
form = UserForm()
return render(request, 'interport/register_user.html', {'form':form})
The admin.py:
from django.contrib import admin
from django.contrib.auth.models import User
forms.py:
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password',)
urls.py:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
url(r'^register_user$', views.register_user, name='register_user'),
url(r'^$', views.home, name='home'),
]
the template for login:
{% extends "interport/base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="center col s4 offset-s4 card-panel #fff8e1 amber lighten-5">
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</div>
</div>
</div>
{% endblock %}
You're saving the new user with a plain text password, but Django will always hash the password before checking for validity.
You need to create your users via User.objects.create_user(), which hashes the password correctly, or use user.set_password() to set the hashed password after creating.
The accepted answer is good and old, however I would advice to put those instructions in the save function of the said form.
This way allows you to have a clearer code in your views and an easier maintenance should you change the way the form is handled. you dont have to go back to every function in your views.py where you used that form.
in OP's case, the Form would look like that afterwards:
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password',)
def save(self, commit=False):
instance = super(UserForm, self).save(commit=False) # create but don't save yet
if commit:
instance.set_password(instance.password)
instance.save()
return instance
There might be more elegant way, but it's been working for me like that.
to have explanation regarding commit=False : Django ModelForm: What is save(commit=False) used for?

how to transfer values from html form to Django admin?

I made one html form in which auto suggestion option also in city field. I want to know that how transfer the values of html form to django admin.
till now i made a model of form where fields like name,city,phone number,sex which register in admin.py. by this i am not able to register directly by django admin.
If you already have your html form, you have to create your function in views.py.
In this file, you have to write the code which is going to receive the data you send from the html form.
Read the docs : Django forms
You probably have a html form like the following :
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
You can create a form in forms.py :
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Your function can look like this (in views.py)
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})

Categories