'Can't get the Profile instance that have logged user as field
So i have here a 'create_project' view where l’m trying to assigne to the 'owner' field of project instance created a 'profile of the current user logged . so it's show a error says:
DoesNotExist at /projects/create-project/
Profile matching query does not exist.
create_project view :
def create_project(request): # create operation
form = projectForm()
if (request.method == "POST"):
form = projectForm(request.POST,request.FILES)
if form.is_valid(): # check if it valid
project = form.save(commit=False)
project.owner = Profile.objects.get(user=request.user)
project.save()
return redirect("home")
context = {'form':form}
return render(request, 'projects/project_form.html',context)
Project Model Class:
class project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)
Profile Model Class:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
Solution 1:[1]
Based on your implementation you should instead do;
project.owner, created = Profile.objects.get_or_create(user=request.user)
get_or_create() will return the object and a bool for whether or not the object was created by the function call.
I'd also advise that you make the project owner a User foreign key rather than a Profile. I inherited a project that was setup like this, where an object was associated with the user profile. The majority of the time its details from the User object that we were interested in so the link would have made more sense to the User.
You should also consider using a signal to create the profile objects for a user. I do this using the post_save from User;
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile
User = get_user_model()
@receiver(post_save, sender=User)
def build_profile_on_user_creation(sender, instance, created, **kwargs):
if created:
profile = Profile(user=instance)
profile.save()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | markwalker_ |
