Python Crash coursem Chapter 18 Pizzeria Project - Getting 'pizzas' is not a valid view function or pattern name - django-models

I am not able to get the 'pizzas' page template to render. The local environment is giving me an error that says: Reverse for 'pizzas' not found. 'pizzas' is not a valid view function or pattern name. Does anyone see the issue? My code is below. Thanks!
urls.py for project folder (pizzeria):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pizzas.urls')),
]
urls.py for app name (pizzas):
from django.urls import path
from . import views
app_name = 'pizzas'
urlpatterns = [
path('', views.index, name='index'),
path('pizzas/', views.pizzas, name='pizzas'),
]
models.py:
from django.db import models
class Pizza(models.Model):
"""Holds names of all pizza types, i.e. Hawaiian and Meat Lovers."""
name = models.CharField(max_length=200)
def __str__(self):
"""Return a string representation of the model."""
return self.name
class Topping(models.Model):
"""Toppings that beloong to specific types of pizzas."""
pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE)
text = models.TextField()
def __str__(self):
"""Return a string representation of the model."""
if len(self.name) > 50:
return f"{self.text[:50]}..."
else:
return f"{self.text}"
base.html:
<p>
<a href="{% url '>Pizzeria</a> -
<a href="{% url '>Pizzas</a>
</p>
{% block content %}{% endblock content %}
index.html:
{% extends "pizzas/base.html" %}
{% block content %}
<p>Pizzeria shows customers all pizza types and the toppings on each type.</p>
{% endblock content %}
views.py
from django.shortcuts import render
from .models import Pizza
def index(request):
"""The home page for Pizzeria."""
return render(request, 'pizzas/index.html')
def pizzas(request):
"""Show all pizzas."""
pizzas = Pizza.objects.all()
context = {'pizzas': pizzas}
return render(request, 'pizzas/pizzas.html', context)
pizzas.html:
{% extends 'pizzas/base.html' %}
{% block content %}
<p>Pizzas</p>
<ul>
{% for pizza in pizzas %}
<li>{{ pizza }}</li>
{% empty %}
<li>No pizzas have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
The homepage ('pizzas/index') was rendering and inheriting properly from base.html. But when I tried adding a new pizzas page I started getting the above error message on the homepage.

Related

how to pass django params in react components

i am new to react , i am building simple blog where user can post with title and body
in html its done with listview with:
{% for x in object_list %}
{% endfor %}
but in react component its not getting good result and showing error
here is my code:
models
class post(models.Model):
title = models.CharField(max_length=100)
body=models.TextField()
views
class list(ListView):
model = post
template_name = 'index.html'
post.js
function Post(){
return(
{% for x in object_list %}
{% endfor %}
)
}
in react what can i do to retreive data from model like we used to do in normal html, or show the object from model in components??

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

Photologue not showing images or thumbnails

I am not able to get photologue to show the images. What am I doing wrong?
development environment
django 2.1
python 3.5
osx, virtual_env, recent pip
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'mst/media/')
MEDIA_URL = "/media/"
urls
urlpatterns += [
...
url(r'^photologue/', include('photologue.urls', namespace='photologue')),
]
model
from photologue.models import Photo, Gallery
class PhotoExtended(models.Model):
photo = models.OneToOneField(Photo, on_delete=models.CASCADE, related_name='photo')
related_model = models.ForeignKey(MyModel, on_delete=models.CASCADE)
def __str__(self):
return self.photo.title
class GalleryExtended(models.Model):
gallery = models.OneToOneField(Gallery, on_delete=models.CASCADE, related_name='gallery')
related_model = models.ForeignKey(MyModel, on_delete=models.CASCADE)
def __str__(self):
return self.gallery.title
class based view
class MyModelList(ListView):
model = MyModel
template_name = "pictures.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['photos'] = PhotoExtended.objects.all()
context['galleries'] = GalleryExtended.objects.all()
return context
template (pictures.html):
{% block content %}
<ul>
{% for photoExtended in photos %}
<li>{{ photoExtended.photo.get_absolute_url }}</li>
<li>{{ photoExtended.photo.image }}</li>
<img src="/{{ photoExtended.photo.image }}" alt="{{ p.photo.title }}">
{% endfor %}
{% for gallery in galleries %}
<li></li>
{% endfor %}
shell response (per docs)
>>> from PIL import Image
>>>
notes
I migrated the database, and see the data in the database, and everything looks correct.
page renderings
photologue urls:
A single photo
the list of the photos
and the direct accessing of the image: (ra is the name in photologue, but em.jpeg is the file name)
and my view directly:
The template was wrong/outdated from an older version. Here is the correct usage in the template for an image within a list of images of type photologueExtended:
{% for photoExtended in photos %}
<!-- The link to the photologue template page with the photo and its gallery(s)-->
Link to page
<!-- The src link to the image thumbnail itself in the media url-->
<img src="{{ photoExtended.photo.get_thumbnail_url }}" />
<!-- The src link to the image itself in the media url-->
<img src="{{ photoExtended.photo.get_display_url }}" />
<!-- The photologue image's title/description/etc… -->
{{ photoExtended.photo.title }} <br>
{{ photoExtended.photo.description }} <br>
{% endfor %}
Also:
the url catchall in the main project urls.py was incorrect, and should be:
url(r'^$', indexView, name='indexView'),

