So, I'm working on a bar tab application in Django, and when it came down to insert some data into the tabs I'm getting the error:
ValueError at /tabs/345/add/Caipirinha/
invalid literal for int() with base 10: '345/add/Caipirinha'
I have tried some of the solutions provided before on Stackoverflow but with no success.
Here are some of my files:
models.py
class Tab(models.Model):
number = models.IntegerField()
name = models.CharField(max_length='50')
tabdate = models.DateTimeField('date created')
consumed = models.ManyToManyField(Product, through='ConsumedRelation')
def __unicode__(self):
return self.name
class ConsumedRelation(models.Model):
tab = models.ForeignKey(Tab)
product = models.ForeignKey(Product)
count = models.PositiveIntegerField(blank=True, null=True, default=1)
def __unicode__(self):
return str(self.tab) + " | " + str(self.count) + " " + str(self.product)
views.py
def addproduct(request, tabnumber, product):
tabnumber = Tab.objects.get(number=number)
productadd = Product.objects.get(name=str(product))
add = ConsumedRelation.objects.create(product=productadd, tab=tabnumber, count=1)
add.save()
context = {'tabnumber': tabnumber, 'product': productadd}
return render_to_response('addproduct.html', context, context_instance=RequestContext(request))
addproduct.html
{% for product in productlist %}
<a href="add/{{ product }}/"<li>{{ product }}</li></a>
{% endfor %}
urls.py
url(r'^tabs/add/(?P<tabnumber>\d)/(?P<product>\d)/$', 'barcomandas.views.addproduct'),
I appreciate the help!
You should be using {% url %} in your template so that Django generates the proper URL.
<a href="{% url 'barcomandas.views.addproduct' tabnumber=sometabnumber product=product %}"<li>{{ product }}</li></a>
Related
i am creating a new django eccomorce website now in product detail page here is my code
the problem is i cant see product name correct in html page problem with first()
when i use first then only product name showing but all products have same name i have 8 producs in my page eight product name same to first just like overwriting also i cant use for loop with first()
i will add some pics
urls.py
path('collection/<str:cate_slug>/<str:prod_slug>',views.product_view,name="productview"),
views.py
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0)):
if (Products.objects.filter(slug=prod_slug, status=0)):
products = Products.objects.filter(slug=prod_slug, status=0).first()
context = {'products':products}
else:
messages.error(request,"no such product found")
return redirect("collection")
else:
messages.error(request,"no such category found")
return redirect("collection")
return render(request,"product_view.html",context)
models.py
class Products(models.Model):
category = models.ForeignKey(Category,on_delete=models.CASCADE)
slug = models.CharField(max_length=150, null=False, blank=False)
product_name = models.CharField(max_length=150, null=False, blank=False)
product_image = models.ImageField( upload_to=get_image,null=True,blank=True)
description = models.TextField(max_length=500,null=False,blank=False)
original_price = models.IntegerField(null=False,blank=False)
selling_price = models.IntegerField(null=False,blank=False)
status = models.BooleanField(default=False,help_text="0=default , 1=Hidden")
trending = models.BooleanField(default=False,help_text="0=default , 1=Trending")
meta_title = models.CharField(max_length=150,null=False,blank=False)
meta_keyword = models.CharField(max_length=150,null=False,blank=False)
meta_description = models.CharField(max_length=400,null=False,blank=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.product_name
productview.html
{% block content %}
<h1>{{ products.product_name }} </h1>
{% endblock %}
i just want correct product name for every category i stucked here in morning helping are appreciated thank you all for helping till now
I think you need to loop through your produckts:
{% for product in products %}
<h1>{{ product.product_name }}</h1>
{% endfor %}
view:
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0).exists()):
if (Products.objects.filter(slug=prod_slug, status=0).exists()):
products = Products.objects.filter(slug=prod_slug, status=0)
context = {'products':products}
else:
messages.error(request,"no such product found")
return redirect("collection")
else:
messages.error(request,"no such category found")
return redirect("collection")
return render(request,"product_view.html",context)
Note that usually the model name is singular, so it should be class Products(models.Model):
I get this error:
ValueError at /product/
The QuerySet value for an exact lookup must be limited to one result using slicing.
this is my models :
class Categorie (models.Model):
title = models.CharField(max_length=50)
category_slug = models.SlugField(blank=True)
def __str__(self):
return self.category_slug
class Products(models.Model):
category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True,
related_name="product")
product_slug = models.SlugField(blank=True)
product_title = models.CharField(max_length=50 , null=True)
product_name = models.CharField(max_length=100 , null=True )
product_describe = models.CharField(max_length=200 , null=True)
product_picture = models.ImageField(upload_to='img_pro' , null=True)
product_created_at = models.DateField(auto_now_add=True)
product_updated_at = models.DateField(auto_now=True)
def __str__(self):
return self.product_slug
this is my view:
def index(requset):
category = Categorie.objects.all()
product = Products.objects.filter(category_slug=category)
context = {
'category':category,
'product ':product ,
}
return render( requset , 'product/index.html' , context)
this is my template:
{% for cat in category %}
<div class="fix single_content">
<h2>{{cat.title}}</h2>
<div class="fix">
{% for pro in product %}
<ul>
<li>
<div class="entry_name"><a href=""><img src="{{pro.product_picture.url}}" alt=""><span>
{{pro.product_title}}</span></a><h6>{{pro.product_name}}</h6></div>
</li>
</ul>
{% endfor %}
</div>
{% endfor %}
this is myapp.urls:
from django.urls import path
from . import views
urlpatterns = [
path('' , views.index , name='index' ),
]
Can anyone help me with that please?
in you index view you are passing a everything you have in vategory
category = Categorie.objects.all()
while it is expecting just one thing
category = Categorie.objects.get(id=pk) # pk or category_id or slug or whatever you named it in your url
so your view should look like
def index(requset,pk):
category = Categorie.objects.get(id=pk)
product = Products.objects.filter(category=category)
context = {
'category':category,
'product ':product ,
}
return render( requset , 'product/index.html' , context)
If you want to get products for a single category use this:
category = Categorie.objects.filter(category_slug='<slug-to-search>').first()
product = Products.objects.filter(category=category)
But if you want the product for multiple categories use this:
categories = Categorie.objects.all()
products = Products.objects.filter(category__in=categories)
I have a model called 'Competicion', with some objects and another model called 'Participante'. This second model has two fields: a foreignkey with the user and another foreingkey to 'Competicion'.
In the view, I've made queryset from 'Competicion' and with a for loop in the template I've given each object the button of the form.
With storing the user of the current session I have no problem but I want the form to know which object of the queryset it is to grab its id. #I have no problem with choices I just don't include them to save space
Models.py
class Competicion(models.Model):
ciudad = models.CharField(max_length=50, null=True, choices=Ciudades_a_elegir, default="Ninguna")
nombre = models.CharField(max_length=20, null=True, choices=Competiciones_a_elegir, default="Ninguna")
titulo = models.CharField(max_length=40, null=True)
fecha = models.DateField(null=True)
participantes = models.IntegerField(null=True)
flyer = models.ImageField(null=True, upload_to='imagenes', default='Ninguna')
def __str__(self):
return self.nombre + " " + self.titulo
class Participante(models.Model):
competicion = models.ForeignKey(Competicion, on_delete=models.CASCADE, null=True, blank=True)
participantes = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.competicion.nombre + " " + self.competicion.titulo
forms.py
class ParticipanteForm(ModelForm):
class Meta:
model = Participante
exclude = ['competicion', 'participantes']
views.py
def competiciones(request):
qs = Competicion.objects.all()
form = ParticipanteForm(request.POST or None)
if form.is_valid():
nombres = form.save()
nombres.competicion = ???#Help me
nombres.participantes = request.user
nombres.save()
return redirect('home')
context = {
'object_list':qs,
'form':form,
}
return render(request, "competiciones.html", context)
template
{% for i in object_list %}
<ul>
<li>{{i.nombre}}</li>
<li>{{i.ciudad}}</li>
<li>{{i.titulo}}</li>
<li>{{i.fecha}}</li>
<li>{{i.participantes}}</li>
{% if i.flyer %}
<img src="{{i.flyer.url}}" width="100px" >
{% endif %}
<li><form action="" method="POST">
{% csrf_token %}
<p> {{ form.competicion}} </p>
<p>{{form.participantes}}</p>
<input type="submit" name="Inscribirse" value="Inscribirse">
</form> </li>
</ul>
{% endfor %}
This is only like 1 course. In number one there is the different fields of the Competicion Model. And number two is the button of the form to the Participante Model, which fields are hidden and take the id of the course and the user. So I have a lot of these both courses displayed in the web. The function of the Particpante Model is to store the people who register in the course and the course itself.
def competiciones(request):
qs = Competicion.objects.all()
form = ParticipanteForm(request.POST or None)
if form.is_valid():
data = form.save()
data.participantes_id = request.user
for i in qs:
data.competicion_id = i.id
data.save()
return redirect('home')
I have a list of links made up of queryset objects. Clicking on each link should take me to that object's detail view. But I'm getting the following error:
NoReverseMatch at /idea_tracker/shoppinglist/
Reverse for 'views.recipient_detail' not found. 'views.recipient_detail' is not a valid view function or pattern name.
My model:
class Recipient(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birthday = models.CharField(max_length=10, blank=True)
notes = models.TextField(max_length=255, blank=True)
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
def get_absolute_url(self):
return reverse(
'views.recipient_detail',
args=(),
kwargs={'recipient_id': str(self.id)}
)
class Gift(models.Model):
name = models.CharField(max_length=30, blank=True)
model_number = models.CharField(max_length=30, blank=True)
price = models.DecimalField(default=0.00, decimal_places=2,
max_digits=6)
recipients = models.ManyToManyField(Recipient, blank=True)
purchased = models.BooleanField(default=False)
def __str__(self):
return "{}".format(self.name)
My views:
def shopping_list(request):
recipients =
models.Recipient.objects.prefetch_related('gift_set').\
all().order_by('last_name')
gift_list = models.Gift.objects.all()
total = []
for y in gift_list:
total.append(y.price)
total_price = sum(total)
return render(request, 'idea_tracker/shoppinglist.html', {
'recipients': recipients,
'total_price': total_price
})
def recipient_detail(request, pk):
recipient = get_object_or_404(models.Recipient, pk=pk)
gift = recipient.gift_set
return render(request, 'idea_tracker/recipient_detail.html', {
'recipient': recipient
})
My url:
urlpatterns = [
url(r'^shoppinglist/', views.shopping_list, name='shopping_list'),
url(r'^recipient_detail/(?P<recipient_id>)/$',
views.recipient_detail, name='recipient_detail'),
]
My template:
<h3> Click on a Recipient to edit or delete:</h3>
{% for name in recipients %}
<ul>
<li><a href="{{ name.get_absolute_url }}">{{ name.first_name }}
{{ name.last_name }} /
{% for gift in name.gift_set.all %}
<span style='color:darkblue'>{{ gift }}</span></a></li>
{% endfor %}
</ul>
{% endfor %}
You should use the name of the url pattern recipient_detail:
return reverse(
'recipient_detail',
args=(),
kwargs={'recipient_id': str(self.id)}
)
Your recipient_id group is empty. For example, you could match digits with:
url(r'^recipient_detail/(?P<recipient_id>\d+)/$',
views.recipient_detail, name='recipient_detail'),
Finally, you should change pk to recipient_id in your recipient_detail view to match the URL pattern.
Getting this error:
Reverse for 'step' with arguments '()' and keyword arguments '{'course_pk': 2, 'step_pk': ''}' not found. 1 pattern(s) tried: ['courses/(?P<course_pk>\\d+)/(?P<step_pk>\\d+)/']
/urls.py
...
url(r'^courses/', include('courses.urls', namespace='courses')),
...
/courses/urls.py
...
url(r'(?P<course_pk>\d+)/(?P<step_pk>\d+)/$', views.step_detail, name='step'),
...
Error during template rendering:
The html line generating the error is:
...
{{ step.title }}
...
courses/models.py
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
def __str__(self):
return self.title
class Step(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
content = models.TextField(blank=True, default='')
order = models.IntegerField(default=0)
course = models.ForeignKey(Course)
class Meta:
ordering = ['order', ]
def __str__(self):
return self.title
courses/views.py
def course_detail(request, pk):
# course = Course.objects.get(pk=pk)
course = get_object_or_404(Course, pk=pk)
return render(request, "courses/course_detail.html", {"course": course})
def step_detail(request, course_pk, step_pk):
step = get_object_or_404(Step, course_id=course_pk, pk=step_pk)
return render(request, "courses/step_detail.html", {"step": step})
I can't seem to understand where the problem is as I'm currently new to Django. Much help would be appreciated.
you need
{% url 'courses:step' course_pk=step.course.pk step_pk=step.pk %}
step.pk instead of step_pk which doesnot exist in your context
In the line
<a href=" {% url 'courses:step' course_pk=step.course.pk step_pk=step_pk %} ">
Here step_pk = step_pk is not working. Step_pk is not defined because you did not return any information about step_pk in def course_detail at this line:
return render(request, "courses/course_detail.html", {"course": course})
pass step inside return and use step_pk = step.pk
Please check it. Thanks.