FieldError at /cart/checkout/ - django-models

Exception Value:
Cannot resolve keyword 'active' into field.
Choices are: billing_profile, billing_profile_id, brand, country, default, exp_month, exp_year, id, last4, stripe_id.
When i click on checkout button it show me that error.i already have a lot of models which are related to each other,i check all of them but i did not got any error so can you please verify them.
billing models.py
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save,pre_save
from accounts.models import GuestEmail
import stripe
User=settings.AUTH_USER_MODEL
STRIP_SECRET_KEY= getattr(settings,"STRIP_SECRET_KEY","sk_test_I2eGCibhrZeFd9N0ipx9ac4I")
#STRIP_PUB_KEY=getattr(settings,"STRIP_PUB_KEY","pk_test_nvw3qh6iGMtKSGHMW5MHVwQD")
stripe.api_key=STRIP_SECRET_KEY
class BillingProfileManager(models.Manager):
def new_or_get(self,request):
user=request.user
guest_email_id=request.session.get('guest_email_id')
created=False
obj=None
if user.is_authenticated:
obj,created= self.model.objects.get_or_create(
user=user, email=user.email)
elif guest_email_id is not None:
guest_email_obj = GuestEmail.objects.get(id=guest_email_id)
obj, created = self.model.objects.get_or_create(
email=guest_email_obj.email)
else:
pass
return obj,created
class BillingProfile(models.Model):
user=models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE)
email=models.EmailField()
active=models.BooleanField(default=True)
update = models.DateTimeField(auto_now=True)
timestamp=models.DateTimeField(auto_now_add=True)
customer_id=models.CharField(max_length=120,null=True,blank=True)
objects=BillingProfileManager()
def __str__(self):
return self.email
def charge(self,order_obj,card=None):
return Charge.objects.do(self,order_obj,card)
def get_cards(self):
return self.card_set.all()
#property
def has_card(self):
card_qs=self.get_cards()
return card_qs.exists()
#property
def default_card(self):
default_cards=self.get_cards().filter(default=True)
if default_cards.exists():
return self.default_cards.first()
return None
def billing_profile_created_receiver(sender,instance,*args,**kwargs):
if not instance.customer_id and instance.email:
print("ACTUAL AIL REQUEST SEND")
customer=stripe.Customer.create(
email=instance.email
)
print (customer)
instance.customer_id=customer.id
pre_save.connect(billing_profile_created_receiver,sender=BillingProfile)
class CardManager(models.Manager):
def all(self, *args, **kwargs): # ModelKlass.objects.all() --> ModelKlass.objects.filter(active=True)
return self.get_queryset().filter(active=True)
def add_new(self, billing_profile, token):
if token:
customer = stripe.Customer.retrieve(billing_profile.customer_id)
stripe_card_response = customer.sources.create(source=token)
new_card = self.model(
billing_profile=billing_profile,
stripe_id = stripe_card_response.id,
brand = stripe_card_response.brand,
country = stripe_card_response.country,
exp_month = stripe_card_response.exp_month,
exp_year = stripe_card_response.exp_year,
last4 = stripe_card_response.last4
)
new_card.save()
return new_card
return None
def user_created_receiver(sender,instance,created,*args,**kwargs):
if created and instance.email:
BillingProfile.objects.get_or_create(user=instance,email=instance.email)
post_save.connect(user_created_receiver,sender=User)
class ChargeManager(models.Manager):
def do(self, billing_profile, order_obj, card=None): # Charge.objects.do()
card_obj = card
if card_obj is None:
cards = billing_profile.card_set.filter(default=True) # card_obj.billing_profile
if cards.exists():
card_obj = cards.first()
if card_obj is None:
return False, "No cards available"
c = stripe.Charge.create(
amount = int(order_obj.total * 100), # 39.19 --> 3919
currency = "usd",
customer = billing_profile.customer_id,
source = card_obj.stripe_id,
metadata={"order_id":order_obj.order_id},
)
new_charge_obj = self.model(
billing_profile = billing_profile,
stripe_id = c.id,
paid = c.paid,
refunded = c.refunded,
outcome = c.outcome,
outcome_type = c.outcome['type'],
seller_message = c.outcome.get('seller_message'),
risk_level = c.outcome.get('risk_level'),
)
new_charge_obj.save()
return new_charge_obj.paid, new_charge_obj.seller_message
class Charge(models.Model):
billing_profile = models.ForeignKey(BillingProfile,on_delete=models.CASCADE)
stripe_id = models.CharField(max_length=120)
paid = models.BooleanField(default=False)
refunded = models.BooleanField(default=False)
outcome = models.TextField(null=True, blank=True)
outcome_type = models.CharField(max_length=120, null=True, blank=True)
seller_message = models.CharField(max_length=120, null=True, blank=True)
risk_level = models.CharField(max_length=120, null=True, blank=True)
objects = ChargeManager()
class Card(models.Model):
billing_profile=models.ForeignKey(BillingProfile,on_delete=models.CASCADE)
stripe_id=models.CharField(max_length=120)
brand=models.CharField(max_length=120,null=True,blank=True)
country = models.CharField(max_length=12, null=True, blank=True)
exp_month=models.IntegerField(null=True,blank=True)
exp_year=models.IntegerField(null=True,blank=True)
last4=models.CharField(max_length=4,null=True,blank=True)
default=models.BooleanField(default=True)
objects = CardManager()
def __str__(self):
return "{} {}".format(self.brand, self.last4)
checkout.html
{% extends "base.html" %}
{% block content %}
{% if not billing_profile%}
<div class="row text-center">
<div class="col-12 col-md-6">
<p class="lead">Login</p>
{% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %}
</div>
<div class="col-12 col-md-6">
Continue as Guest
{% url "guest_register" as guest_register_url %}
{% include 'accounts/snippets/form.html' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %}
</div>
</div>
{% else %}
{% if not object.shipping_address %}
<div class="row">
<div class="col-12">
<p class="lead">Shipping Address</p>
<hr/>
</div>
<div class="col-6">
{% url "checkout_address_create" as checkout_address_create %}
{% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %}'
</div>
<div class="col-6">
{% url 'checkout_address_reuse' as checkout_address_reuse %}
{% include 'addresses/prev_addresses.html' with address_qs=address_qs next_url=request.build_absolute_uri address_type='shipping' action_url=checkout_address_reuse %}
</div>
</div>
{% elif not object.billing_address %}
<div class="row">
<div class="col-12">
<p class="lead">Billing Address</p>
<hr/>
</div>
<div class="col-md-6">
{% url "checkout_address_create" as checkout_address_create %}
{% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}
</div>
<div class="col-6">
{% url 'checkout_address_reuse' as checkout_address_reuse %}
{% include 'addresses/prev_addresses.html' with address_qs=address_qs next_url=request.build_absolute_uri address_type='billing' action_url=checkout_address_reuse %}
</div>
</div>
{% else%}
{% if not has_card %}
<!-- enter credit card here -->
<div class='stripe-payment-form' data-token='{{ publish_key }}' data-next-url='{{ request.build_absolute_uri }}' data-btn-title='Add Payment Method'></div>
{% else %}
<h1>Finalize Checkout</h1>
<p>Cart Item:{% for product in object.cart.products.all %}{{ product}}{% if not forloop.last %},{% endif %},{% endfor %}</p>
<p>Shipping Address:{{object.shipping_address.get_address}}</p>
<p>Billing Address:{{object.shipping_address.get_address}}</p>
<p>Cart Total:{{object.cart.total}}</p>
<p>Shipping Total:{{object.shipping_total}}</p>
<p>Order Total:{{object.total}}</p>
<form class="form" method="POST" action="">{% csrf_token %}
<button type="submit btn btn-success">Checkout</button>
</form>
{% endif %}
{% endif %}
{% endif %}
{% endblock %}

