0

how can i create a correct sign-in And sign-up with custom user model(OneToOneField) in django ? im using normal HTML form . im using Django 2.2.3 . my database is Postgeres.

hi, i created a website that sign in and sign up where ok , But ... i needed custom user model .. so i created a custom user model (using one on one field ) , but i don't know how to create sign-in and sign-up for it... so i tryed ... but it won't work correctly... i can't make a sign up with additional fields in my custom user model , it sign up with only User , not Profile and gives me this error "'Manager' object has no attribute 'create_profile'". and for my sign-in .. i think its sign-in with Django's User. im using Django 2.2.3 . my database is Postgeres. how can i create a correct sign-in And sign-up ?

my models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
     user           =   models.OneToOneField(User,on_delete=models.CASCADE)
     address        =   models.TextField(max_length=500)
     phone          =   models.CharField(max_length=50)
     postcode       =   models.CharField(max_length=50, blank=True)
     isManager      =   models.BooleanField(default=False)
     isAccountment  =   models.BooleanField(default=False)
     isStorekeeper  =   models.BooleanField(default=False)
     isSeller       =   models.BooleanField(default=False)
     isNormal       =   models.BooleanField(default=True)

     def __str__(self):
         return self.user.email

def create_profile(sender,**kwargs):
    if kwargs['created']:
        user_profile=Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile,sender=User)

my views.py :

from django.shortcuts import render , redirect
from django.contrib.auth.models import User
from accounts.models import Profile
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.core.mail import send_mail



def signup(request):
if request.method == 'POST':
    #USER HAS INFO AND WANTS ACCOUNT___NOW!
    if request.POST['password1'] == request.POST['password2']:
        try:
            user =  User.objects.get(username=request.POST['username'],)
            return render(request,'accounts/signup.html',{'error':'Username Exist...Try Something Else !','username':user})
        except User.DoesNotExist :
            user = User.objects.create_user(request.POST['username'] , password = request.POST['password1'],first_name=request.POST['fname'],last_name=request.POST['lname'],email=request.POST['email'],)
            profile = user.profile # because of signal and one2one relation
            profile.phone = request.POST['mobile_num']
            profile.address = request.POST['address']
            profile.postcode = request.POST['post_code']
            profile.save()
            auth.login(request,user)              
            return redirect('homepage')
    return render(request,'accounts/signup.html',{'error':"Passwords Don't Match"})
else:
    #USER wants enter info
    return render(request,'accounts/signup.html')    
def login(request):
    if request.method == 'POST':
        user=auth.authenticate(username=request.POST['username'],password=request.POST['password'])
        if user is not None:
            auth.login(request,user)
            return render(request,'products/home.html')
            #return redirect('homepage')
        else:
            return render(request,'accounts/login.html',{'error':'Username Or Password Is Incorrect !'})
    else:
        return render(request,'accounts/login.html')

def logout(request):
    if request.method =='POST':
        auth.logout(request)
        return redirect('homepage')
@login_required
def myproducts(request):
        user_id=request.user.id
        products=Products.objects.all().filter(creator__exact=user_id)
        return render(request,'accounts/myproducts.html',{'products':products})
def about_us(request):
    return render(request,'accounts/aboutus.html')
def connect_us(request):
    return render(request,'accounts/connectus.html')

and this is my form page :

{% extends 'base.html' %}

{% block content%}
<h1 style="margin-left:490px"> Register </h1>
<div class="left" style="margin-left:465px">
<form method="POST" action="{% url 'signup' %}">
  {% csrf_token %}
  First Name:
  <br/>
  <input type="text" name="fname"/><br/>
  Last Name:
  <br/>
  <input type="text" name="lname"/><br/>
  UserName:
  <br/>
  <input type="text" name="username"/><br/>
  Mobile:
  <br/>
  <input type="text" name="mobile_num"/><br/>
  Email:
  <br/>
  <input type="text" name="email"/><br/>
  Address:
  <br/>
  <input type="text" name="address"/><br/>
  Post Code
  <br/>
  <input type="text" name="post_code"/><br/>
  Password:
  <br/>
  <input type="password" name="password1"/><br/>
  Confirm password:
  <br/>
  <input type="password" name="password2"/>
  <br/>
  <br/>
  <input class="btn btn-primary" type="submit" name="signup-btn" value="SignUp" style="margin-top:-23px;margin-left:49px;"/>
</form>
{% if error %}
<p style="color:red">{{error}}</p>
<br/>
{% endif%}
</div>
{% endblock %}

please help .

Hossein
  • 11
  • 1
  • 7

1 Answers1

0

I think you are confusing signals and manager methods. You can't call a signal method as manager method.

What I mean by that is create_profile() is a signal, and it will be triggered automatically when a User is created. So, instead of creating Profile, you should create User instance. Like this:

def signup(request):
    if request.method == 'POST':
        #USER HAS INFO AND WANTS ACCOUNT___NOW!
        if request.POST['password1'] == request.POST['password2']:
            try:
                # rest of the code...
            except User.DoesNotExist :
                user = User.objects.create_user(username=request.POST['username'] ,first_name=request.POST['fname'],last_name=request.POST['lname'],email=request.POST['email'],password = request.POST['password1'])
                profile = user.profile # because of signal and one2one relation
                profile.phone_no = request.POST['phone'] 
                profile.post_code = request.POST['post_code']
                profile.save()
                auth.login(request,user)
                return redirect('homepage')
        return render(request,'accounts/signup.html',{'error':"Passwords Don't Match"})
    else:
        #USER wants enter info
        return render(request,'accounts/signup.html')

But, when you try to create a User, you might face error NOT NULL constraint failed, because in Profile there are two fields (phone and address) which are not null. So I suggest you make them null=True.

ruddra
  • 50,746
  • 7
  • 78
  • 101
  • hi, thanks for your help. i did what you have told me... but there is a problem that when i go to Admin panel and check Profile , the User added but address and phone and post code fields are empty.. while in registration form i filed them. How Can I Have Them ? – Hossein Aug 26 '19 at 23:08
  • you can add additional fields in form with phone and post code, and save them to profile. I have updated my answer, so please have a look – ruddra Aug 26 '19 at 23:19
  • i did this , but in Admin panel, Fields are still Empty . profile = user.profile shoud'nt be something else.. like profile = user.Profile() ? – Hossein Aug 26 '19 at 23:34
  • um, did you get any error? Also, did you have a look at the part on how you can update the profile in updated answer :) ? – ruddra Aug 26 '19 at 23:36
  • i did't get an error ... user saved and i log in with it ,but in admin panel , phone,address and ... still empty. and Yes I looked at it...i'm new to django and this is my first project and i don'nt know too much about how signals works... plz help . – Hossein Aug 26 '19 at 23:42
  • The post is updated..but my problem still exist... user saved and i log in with it ,but in admin panel , phone,address and ... still empty. – Hossein Aug 27 '19 at 20:39
  • Views.py Updated .. It worked ... the problem was in the name of requests in Html – Hossein Aug 28 '19 at 17:23
  • Thanks a lot ruddra – Hossein Aug 28 '19 at 17:24