Django view not saving to model - python

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')
]

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!

Related

how to store third party access token to database to my profile model from views.py django

i'm trying to store a session id and an access token from a third party website's API to my users profiles
i've been trying for days and searching but i couldn't find anything like this
i tried to import profiles instances so that i can save the data to the users profiles instances
but i didn't find out how , here is my code
#views.py
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
from django.contrib.auth.decorators import login_required
import urllib.parse
from django.views.generic import View
from users.models import Profile
from django.contrib.auth.models import User
def profile_view(request):
RuName= 'driss_aitkassi-drissait-crm-SB-ijuzzy'
r= {
'RuName': RuName
}
response = api.execute('GetSessionID', r)
print(response)
res =response.text
tree= ET.fromstring(res)
#here is my session id from the website's api
for node in tree.iter('{urn:ebay:apis:eBLBaseComponents}GetSessionIDResponse'):
SessionID= node.find('{urn:ebay:apis:eBLBaseComponents}SessionID').text
#i tried this :
s=Profile(session_id=SessionID)
s.save()
# and also tried this
# and also this:
Profile.objects.update(session_id=SessionID)
Profile.objects.model.save()
here is the Models.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User,related_name='profile' , on_delete=models.CASCADE)
token = models.TextField(max_length=500, blank=True)
session_id=models.TextField( max_length=500, blank=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
please help me with this or just point me at the right direction thanks

send a contact form to mail id and PostgreSQL database using Django

I would like to send a contactform to an emailid as well as save it to postgresql database.The following code helps me to send it to the mail id but can't save it in the database. can anyone please help me to solve this one which would be very much appreciated
urls.py
from django.contrib import admin
from django.urls import path
from.import views
urlpatterns = [
path('email/', views.email, name='email'),
path('success/', views.success, name='success')
]
models.py
from django.db import models
from django.forms import ModelForm
class Comment(models.Model):
what_about = models.CharField(max_length=255)
contact_email = models.EmailField(max_length=255)
content = models.TextField()
Name = models.CharField(max_length=255)
Phone_Number = models.CharField(max_length=255)
def __str__(self): # __unicode__ on Python 2
return self.what_about
forms.py
from django.forms import ModelForm
from django import forms
from .models import Comment
class MyCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['what_about', 'content', 'contact_email', 'Name', 'Phone_Number']
views.py
from django.shortcuts import render, redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from django.utils import timezone
from.forms import MyCommentForm
def email(request):
if request.method == 'GET':
form = MyCommentForm()
else:
form = MyCommentForm(request.POST)
if form.is_valid():
form.save()
cd = form.cleaned_data
subject = form.cleaned_data['what_about']
from_email = form.cleaned_data['contact_email']
message = 'contact_email: "{}"\n Phone_Number: "{}"\n Name: "{}"\n content: "{}"'.format(cd['contact_email'],
cd['Phone_Number'],
cd['Name'],
cd['content'])
try:
send_mail(subject, message, from_email, ['prasanth#interloggg.net'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
You need to import your models in the views and make "Comment.save()"
You're importing ur forms but it isn't ur database, place it in the moment where you think suit the best, save every answer to the right column.

How to put the username of the logged-in user in the databse each time a form is submitted

I have an application where a user can submit a form which goes into the database (POSTGRES).
I want to be able to automatically send the username of the user logged in to the same database, so i can keep track of who is submitting. (I do not want to put a form line with the username, i want this to be dealt with in the back-end).
what I managed to do is get the user-id, but it stays null, and I do not know how to get the username in the database and to complete it at each submission.
I hope I am clear,
thanls guys.
Here is my code
models.py
from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models
class Fertidb(models.Model):
user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
area = models.IntegerField()
plot = models.FileField(upload_to='KML_FILES', blank=True)
def __str__(self):
return f' Parcelles de {self.user.username}'
forms.py
from django import forms
from django.contrib.auth.models import User
from .models import Fertidb
class FertidbForm(forms.ModelForm):
class Meta:
model = Fertidb
labels = {
"plot": "Importez votre fichier KML"
}
fields = ['culture', 'area', 'plot']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User
title = 'FERTISAT'
#login_required
def fertisatmap(request):
mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
if request.method == "POST":
o_form = FertidbForm(request.POST, request.FILES)
if o_form.is_valid():
o_form.save(commit=False)
o_form.user = request.user.username()
messages.success(request, f'Vos informations ont été envoyées')
return redirect('fertisat-map')
else:
o_form = FertidbForm()
context = {'title': title, 'o_form': o_form}
return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})
Try to update your view like so:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User
title = 'FERTISAT'
#login_required
def fertisatmap(request):
mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
if request.method == "POST":
o_form = FertidbForm(request.POST, request.FILES)
if o_form.is_valid():
fertidb = o_form.save(commit=False)
fertidb.user = request.user
fertidb.save()
messages.success(request, f'Vos informations ont été envoyées')
return redirect('fertisat-map')
else:
o_form = FertidbForm()
context = {'title': title, 'o_form': o_form}
return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})
(commit=False) use for creating the model instance without submit to database, then assign current user to your new model instance fertidb.user = request.user and then call .save() to commit your data to database
Btw, mapbox_access_token suppose to stay inside settings.py in case you want to load it from environment variable when deploy production. like so:
settings.py
MAPBOX_ACCESS_TOKEN="pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w"
views.py
from django.conf import settings
...
def fertisatmap(request):
mapbox_access_token = settings.MAPBOX_ACCESS_TOKEN
Hope that helps!
There are two issues here:
1. In your Model, you want a User, but in your form, you are assigning it the username, which I think is a string.
user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
and
o_form.user = request.user.username()
Just change the second line to o_form.user = request.user.
2. You are not saving the user anyway.
You have to save your model again after you assign the user.
Thanks fo the help guys.
#Toan Quoc Ho thank you I made the modifications but I still have a problem.
The database displays the user_id, but I would like it to display the username.
I guess my problem is in the model file. How do I modify the following, so I get the username in the database.
user=deb_models.ForeignKey(User,on_delete)models.CASCADE) puts the user_id -> I would like to have the username. How do I call it ?
models.py
*from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models
class Fertidb(models.Model):
user = db_models.ForeignKey(User, on_delete=models.CASCADE)
culture = models.CharField(max_length=50)
area = models.IntegerField()
plot = models.FileField(upload_to='KML_FILES', blank=True)
def __str__(self):
return f' Parcelles de {self.user.username}'*