FieldError at /cart/checkout/

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.

Filtering Django Databases

I am learning Django and am trying to filter names based off the database table: power_id. Is there anyway to filter based off power_id, or any variable in a database? Here is what I have so far. Note, I am using Twitter-Bootstrap
This is the Team View
<div class="accordion-inner">
<ul>
{% if User.object.power_id == 1 %}
<li>
<a href="#">
{{ user }}
</a>
</li>
{% endif %}
</ul>
</div>
Lets say, 1 is an Admin.
Here is my views.py:
# Home view
class home(generic.ListView):
template_name = 'users/home.html'
context_object_name = 'User_list'
context_object_name2 = 'Power_list'
def get_queryset(self):
return User.objects.order_by('username')
# Team view
class team(generic.ListView):
template_name = 'users/team.html'
context_object_name = 'User_list'
def get_queryset(self):
return User.objects.order_by('username')
context_object_name2 = 'Power_list'
def in_catagory(User, Admin):
return things.filter(Admin=Admin)
From what I can see, you have passed in a model that you have created called User. Now, I do not know if this is a model that you have actually created or if you are using django.contrib.auth.models.User. But, this is an attempt to show you how to work with views in django.
from django.views.generic import View
from django.shortcuts import render
from .models import User
class TeamView(View):
def get(self, request):
Users = User.objects.filter(power_id='123')
return render(request, 'something.html', {'Users': Users, })
What I've done here may look intimidating, but is actually quite simple. From what I can understand, you have a bunch of users, with an property called power_id. And you want to get that, you need to filter all your users for the users with the power_id that you want.
That is what the first line after the get function call does. the get function call is here because when you send a request to a page, like www.google.com, you are sending a get request.
Now, the render function is a shortcut function. What it does is this: first parameter is always request, the second parameter is the html file that you want it to render, and the third parameter is the information you are sending which is a dictionary.
Now coming to your template. You can simply loop through all your users, like so:
<div class="accordion-inner">
<ul>
{% for user in Users %}
<li>
<a href="#">
{{ user }}
</a>
</li>
{% endfor %}
</ul>
</div>
You can override the get_context_data method to add that other variable.
class TeamView(ListView):
template_name = 'users/team.html'
context_object_name = 'User_list'
model = User # You never set the model
def get_queryset(self):
return super('TeamView', self).get_queryset().order_by('username') # call the parent function
def get_context_data(self, *args, **kwargs):
context = super('TeamView', self).get_context_data(*args, **kwargs)
context['Power_list'] = self.get_queryset().filter(power_id=1)
return context
Now you also have a context variable Power_list with all of the users that have power_id == 1 that you can iterate over
<div class="accordion-inner">
<ul>
{% for user in Power_list %}
<li>
<a href="#">
{{ user }}
</a>
</li>
{% endfor %}
</ul>
</div>
I have found the answer to my own question. Turns out, it was much simpler than I thought it was. What I needed was to re-arrange the code, along with getting variables right.
<div class="accordion-inner">
<ul>
{% for name in User_list %}
{% if name.power_id == 1 %}
{{ name }}<br />
{% endif %}
{% endfor %}
</ul>
</div>
The views.py file didn't need to be edited at all.

Resources