I'm learning django, and I have a problem, I'm doing a virtual store and when I click on add a product to the shopping cart you should redirect me to another page, but can not find it, this is my code and my error:
django.template.exceptions.TemplateDoesNotExist: productos/carritocompras_form.html
detalle.html
<div class="fixed-action-btn" style="bottom:90px;">
<form action="{% url 'aniadir_carrito' %}" method="post">
{% csrf_token %}
<input type="hidden" name="usuario" value="{{request.user.pk}}">
<input type="hidden" name="produto" value="{{object.pk}}">
<input type="hidden" name="precio" value="{{object.precio}}">
<button class="btn-floating btn-large red pulse">
<i class="large material-icons">add_shopping_cart</i>
</button>
</form>
</div>
<div class="fixed-action-btn">
<a class="btn-floating btn-large red pulse">
<i class="large material-icons">add_shopping_cart</i>
</a>
<ul>
</ul>
</div>
url.py
from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from tienda.users.views import (
Indice, ListarProductos, DetalleProducto, ComentarioProducto, Ingresar, Salir, CambiarPerfil,
CarritoCompras, AniadirCarrito, ListarCarrito, ListarCarritoPendientes, ListarCarritoFinalizadas, EliminarCarrito
)
urlpatterns = [
path('', Indice.as_view(), name="indice"),
path("listado_productos", ListarProductos.as_view(), name="listado_productos"),
path("detalle_producto/<int:pk>/", DetalleProducto.as_view(), name="detalle_producto"),
path("crear_comentario/", ComentarioProducto.as_view(), name="crear_comentario"),
path("ingresar/", Ingresar.as_view(), name="ingresar"),
path("salir/", Salir.as_view(), name="salir"),
path("editar_perfil/", CambiarPerfil.as_view(), name="editar_perfil"),
path("aniadir_carrito", AniadirCarrito.as_view(), name="aniadir_carrito"),
path("listar_carrito", ListarCarrito.as_view(), name="listar_carrito"),
path("listar_pendientes", ListarCarritoPendientes.as_view(), name="listar_pendientes"),
path("listar_finalizado", ListarCarritoFinalizadas.as_view(), name="listar_finalizado"),
path("eliminar_carrito", EliminarCarrito.as_view(), name="eliminar_carrito"),
# Django Admin, use {% url 'admin:index' %}
path(settings.ADMIN_URL, admin.site.urls),
# Your stuff: custom urls includes go here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class AniadirCarrito(LoginRequiredMixin, CreateView):
model = CarritoCompras
fields = ('usuario','producto', 'precio',)
success_url = reverse_lazy('indice')
login_url = 'ingresar'
models.py
class CarritoCompras(models.Model):
producto = models.ForeignKey(Producto, related_name="producto_carrito", on_delete=models.CASCADE)
usuario = models.ForeignKey(get_user_model(), related_name="carrito_usuario", on_delete=models.CASCADE)
precio = models.IntegerField()
direccion = models.CharField(max_length=300)
datos_payu = models.CharField(max_length=600)
comprado = models.BooleanField(default=False)
pendiente = models.BooleanField(default=False)
def __str__(self):
return "{} {}".format(self.usuario)
Related
I'm currently using UpdateView to add edit functionality to my Django project. It's working correctly insofar as I can edit my data, however when I submit the new data, it returns a NoReverseMatch error:
NoReverseMatch at /MyHealth/edit/8
Reverse for 'health_hub_history' not found. 'health_hub_history' is not a valid view function or pattern name.
I've researched it and added a get_absolute_url to my model, but it isn't working. Any help would be appreciated!
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class HealthStats(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
weight = models.DecimalField(max_digits=5, decimal_places=2)
run_distance = models.IntegerField(default=5)
run_time = models.TimeField()
class Meta:
db_table = 'health_stats'
ordering = ['-date']
def get_absolute_url(self):
return reverse('health_hub_history')
def __str__(self):
return f"{self.user} | {self.date}"
urls.py:
from django.urls import path
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from . import views
app_name = 'HealthHub'
urlpatterns = [
path('', views.home, name='home'),
path('MyHealth/', views.health_hub, name='health_hub'),
path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
path('MyHealth/history', views.health_history, name='health_hub_history'),
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
path('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'),
path('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'),
]
Views.py:
class EditHealth(UpdateView):
model = HealthStats
template_name = 'health_hub_edit.html'
fields = ['weight', 'run_distance', 'run_time']
health_hub_edit.html:
{% extends 'base.html' %}
{% load static %}
{%load crispy_forms_tags %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>Edit my Data</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-signup btn-lg">Submit</button>
</form>
</div>
</div>
<div class="row justify-content-center">
</div>
</div>
{% endblock content %}
This error occurs because the django couldn't resolve the url
you didn't specify a primary key to base the query on.
you should modify this function
def get_absolute_url(self):
return reverse('health_hub_history', kwargs={'user': self.user})
also that health_history url is it a class based view you should add .as_view() to the end and observe camel casing
Lastly your url should observe the primary key specified
You can do this:
class EditHealth(UpdateView):
model = HealthStats
template_name = 'health_hub_edit.html'
fields = ['weight', 'run_distance', 'run_time']
def get(self, request):
return HttpResponse("health_hub")
def post(self, request):
# do something
return redirect("health_hub")
urlpatterns = patterns('',
url('', views.home, name='home'),
url('MyHealth/', views.health_hub, name='health_hub'),
url('^MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
url('MyHealth/history', views.health_history, name='health_hub_history'),
url('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
url('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'),
url('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'),
)
This will solve your problem
I found the answer to this issue here:
https://stackoverflow.com/a/48068932/19053957
Looks like all I need to do was refer to the app name prior to the name of the URL in get_absolute_url()!
I'm trying to get images for an object filtered by the object's id, but for now, I don't even see any request to it in my MySQL database. The snippets of my code are below.
models.py:
class Media(models.Model):
word = models.ForeignKey(Word, on_delete=models.CASCADE)
title = models.TextField(max_length=100, null=True)
image = models.ImageField(upload_to='images/')
views.py:
class MediaListView(generic.ListView):
model = Media
template_name = 'dictionaty_web/index.html'
context_object_name = 'images'
def get_queryset(self):
return Media.objects.filter(word=self.request.resolver_match.kwargs['pk'])
urls.py:
urlpatterns = [
path('languages/<int:pk>/', views.WordMapListView.as_view(), name='wordmaps'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
index.html:
{% for word in words %}
<div class="col-sm text-center">
<div class="card" style="width: 18rem;">
<img scr="{{ MEDIA_URL }}{{ image.image.url }}">
<div class="card-body">
<h5 class="card-title">{{ word.value }}</h5>
</div>
</div>
</div>
{% endfor %}
Your urls.py is also important when serving images in django.
do you have imported in your urls.py the following code
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
path('url/', name_of_view, name = 'url_name'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Here is my settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Here is urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('laxmi.urls')),
] + static(settings.MEDIA_URL, documents_root=settings.MEDIA_ROOT)
Here is my model:
class Services(models.Model):
title = models.CharField(max_length=250)
desc = models.TextField()
img = models.ImageField(upload_to='img')
def __str__(self):
return self.title
Views:
def index(request):
why_choose_uss = why_choose_us.objects.all()
servicess = Services.objects.all()
return render(request, 'laxmi/index.html', {'servicess': servicess, 'why_choose_uss':
why_choose_uss})
Template:
{% for services in servicess %}
<div class="col mb-4">
<div class="card">
<img src="{{services.img.url}}"class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{services.title}}</h5>
<p class="card-text">{{services.desc}}</p>
Lern More
</div>
</div>
</div>
{% endfor %}
And here is an image upload from admin pannel but its not shwoing in template
here it is model in admin panel
output in template
Try to substitute
<img src="{{services.img.url}}"class="card-img-top" alt="...">
with
<img src="{{services.img.url}}" class="card-img-top" alt="..." />
I am very new in Django. Not sure whether this is a bug or an error.
Here is my model in an app called gcbv (for generic class-based view)
from django.db import models
from core.models import TimeStampModel
from django.urls import reverse
# Create your models here.
class Vehicle(TimeStampModel):
maker = models.CharField(max_length=100)
model_year = models.IntegerField()
vehicle_type = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
vehicle_model = models.CharField(max_length=100)
website = models.URLField(max_length=100, blank=True)
email = models.EmailField(max_length=100, blank=True)
notes = models.TextField(blank=True, default='')
def __str__(self):
x = self.maker + ' ' + self.vehicle_model
return x
And here are the URLs:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from . import views
from django.urls import reverse
#from django.views.generic.base import TemplateView
app_name = 'gcbv'
urlpatterns = [
path('sub1/', views.SubView.as_view(), name='sub1'),
path('vehicle_list/', views.VehicleListView.as_view(),
name = 'vehicle_list'),
path('vehicle/<str:slug>/',
views.VehicleDetailView.as_view(),
name='vehicle_detail'),
path('vehicle/create', views.VehicleCreateView.as_view(),
name='vehicle_create'),
path('', views.IndexTemplateView.as_view(), name='index'),
]
And here is the relevant view:
class VehicleCreateView(CreateView):
model = Vehicle
fields = ['maker', 'model_year', 'vehicle_type', 'slug',
'vehicle_model', 'website', 'email', 'notes']
labels = {'maker':'Maker', 'model_year':'Year',
'vehicle_type':'Type', 'vehicle_model':'Model',
'website':'Website', 'email':'Email', 'notes':'Notes'}
Here is the template:
{% extends "core/base.html" %}
{% block body_block %}
<h1>Vehicle Create for GCBV</h1>
<form action="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-primary">Submit</button>
</form>
<h1>End Vehicle Create for GCBV</h1>
{% endblock %}
It looks as if the data aren't saved in the database, but when i'm adding the same data by hand directly in the admin page, everything works fine. I've attached another screenshot showing that VehicleDetailView has found the relevant template and rendered the information.
Any help would be greatly appreciated.
NB: Everything worked fine when I use function views and regex instead of path.
Form
After submit
List
Details
OK, this is what we septuagenarians call a "senior moment". I have been staring at this code for two days and did not see the obvious.
method="POST"!
NOT
action="POST"
Many, many thanks
In the fourth line of your template, method should be equal to "post"
{% extends "core/base.html" %}
{% block body_block %}
<h1>Vehicle Create for GCBV</h1>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-primary">Submit</button>
</form>
<h1>End Vehicle Create for GCBV</h1>
{% endblock %}
models.py
from django.db import models
class Blog(models.Model):
time = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length = 100)
slug = models.SlugField()
perex = models.TextField()
content = models.TextField()
#models.permalink
def get_absolute_url(self):
return ('blog', [self.slug])
def __unicode__(self):
return self.title
class Meta:
ordering = ['-time']
views.py
from django.shortcuts import render_to_response, get_object_or_404
from blog.models import Blog
def blog_entries(request):
blogs = Blog.objects.all()[0:3]
title = "Blogs"
return render_to_response('blog/blog.djhtml', {'blogs': blogs, 'title': title,})
def blog_single_entry(request, slug):
blog = get_object_or_404(Blog, slug=slug)
title = blog.title
return render_to_response('blog/single.djhtml', {'blog': blog, 'title': title,})
url.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'kablog.views.home', name='home'),
# url(r'^kablog/', include('kablog.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', 'blog.views.blog_entries', name='blog'),
url(r'^blog/(?P<slug>[-\w]+)/', 'blog.views.blog_single_entry', name='single_blog'),
)
template
{% extends 'base.djhtml' %}
{% block title %}| {{title}}{% endblock %}
{% block content %}
<div class="hero-unit">
<h1>Welcome to my Blog</h1>
<p>Where knowledge is always free</p>
<p>
<a class="btn btn-primary btn-large">
Read More
</a>
</p>
</div>
<div class="row">
{% for blog in blogs %}
<div class="span4">
<h2>{{blog}}<small>{{blog.time|date:"M D d Y"}}</small></h2>
<p>{{blog.perex|safe}}</p>
<a class="btn" href="{{ blog.get_absolute_url }}">
Read More
</a>
</div>
{% endfor %}
</div>
{% endblock %}
blog.get_absolute_url does not return a slug and also even though i have have try to browse "blog/my-first-blog" the browser just displays the home blog not the single_blog and it doesn't return a 404 error if you browse "blog/dgdsghdsfhdsfhds"
I also tried that but I can't make it work, so I try other approach
class Blog(models.Model):
[......]
#property
def get_blog_url(self):
return reverse('blog', args=[self.slug])
<a class="btn" href="{{ blog.get_blog_url }}">
Read More
</a>
You need to make #models.permalink instead #permalink.