jahantaila
jahantaila

Reputation: 908

Adding data to a Django model associated with a user field

I am creating an application that contains the model UserDetail. In this model, there are 3 fields, a field for donations, points, and a field for the user who is associated with these points. I show these fields in the dashboard.html file, and everything works. My problem is that I manually have to go into /admin and give a user in the database a points and donations field. I want my program to automatically populate the user, donations, and points data to the database when their account is completed, giving the points and donation field a value of 0 and associating it with the user. Below is my code for both the dashboard.html view, which allows the data to be shown on the dashboard page, my UserDetail model, and the view for when the account is created. Thank you to everyone who helps!


Model:

class UserDetail(models.Model):
  donations = models.IntegerField(blank=True, null = True,)
  points = models.IntegerField(blank=True, null = True,)
  user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )

Dashboard view:

@login_required(login_url='/login/')
def dashboard(request):
    user = request.user
    # assuming there is exactly one
    # this will break if there are multiple or if there are zero
    # You can (And should) add your own checks on how many userdetails objects you have for the user
    # consider using a OneToOneField instead of a ForeignKey
    user_details = UserDetail.objects.get(user=user)  # or userdetails.objects.get(user=user)
    context = {
        "donations": user_details.donations,
        "points": user_details.points,
    }
    return render(request,'dashboard.html', context=context)

Signup View:

def register(request, ):
    if request.user.is_authenticated:
        return redirect('/dashboard/')
    else: 
        form = CreateUserForm()
        if request.method == "POST":
            form = CreateUserForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data.get('username')
                messages.success(request, f'Your account has been successfully created, {username} ')
                return redirect('loginpage')
        context = {'form': form}
        return render(request, "register.html",  context )

Upvotes: 1

Views: 131

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476554

You create a UserDetail object in the register view with:

def register(request, ):
    if request.user.is_authenticated:
        return redirect('/dashboard/')
    else: 
        form = CreateUserForm()
        if request.method == "POST":
            form = CreateUserForm(request.POST)
            if form.is_valid():
                user = form.save()
                UserDetail.objects.create(
                    donations=0,
                    points=0,
                    user=user
                )
                username = form.cleaned_data.get('username')
                messages.success(request, f'Your account has been successfully created, {username} ')
                return redirect('loginpage')
        context = {'form': form}
        return render(request, "register.html",  context )

For the existing records that will not be the case, so you will need to create UserDetails manually for these user objects.

Upvotes: 1

Related Questions