The problem appears to be in your CardManager declaration.
class CardManager(models.Manager):
def all(self, *args, **kwargs):
return self.get_queryset().filter(active=True)
active is not a field on the Card model, but rather on the BillingProfile FK from the Card model.
Change this to:
class CardManager(models.Manager):
def all(self, *args, **kwargs):
return self.get_queryset().filter(billing_profile__active=True)

That is likely to happen because you are trying to filter a queryset by an attribute its model does not have.
The model missing this attribute is the one having the attributes are shown to you by the traceback:
billing_profile, billing_profile_id, brand, country, default, exp_month, exp_year, id, last4, stripe_id.
that is, model Card.
Add something like:
active = models.BooleanField(default=True)
to Card model, then makemigrations, migrate, and it should work.

Related

Having a following followers problem in Django "too many values.."

I'm about to finish a Django based project, and the last step of this project is to build a followers/following feature. I can unfollow someone I've followed manually from the admin, but I can't follow someone from my html view. It misses me just one tiny thing to add into my html code but I'm really stuck. My code
My Model:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
CREATOR = "CREATOR"
SUBSCRIBER = "SUBSCRIBER"
ROLE_CHOICES = (
(CREATOR, "Créateur"),
(SUBSCRIBER, "Abonné"),
)
profile_photo = models.ImageField(upload_to='profile_photos/', default='profile_photos/default.png', blank=True, null=True)
role = models.CharField(max_length=10, choices=ROLE_CHOICES, default=SUBSCRIBER)
follows = models.ManyToManyField('self', related_name='followers', symmetrical=False)
My Views:
#login_required
def abonnements(request):
user = request.user
followers = user.followers.all()
follows = user.follows.all()
if request.method == 'POST':
if request.POST.get('follow'):
if request.POST.get('follow') == user.username:
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows, "error": "You can't follow yourself!"})
try:
followed_user = User.objects.get(request.POST.get('follow'))
except User.DoesNotExist:
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows, "error": "User does not exist"})
else:
print(followed_user)
elif request.POST.get('unfollow'):
user.follows.remove(User.objects.get(pk=request.POST.get('unfollow')))
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows, "success": "You are no longer following " + request.POST.get('unfollow')})
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows})
My HTML
{% extends 'base.html' %}
<title>{% block title %}Abonnements{% endblock %}</title>
{% block content %} {% include 'partials/_navbar.html' %}
<main class="corps_abonnements">
<section class="suivre">
<p class="suivre_utilisateurs_titre">Suivre d'autres utilisateurs</p>
<form method="post">
{% csrf_token %}
<input type="text" name="follow" value="">
<input type="submit" value="Envoyer">
</form>
</section>
<section class="abonnements">
<p color="red">{{ error }}</p>
{% if success %}<p color="green">{{ success }}</p>{% endif %}
<p class="abonnements_titre">Abonnements</p>
{% for user in follows %}
<div class="utilisateur_desabonner_container">
<p class="nom_utilisateur_desabonner">{{ user.username }}</p>
<form method="post">
{% csrf_token %}
{% if user in follows %}
<input type="hidden" name="unfollow" value="{{ user.id }}">
<button style="background-color:red;" type="submit" class="creer_critique_demande">
Se désabonner
</button>
{% endif %}
</form>
</div>
{% endfor %}
</section>
<section class="abonnes">
<p class="abonnes_titre">Abonnés</p>
{% for user in followers %}
<div class="utilisateur_abonne_container">
<p class="nom_utilisateur_abonne">{{ user.username }}</p>
</div>
{% endfor %}
</section>
</main>
{% endblock %}
So when I put the connected user name in the input, it returns me the error "you can't follow yourself", it means that my code is good
the message
but If I try to put the username of another user I want to follow, it raises me an error. Can someone help me please ?
ValueError at /abonnements/
too many values to unpack (expected 2)
Request Method: POST
Request URL: http://127.0.0.1:8000/abonnements/
views.py, line 155, in abonnements
followed_user = User.objects.get(request.POST.get('follow'))

