Jiroscopes
Jiroscopes

Reputation: 555

Django view not saving to model

I have a view I am calling when a user clicks a button on the site, it pulls JSON data(from the Coinbase API) and converts it to a string and should save the string pulled to the current user's account.

Whenever they click the button it will pull the string, but nothing is saved to the account, which is the issue.

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from ico_login.models import UserAddress 
from coinbase.wallet.client import Client


@login_required()
def generate_address_btc(request, *args, **kwargs):
    client = Client('api', 'key')
    r = client.get_addresses('account_id')
    address = r['data'][0]['address']
    request.user.address = str(address)
    request.user.save()

    return HttpResponse(address)

models.py

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


class UserAddress(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    address = models.CharField(max_length=300, default=' ')

urls.py

from django.contrib import admin
from django.urls import path, include
from ico_details import views


urlpatterns = [
    path('create_address/', views.generate_address_btc, name='generate')
]

Upvotes: 2

Views: 991

Answers (1)

j-i-l
j-i-l

Reputation: 10957

In your view you write request.user.address = ..., so you add the attribute address to a User object. As far as I read your code, this is not what you want. You would like to put str(address) into the field address of the object UserAddress related to the User object from request.user, right?!

So, here are the suggested edits to do so:

models.py

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


class UserAddress(models.Model):
    # next line changed
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_address')
    address = models.CharField(max_length=300, default=' ')

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from ico_login.models import UserAddress 
from coinbase.wallet.client import Client


@login_required()
def generate_address_btc(request, *args, **kwargs):
    client = Client('api', 'key')
    r = client.get_addresses('account_id')
    address = r['data'][0]['address']
    # next 2 lines changed
    request.user.user_address.address = str(address)
    request.user.user_address.save()

return HttpResponse(address)

Hope that helped and happy coding!

Upvotes: 3

Related Questions