0

"Column 'email_id' cannot be null" This is the error I am getting when I try to fill the form when a user is logged in form will be accessible only to logged in users to update their day to day work.
This is the model:

class User(AbstractBaseUser):
 sys_id = models.AutoField(primary_key=True, blank=True)
 email = models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
 )
 first_name = models.CharField(max_length=50,blank=True,null=True)
 last_name = models.CharField(max_length=50,blank=True,null=True)
 address = models.TextField(max_length=300,blank=True,null=True)
 DOB = models.DateField('Date of Birth', blank=True, null=True)
 DOJ = models.DateTimeField(auto_now=True)
 active = models.BooleanField(default=True)
 staff = models.BooleanField(default=False) 
 admin = models.BooleanField(default=False)

class services(models.Model):
 taskid = models.AutoField(primary_key=True, blank=True)
 client = models.CharField(max_length=50,blank=True,null=True)
 project = models.CharField(max_length=50,blank=True,null=True)
 taskTime = models.DateTimeField('Task Time', blank=True, null=True)
 hours = models.TimeField(blank=True, null=True)
 minutes = models.TimeField(blank=True, null=True)
 Description = models.TextField(max_length=300,blank=True,null=True)
 email = models.OneToOneField(User, on_delete=models.CASCADE)

This is Form:

class ServiceForm(forms.ModelForm):
class Meta:
    model = services
    fields = ('client','project','taskTime','hours','minutes','Description')

This is View:

@login_required
def service(request):
  if request.method == 'POST':
      user_form = ServiceForm(data=request.POST)
      if user_form.is_valid():
          user_form.email = request.user.email
          user_form.save()
      else:
          print(user_form.errors)
  else:
      user_form = ServiceForm()
  return render(request, 'service.html', {
    'user_form':user_form})

My main Problem is that user login and tries to create a service or his work details user id should automatically be assigned to the service model. Pls, help me to solve this problem.
My problem is when I create the task its has username as email and should automatically assign to it when I create the task it'not happening as mentioned duplicate it differs assigning username when creating the first form is easy but my question is I am creating another form when user logins and that user id should be assigned to this form by default.

Naga Teja
  • 73
  • 2
  • 3
  • 10

1 Answers1

0

You should prepopulate your form with the required information. Because email is a OneToOne relation to User (confusing naming there!), you should use the request.user object, not the email address:

  user_form = ServiceForm(data=request.POST, initial={'email': request.user})
Selcuk
  • 57,004
  • 12
  • 102
  • 110