How to solve NoReverseMatch?

Refer here for traceback****django throwing the error like this. Exception Value:Reverse for 'movie_details' with arguments '('',)' not found. 1 pattern(s) tried: ['movie\/(?P[0-9]+)\/$']
{% extends 'base.html' %}
{% block title %}
{{object.first_name}} - {{object.last_name}}
{% endblock %}
{% block main %}
<h1> {{object}} </h1>
<h2>Actor</h2>
<ul>
<p>hello</p>
{% for role in object.role_set.all %}
<li>
{{role.movie}}
</li>
{% endfor %}
</ul>
<h2>Writer</h2>
<ul>
{% for movie in objects.writing_credits.all %}
<li>
{{movie}}
</li>
{% endfor %}
</ul>
<h2>Director</h2>
<ul>
{% for movie in object.directed.all %}
<li>
{{movie}}
</li>
{% endfor %}
</ul>
{% endblock %}
codes in model.py
from django.db import models
class PersonManager(models.Manager):
def all_with_prefetch_movies(self):
qs = self.get_queryset()
return qs.prefetch_related('directed','writing_credits','roll_set__movie')
class Person(models.Model):
first_name = models.CharField(max_length=140)
last_name = models.CharField(max_length=140)
born = models.DateField()
died = models.DateField(null=True,blank=True)
objects = PersonManager()
Codes in views.py
class MovieDetail(DetailView):
model = Movie
queryset = Movie.objects.all_with_prefetch_persons()
class PersonDetail(DetailView):
queryset = Person.objects.all_with_prefetch_movies()
url mapping in urls.py
url pattern mentioned bellow
urlpatterns = [
path('movies/', MovieList.as_view(), name='movie_list'),
path('movie/<int:pk>/', MovieDetail.as_view(), name='movie_details'),
path('person/<int:pk>/', PersonDetail.as_view(), name='person_details'),
]