How to compare models using id's Django

Can anyone please help in tackling the following problem?
Suppose I have a model named Answer and a form for user input named CheckAnswer.
What I want is that when a particular Question page is openend and the user types the answer, it should get checked with the corresponding answer
The answer from the model can be accessed using the id. but how can i specify the id of question page that opens up and link it to the answer id.
Below are the codes attached
forms.py
from django import forms
from .models import Answer
from django.core.exceptions import ObjectDoesNotExist
class CheckAnswer(forms.Form):
your_answer=forms.CharField(label='Answer')
def clean(self):
cleaned_data=super(CheckAnswer,self).clean()
response=cleaned_data.get("your_answer")
try:
p = Answer.objects.get(id=1,answer__iexact=response)
except Answer.DoesNotExist:
raise forms.ValidationError("Wrong Answer.")
views.py
from django.shortcuts import render,redirect
from django.views.generic import *
from . import models
from django import forms
from .forms import CheckAnswer
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def Arena1(request):
if request.method=='POST':
form = CheckAnswer(request.POST)
if form.is_valid():
return redirect('thanks')
else:
form=CheckAnswer()
return render(request,'levels/arena1.html',{'form':form})
models.py
from django.db import models
from django.contrib.auth import get_user_model
User=get_user_model()
users=User.objects.all()
# Create your models here.
class Answer(models.Model):
name=models.CharField(max_length=10,unique=True)
answer=models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
ordering= ["-name"]

[Django]How to get the str(id) of a ModelA object in order to give the source code of a page as initial value of a CharField that belongs to a ModelB?

I started to code a two-apps django project. ModelA belongs to appone and ModelB belongs to apptwo. My purpose is to create a ModelA instance everytime that the user creates a ModelB instance. And the value of a ModelA CharField (that is ckeditor widgeted) must be the source code of a ModelB admin view. I used a post_data signal to link a function of creation for that. The problem is that i use the id of each instance of ModelB in order to create the good content for each instance of ModelA. When I try to use a string of the url sending the id parameter, the content field has for value the source code of the debug page
(error 500, DoesNotExist at /admin/apptwo/modelb/my_view/ref=76, [76 is an example] ModelB matching query does not exist. Exception location : /home/me/Desktop/env/lib/python3.5/site-packages/django/db/models/query.py in get, line 385)
But when I try to visit the url "http://localhost:8000//admin/apptwo/modelb/my_view/ref=76", or when I hardcode the url, without a str(instance.id), the page exists and everything works perfectly.
I don't understand why.
Could anybody give me some help to solve this problem ?
Thanks in advance,
PS :
The first app has a model.py that contains the following code :
from django.db import models
from django.contrib.auth.models import User
from registre.models import *
class ModelA(models.Model):
content = models.CharField(max_length=255, null=True)
def __str__(self):
return "ModelA : " + str(self.id)
the admin.py of this first app also contains :
from django.contrib import admin
from appone.models import *
from apptwo.models import ModelB
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.conf.urls import url
from registre import views
from django.db.models.signals import post_save
from django.dispatch import receiver
import datetime
from django.contrib.auth.models import User
from django import forms
from ckeditor.widgets import CKEditorWidget
from django.template.loader import render_to_string
import requests
class ModelAAdminForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = ModelA
fields = '__all__'
class ModelAAdmin(admin.ModelAdmin):
form = ModelAAdminForm
def create_A(sender, instance, **kwargs):
string = "http://localhost:8000/admin/apptwo/modelb/my_view/ref=" + str(instance.id)
r = requests.get(string)
ModelA.objects.create(contenu=r.text.encode('utf-8'))
post_save.connect(create_A, sender=ModelB)
admin.site.register(ModelA, ModelAAdmin)
the second app (apptwo) has a models.py like this :
from django.db import models
from django.contrib.auth.models import User
class ModelB(models.Model):
owner = models.ForeignKey(User, null=True)
name = models.CharField(max_length=255, null=True)
def __str__(self):
return self.name
and an admin.py that contains :
from django.contrib import admin
from appone.models import *
from apptwo.models import *
import datetime
from django.conf.urls import url, include
from django.template.response import TemplateResponse
class ModelBAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(ModelB, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(owner=request.user)
def save_model(self, request, obj, form, change):
obj.owner = request.user
obj.save()
def get_urls(self):
urls = super(ModelBAdmin, self).get_urls()
my_urls = [
url(r'^my_view/ref=(?P<id>\d+)$', self.my_view),
]
return my_urls + urls
def my_view(self, request, id):
context = dict(
self.admin_site.each_context(request),
selector = ModelB.objects.get(id=id),
)
return TemplateResponse(request, "myview.html", context)
admin.site.register(ModelB, ModelBAdmin)
and finally a template myview.html with :
<p>Test {{ selector.name }}</p>

Categories