0

I got the idea from a random post that how to extend the field of the User Model in Django by using the One to One relation. I'm trying to write One to One relation by creating a complete_user model in models.py but i'm getting error.NOT NULL constraint failed: complete_user.user_id can anyone tell me what's wrong with my code.i'm new in django.

models.py

from django.db import models
from django.contrib.auth.models import User

class complete_user(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    country1=models.CharField(max_length=10)

    class Meta:
        db_table='complete_user'

forms.py

from django import forms

class user_data(forms.Form):
    country=forms.CharField(widget=forms.TextInput)

html file

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  </head>
  <body>
      <br>
    <center><h1 class="bg-info">Create Your New Account</h1></center>
    <header class="container">
        <div class="w-25 mx-auto">
      <form action="{% url 'save_account' %}" method="POST">
        {% csrf_token %}
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" placeholder="e.g. John" required name="name" class="form-control" id="name">
        </div>
        <div class="form-group">
          <label for="email">Email address</label>
          <input type="email" name="email" required placeholder="e.g. john12@gamil.com" class="form-control" id="email" aria-describedby="emailHelp">
          <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
        </div>
        <div class="form-group">
            <label for="country">Country</label>
            <input type="text" required name="country" placeholder="e.g. India" class="form-control" id="country">
        </div>
        <div class="form-group">
          <label for="password1">Password</label>
          <input type="password" minlength="8" required name="password1" class="form-control" id="password1" aria-describedby="password_help">
          <small id="password_help" class="form-text text-muted">Password should be strong it must contain numbers,alphabet and special symbols.</small>
        </div>
        <div class="form-group">
            <label for="Confirm-Password">Confirm-Password</label>
            <input type="password" minlength="8" required name="confirm-password" class="form-control" id="Confirm-Password">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
    </header>
  </body>
</html>

views.py

from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import complete_user
from django.contrib.auth.models import User
from .forms import user_data
# Create your views here.

def my_account(request):
    return render(request,'account.html')

def save_account(request):
    if request.method == "POST":
        userdata=user_data(request.POST)
        name=request.POST.get("name")
        email=request.POST.get("email")
        password1=request.POST.get("password1")
        password2=request.POST.get("confirm-password")
        if (userdata.is_valid()):
            country=userdata.cleaned_data["country"]
            new_user=User.objects.create_user(username=name,email=email,password=password1)
            new_user.save()
            data=complete_user(country1=country)
            complete_user.save(self=data)
        return redirect('/payment/')
    else:
        return HttpResponse("404 Not Found")
  • so, what is the error that you're getting? – Sajad Mar 30 '20 at 13:37
  • Are we supposed to guess what the error is ? Exact error message AND full traceback please. – bruno desthuilliers Mar 30 '20 at 13:37
  • Also: 1/ use CamelCase for your class names, 2/ use a form to create your `User` object (you can use two Django forms in the same HTML form tag and validate both in your view), 3/ if your view must only accept POST requests use the `requires_POST` decorator (which will return the proper HTTP code) - BUT 4/ if your form doesn't validate, you want to re-render it to the user _with the error messages_ instead of blindly redirecting like if everything was ok. – bruno desthuilliers Mar 30 '20 at 13:42
  • Oh and yes: 5/ `User.objects.create_user()` already saves the user so no need to call `new_user.save()`, and 6/ you need to pass the user instance to your (ill-named) 'complete_user` - and that's most probably the cause of the error you get. – bruno desthuilliers Mar 30 '20 at 13:44
  • And you might also be interested in the `Model.objects.create()` method which allow you to create AND save a model instance at once. – bruno desthuilliers Mar 30 '20 at 13:46
  • @Sajad and @bruno desthuilliers i'm getting `NOT NULL constraint failed: complete_user.user_id` – Maninder Singh Mar 30 '20 at 13:48
  • change `data=complete_user(country1=country)` to `data=complete_user(user=new_user, country1=country)` and the error will go away, but this design really is not a good one, You may want to think about extending `AbstractUser` model – Sajad Mar 30 '20 at 13:55
  • @Sajad thanks man for helping me.Can you tell me what is AbstractUser model and how to use it and why this design is not good.does it has any bug or something.again thank you. – Maninder Singh Mar 30 '20 at 14:05
  • What are you doing here is that you're making a table of users, and a table of complete_users, and connect these two with a key; which is not what you really wanted, the complete_user is not something RELATED to user, it's an extension to it. the `AbstractUser` simply is a model in django which gives you the ability to modify and customize the user model. see [this](https://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django) and [this](https://docs.djangoproject.com/en/3.0/topics/auth/customizing/) – Sajad Mar 30 '20 at 14:11
  • @Sajad thank you again. – Maninder Singh Mar 30 '20 at 16:57

0 Answers0