if same id is present in two tables show edit button else show assign button in django

Get all the employee profile table id and check the id with employee process,if id matches show edit button in templates else show assign button.
Views.py
def Employee(request):
emp = Emp_Profile.objects.filter(is_active=True)
emptable = Emp_Profile.objects.values_list('id')
print(emptable)
empprocess = Emp_Process.objects.values_list('username_id').distinct()
print(empprocess)
obj = {}
for i in range(len(empprocess)):
obj[i] = empprocess[i]
return render(request, 'employee.html',{'list' : emp,'empprocess':empprocess,'obj':obj})
templates
{% for list in list %}
{% if obj != list.id %}
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Edit</button></a>
</td>
{% else %}
<h6>welcome</h6>
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Assign</button></a>
</td>
{% endif %}
{% endfor %}
You can construct a set of username_ids and pass this to your template:
def Employee(request):
empS = Emp_Profile.objects.filter(is_active=True)
empprocess = set(Emp_Process.objects.values_list('username_id', flat=True).distinct())
return render(request, 'employee.html', {'emps' : emps, 'empprocess': empprocess })
In the template, we can then make a membership check of the set:
{% for emp in emps %}
<td>
{% if emp.id not in empprocess %}
<button class="btn btn-info">Edit</button>
{% else %}
<button class="btn btn-info">Assign</button>
{% endif %}
</td>
{% endfor %}
Note: you might want to rename your field username to user since a ForeignKey to a user is not the same as a username.
Note: please use {% url ... %} template tags [Django-doc] instead of performing URL processing yourself.

Query returning every cover in db for each entry?

