I asked in past time about how generate an url with similar caracterist starting from an ID you said me that is better use slugs to do that. On this time I wanna generate dinamics urls with slugs. My objective is obtain this result:
I have five products that I named cards in models.py (Ysera, Neltharion, Nozdormu, Alexstrasza, Malygos). I need the respective url of each of the products:
localhost:8000/card/ysera
localhost:8000/card/neltharion
localhost:8000/card/nozdormu ... etc.
I try to generate these urls but i dont know if I made a good applying of commands, either I don't know how I can specify the id card like the main name of the card (ysera, neltharion...). I was trying to follow an answer posted here in this community a little blind and this is my "reconfiguration":
Here my views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
def shop(request):
tarj = card.objects.filter(status=True)
ctx = {'tarjetas':tarj}
return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))
def singleCard(request, slug, id):
try:
tarj = card.objects.get(slug=slug, id=id_tarj)
except ObjectDoesNotExist:
tarj = get_object_or_404(card, id=id_tarj)
return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))
My urls.py (I have an urls.py by app and the main urls.py):
url(r'^card/(?P<slug>[-\w]+)/(?P<id_tarj>\d+)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
My models.py:
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.nombre
My common template for all cards:
{% extends 'base.html' %}
{% block title %} Tarjeta {{card.nombre}} {% endblock %}
{% block content %}
<h1>{{ card.nombre }}</h1><br>
<p> {{ card.descripcion }}</p>
{% endblock %}
I don't know if my slug building in views.py was find, I'm convinced that the urls.py is bad but i don't know how build it?
please excuse me if I edit my own question to prolong it, Recently I'm trying to learn django by my side and I have many gaps in my learning
apologizeme in advance my extensive question and if I overlook something.
Thanks!!
This line:
tarj = card.objects.get(slug=slug, id=id_tarj)
tries to load a card object where the id field is set to is id_tarj and the slug field is set to slug. Your model does not have a field named slug. You will need to add one.
A good candidate for it would be a SlugField - https://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield
You will need to make sure that your slug field contains a proper value in each case.
Related
I'm having quite some troubles understanding how variables are passed to templates in Django, I'm new so keep this in mind.
My problem is that, when the URL is loaded data from databases can't be rendered except for the user(request.user.username) which is strangely loaded.
I even tried to declare variables inside the view's def but even them are not rendered
The model is imported inside the views.py.
My idea is that, since the user from request.user is loaded, there must be some problem with loading the database model, but this doesn't explain why even freshly declared variables inside the view's def are not passed.
In the /admin page all the models work fine.
Below are the fragments of my code, they should be enough to understand the problem, if not I can upload other parts.
Thank you in advance.
views.py:
def load_main(request):
diet_list = DietTable.objects.all()
return render(request, 'main/main.html',
{
'diet_list': diet_list,
'user': request.user.username,
})
part in the main.html:
<body>
...
<header>
...
</header>
...
{% block content %}
<strong>
{{ user }}
{% for element in diet_list %}
{{ element }}
{% endfor %}
</strong>
{% endblock %}
...
</body>
urls.py:
from django.urls import path, include
from main import views
urlpatterns = [
path('', views.load_main, name='main_view'),
]
models.py
...
class DietTable(models.Model):
diet_id = models.AutoField(primary_key=True) # to not use the default 'id; given by django
dietName = models.CharField(max_length=50)
dietType = models.ForeignKey(DietTypes, on_delete=models.PROTECT)
startDate = models.DateTimeField()
dayLength = models.IntegerField()
def __str__(self):
return str(str(self.dietName) + "(" + str(self.dayLength) + ")")
...
I'm working on a basic social media django project with the help of an udemy course. The following are the models i created:
group : models.py
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(allow_unicode=True,unique=True)
description = models.TextField(blank=True,default='')
description_html = models.TextField(editable=False,default='',blank=True)
members = models.ManyToManyField(User,through="GroupMember")
class GroupMember(models.Model):
group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE)
user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE)
post : models.py
class Post(models.Model):
user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
group = models.ForeignKey(Group,related_name='posts',null=True,blank=True)
And the part that does not make any sense to me is the following:
post_list.html
{% for member_group in get_user_groups %}
<a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name
}}</a></li>
{% endfor %}
{% for other_group in get_other_groups %}
{{ other_group.name }}</li>
{% endfor %}
What does "get_user_groups","get_other_groups" and "register = template.Library()" mean here and how are they related? Also what are they trying to achieve here? I'm clueless guys, help me out.
That's an example of custom template tags. There is probably a custom_tags.py file where you created the custom template tags within a folder called template_tags that shows the work being done to create the content of those tags.
get_user_groups isn't pulling from views.py or directly referencing your models.py. Instead, it's referencing queries stored in custom_tags.py
Find a detailed breakdown here:
https://medium.com/#hiteshgarg14/creating-custom-template-tags-in-django-application-7bd1dcfeb144
This can be useful if you want to display content from a query on a variety of different views without having to redundantly insert that query into multiple functions within views.py. In this case, it looks like it will be used to insert group membership information within a variety of views by using custom tags.
I have some problems to get the content out of the django database.
I'm a bloody beginner at django so I did some tutorials. They've worked fine. Now I want to reproduce them in my own project with own variables so I can see if I've understood all the stuff.
So to come to my problem I initalized my modules in models.py
from django.db import models
class Aboutme(models.Model):
author = models.CharField(max_length=30)
...
This works because I could add content to the database.
So there is no mistake.
Now in the views.py
from django.shortcuts import render
from portfolio.models import Aboutme
def portfolio_index(request):
aboutme = Aboutme.objects.all()
context = {'aboutme': aboutme}
return render(request, 'portfolio_index.html', context)
So finally in my HTML file, called portfolio_index.html, I call the content via
<h1>{{ aboutme.author }}</h1>
I guess it's right. But the content of author doesn't showup, so what did I miss?
I can call static files via django, so couldn't be something wrong with django...
Can anyone help.
Thanks in advance.
I think that you need to use a for loop to show "aboutme" because with "aboutme = Aboutme.objects.all()" you query a list of elements.
{% for aboutme_item in aboutme %}
<h1>{{ aboutme_item.author }}</h1>
{% endfor %}
So I'd like to think what I'm doing is fairly common. I'm attempting to display a result set using Django. I have looked online for a while and here is what I've come up with:
models.py{
from django.db import models
from django.conf import settings
class SalesRep(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Sales(models.Model):
seller = models.ForeignKey(SalesRep)
sold_on = models.DateField("Sold On")
}
sales_view.py{
from salesteam.models import SalesRep, Sales
from django.views.generic import ListView
class SellerHome(List View):
model = SalesRep
template_name = 'production/sales.html'
#property
def rep_sales(self):
return Sales.objects.filter(SalesRep=self)
}
sales.html{
<div id="total-sales">
{% for sale in SellerHome.rep_sales%}
<li>{{ sale.id }}</li>
{% empty %}
<li>You don't currently have any sales</li>
{% endfor %}
</div>
}
For the sake of completeness I even tried writing just the property out as Sales.objects.all() but still no luck. Thanks for taking a look as I'm fairly new to HTML, Django, and Python. Any help on what I'm doing wrong would be much appreciated. Let me know if you have any questions :)
I'm not sure what tutorial you've followed, but there is a lot of errors in your code... I'm assuming you would like to display all Sales for the logged in user?
In this scenario, I would change the model slightly to add a related_name to Sales foreign key to SalesRep:
class SalesRep(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Sales(models.Model):
seller = models.ForeignKey(SalesRep, related_name='sales')
sold_on = models.DateField('Sold On')
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ForeignKey.related_name
And I would change the views to use DetailView:
from django.views.generic import DetailView
class SellerDetailView(DetailView):
model = SalesRep
template_name = 'production/sales.html'
context_object_name = 'seller'
def get_object(self):
return self.request.user
Docs on DetailView — https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-display/#detailview
<div id="total-sales">
<ul>
{% for sale in seller.sales.all %}
<li>{{ sale.id }}</li>
{% empty %}
<li>You don't currently have any sales</li>
{% endfor %}
</ul>
</div>
First, I'd recommend avoiding class based views, at least as you are learning Django, since they are not really necessary and needlessly complicated for what you are doing.
Anyway, to answer your question using class-based views, your problem is in your template and your view. You'll want to put your rep_sales logic in a get_queryset, set the model to be Sales, not SalesRep, and then reference object_list in the template. More info.
However, I'd instead recommend writing a normal, function-based Django view. Something like this might get you started:
def view_all_sales(request):
my_sales_rep = SalesRep.objects.get(request.user)
all_my_sales = Sales.objects.filter(seller=my_sales_rep)
return render(request, "production/sales.html", {
"sales": all_my_sales
})
I've gone through quite a few django tutorials, and I'm finally getting ready to head out on my own. However, my first non-tutorial program is throwing an error, and I've been banging my head for a couple of days. I expect it to be a very noob problem, because, well, I am.
When I use this view
def todo(request):
latest_list = Item.objects.all()
return HttpResponse(latest_list)
I get
conquer djangocan I do this?learn thislearn this
which are the four items that populate the database. Not very handy since they are concatenated, and they don't appear to be handed off to the template.
When I change my view.py to try to talk to the template using
def todo(request):
latest_list = Item.objects.all()
return render_to_response,('index.html', {"latest_list", latest_list})
I get
'tuple' object has no attribute 'status_code'
Could it be that the model that's returning 'self.task' is limiting the return to only that field? Other tutorial I looked at seemed to return only one value (and returning just 'self' gets me a very similar error.
It could also be that I'm not passing in
Any help that would push me down the correct path would be greatly appreciated.
Greg
My model.py
from django.db import models
class Item(models.Model):
task = models.CharField(max_length=60)
taskNotes = models.CharField(max_length=600)
created = models.DateTimeField(auto_now_add=True)
done = models.BooleanField(default=False)
def __unicode__(self):
return self.task
My views.py
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponse
from myToDo.todo.models import Item
def todo(request):
latest_list = Item.objects.all()
return HttpResponse(latest_list)
My index.html (template)
{% if latest_list %}
<ul>
{% for task in latest_list %}
<li>{{ Item.task }}</li>
{% endfor %}
</ul>
{% else %}
<p>Looks like you're all done</p>
{% endif %}
return render_to_response,('index.html', {"latest_list", latest_list})
Remove that comma affer render_to_response and you should be ok. Reason: the comma makes the return value a tuple object, but need to return an HttpResponse object from a view.
You goofed on your return.
def todo(request):
latest_list = Item.objects.all()
return render_to_response('index.html', {"latest_list", latest_list})
Note the lack of comma after the function name.