My query seems to be returning 1 entry for each cover. That is, if I have 3 covers in the database, then the query will return entry #1 three times with each of the different covers. Since I have 7 entries, I'm getting 21 results. How do I structure my query to return the cover associated with the entry?
Here's what I have:
#app.route('/list', methods=['GET', 'POST'])
def list():
entries = Book.query.order_by(Book.id.desc()).all()
cvr_entries = Cover.query.filter(Cover.book).all()
### Other queries I've tried ###
# cvr_entries = Cover.query.join(Cover.book).all()
# cvr_entries = Cover.query.filter(Cover.book.any())
# cvr_entries = Cover.query.filter(Cover.book.any()).all()
return render_template(
'list.html',
entries=entries,
cvr_entries=cvr_entries)
Here's the /list output page:
{% for entry in entries %}
{% for cvr in cvr_entries %}
<article class="entry">
<img src="/static/data/covers/{{ cvr.name }}" alt="Cover for {{ entry.title }}" />
<ul class="entry-info">
<li class=""><h2>{{ entry.title }}</h2></li>
<li class="">Summary: {{ entry.summary|truncate( 30, true ) }}</li>
</ul>
</article>
{% endfor %}
{% endfor %}
Switching the order of the entries and cvr_entries for loops changes nothing. I've also tried adding first() instead of all(), but that leads to an error where it says
TypeError: 'Cover' object is not iterable
so that was a bust. I don't understand how to build the query.
Here is my model, as requested by #jonafato:
book_to_cover = db.Table('book_to_cover',
db.Column('cover_id', db.Integer, db.ForeignKey('cover.id')),
db.Column('book_id', db.Integer, db.ForeignKey('book.id'))
)
class Book(db.Model):
__tablename__ = 'book'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String())
summary = db.Column(db.Text)
book_to_cover = db.relationship('Cover', secondary=book_to_cover,
backref=db.backref('book', lazy='dynamic'))
def __repr__(self):
return "<Book (title='%s')>" % (self.title)
class Cover(db.Model):
__tablename__ = 'cover'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
def __repr__(self):
return "<Cover (name='%s')>" % self.name
Generally, you iterate over the model-- your relationships should allow you to do:
books = Book.query.all()
return render_template('list.html', books=books)
Then in your Jinja2 list.html template:
{% for book in books %}
<h3>{{ book }}</h3>
<ul>
{% for cover in book.book_to_cover %}
<li>{{ cover }}</li>
{% endfor %}
</ul>
{% endfor %}
It'd be more natural to rename the book_to_cover to covers to make it more like natural language when you access the model.

UnicodeDecodeError. While rendering the blob image

I am trying to add uploading images feature.
This class saves new entity:
class NewPost(Handler):
def render_newpost(self, title='' , content='', error = ''):
self.render("newpost.html", title = title, content = content, error = error)
def get(self):
user_cookie = self.request.cookies.get('user')
if user_cookie:
user_id = user_cookie.split('|')[0]
if hash_str(user_id) == user_cookie.split('|')[1]:
user = Users.get_by_id(int(user_id))
self.render_newpost()
else:
self.redirect('/')
def post(self):
title = self.request.get("title")
content = self.request.get("content")
image = self.request.get("file")
if title and content:
p = Posts(title = title, content = content)
p.image=db.Blob(image)
p.put()
self.redirect("/")
else:
error = "Enter both title and text"
self.render_newpost(title, content, error)
Here is my front page render class:
class Main(Handler):
def get(self):
posts = db.GqlQuery("SELECT * FROM Posts Order by created DESC LIMIT 10")
user_cookie = self.request.cookies.get('user')
if user_cookie:
user_id = user_cookie.split('|')[0]
if hash_str(user_id) == user_cookie.split('|')[1]:
user = Users.get_by_id(int(user_id))
self.render("front.html", posts = posts, user=user)
else:
self.response.headers['Content-Type'] = "image/jpeg"
self.render("front.html", posts = posts)
form to enter data:
<form method="post" enctype="multipart/form-data">
<div class="newpost">
<label>Image:</label>
<input type="file" name="file"/>
<div class="label">Title:
<input type="text" name="title" value="{{title}}"/>
</div>
<hr>
<div class="label">Content:
<textarea name="content">{{content}}</textarea>
</div>
</div>
<input type="submit"/>
<div class="error">{{error}}</div>
</form>
and here is my home page template: (The problem appears here!)
{% for post in posts %}
{% if post.image %}
<li><img src="/static/images/{{post.image}}"/>
{% endif %}
<h4>{{post.title}}</h4>
<p class="zoom">{{post.content}}</p>
{% endfor %}
App successfully stores image, but when it returns to the front page trying to render image it gives this error:
File "/home/wanhrust/google_appengine/newsite/templates/front.html", line 54, in top-level template code
{{post.image}}
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
I've been googling for several hours but without results. Any help?
The problem is that you are trying to embed an image in an html document which is not possible. Post.image is storing the bytes representing the image.
If you want to include the image in your html, you need to add something like this
{% if post.image_id %}
<li><img src="/image/{{post.image_id}}" />
{% endif %}
Where /image/ is a handler that returns the content of the image (setting the apprpriate content-type).
I also would recommend you to use the Blobstore API.

Resources