Django: Multiple URL parameters - python

I'm making a study app that involves flashcards. It is divided into subjects. Each subject (biology, physics) has a set of decks (unitone, unittwo). Each deck has a set of cards (terms and definitions). I want my URLs to look like
localhost:8000/biology/unitone/ but I have trouble putting two URL parameters in one URL.
models.py
class Subject(models.Model):
subject_name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.subject_name
def get_absolute_url(self):
return reverse('card:index')
class Deck(models.Model):
deck_name = models.CharField(max_length=100)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
def __str__(self):
return self.deck_name
class Card(models.Model):
term = models.CharField(max_length=100)
definition = models.TextField()
deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
def __str__(self):
return self.term
views.py
class IndexView(generic.ListView):
template_name = 'card/index.html'
context_object_name = 'subjects'
def get_queryset(self):
return Subject.objects.all()
class SubjectView(DetailView):
model = Subject
slug_field = "subject"
template_name = 'card/subject.html'
class DeckView(DetailView):
model = Deck
slug_field = "deck"
template_name = 'card/deck.html'
urls.py
# localhost:8000/subjects/1 (biology)
url(r'^subjects/(?P<pk>[0-9]+)/$', views.SubjectView.as_view(), name='subject')
# localhost:8000/subjects/1/1 (biology/unitone)
url(r'^subjects/(?P<pk>[0-9]+)/(?P<pk>[0-9]+)/$', views.DeckView.as_view(), name='deck'),
The second URL in urls.py is what I'm having trouble with. It's not a valid URL.

You can't have multiple parameters with the same name. You have to give each parameter a unique name, e.g.:
url(r'^subjects/(?P<pk>[0-9]+)/(?P<deck>[0-9]+)/$', views.DeckView.as_view(), name='deck'),
In the DeckView you can then access them as self.kwargs['pk'] and self.kwargs['deck'].

there's a way by rewriting the DetailViews
urls.py
url(r'^subjects/(?P<subjects>\w+)/(?P<deck>\w+)/$', views.DeckView.as_view(), name='deck'),
views.py
class DeckView(DetailView):
model = Deck
# slug_field = "deck" # you don't need it
template_name = 'card/deck.html'
def get_object(self, subjects, deck):
subject_obj = Subject.objects.filter(subject_name=subjects).first()
obj = Deck.objects.filter(subject=subject_obj,deck_name=deck).first()
return obj
def get(self, request, subjects, deck):
self.object = self.get_object(subjects, deck)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
then access localhost:8000/subjects/biology/unitone/

Related

Django url path matching not working as expected

I have problem with Django model get_absolute_url reverse methods.
I have a url pattern that works perfectly but the problem for example
when I visit example.com/blog/python/first-post the path works perfectly, but
when I try a random path like, example.com/blog/python-randomr9353/first-post
it still works correctly even though it shouldn't because, python-randomr9353 is not
a valid path and it should return a page not found error.
Here is my code.
Models
class ArticleSeries(models.Model):
title = models.CharField(max_length=200)
series_slug = AutoSlugField(populate_from='title')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:article_list', kwargs={'series_slug': self.series_slug})
class Tag(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class Article(models.Model):
title = models.CharField(max_length=200)
article_slug = AutoSlugField(populate_from='title')
tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag')
series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug))
url patterns
app_name = 'blog'
urlpatterns = [
path('', views.IndexView.as_view(), name='index_view'),
path('blog', views.BlogView.as_view(), name='blog_view'),
path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'),
path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'),
]
Views
class IndexView(TemplateView):
template_name = 'blog/index.html'
extra_context = {}
class BlogView(ListView):
model = ArticleSeries
template_name = 'blog/blog_view.html'
context_object_name = 'series_list'
def get_queryset(self):
series = ArticleSeries.objects.all()
return get_list_or_404(series)
class ArticleListView(ListView):
model = Article
template_name = 'blog/article_list.html'
context_object_name = 'article_list'
def get_queryset(self):
slug = self.kwargs['series_slug']
articles = Article.objects.filter(series__series_slug=slug)
return get_list_or_404(articles)
class ArticleDetailView(DetailView):
model = Article
template_name = 'blog/article_detail.html'
context_object_name = 'article'
slug_field = 'article_slug'
slug_url_kwarg = 'article_slug'
def get_object(self, queryset=None):
slug = self.kwargs.get('article_slug')
return get_object_or_404(Article, article_slug=slug)
Try using path('blog/python/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail') in the urls.py instead of path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail').
EDIT:
At the point where you obtain the value of series_slug, validate this there itself.
...
validSeries = ['python', 'c', 'cpp', 'js'] # etc
if series_slug not in validSeries:
# Raise a page not found error

How to display recent posts in django

Here is the case, I need the last records of the model to be displayed on the page, for this I added a new pub_date record in the models to add to the queue of records, I also added this to views.py, and it kind of displays, but both records.
views.py code
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'
def description(self):
return self.description_text
def price(self):
return self.price_text
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
numbers = Number.objects.all()
context['numbers'] = numbers
return context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
avaibilitys = Avaibility.objects.order_by('-pub_date')
context['avaibilitys'] = avaibilitys
return context
models.py code
class Avaibility(models.Model):
name_text = models.CharField(max_length=200)
apply_text = models.CharField(max_length=200)
presence_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', null=True)
def __str__(self):
return self.name_text
def __str__(self):
return self.apply_text
def __str__(self):
return self.presence_text
this is what displays
You are just sorting the data using order_by and assign the sorted data to a variable:
avaibilitys = Avaibility.objects.order_by('-pub_date')
If you want to get only one of them, you can do this:
avaibilitys = Avaibility.objects.order_by('-pub_date').first()
EDIT
If you want the last one, do this:
avaibilitys = Avaibility.objects.order_by('-pub_date').last()

Django: Expected view likeList to be called with a URL keyword argument named "id"

Ive been trying to create an API that would return all objects from Like model however, I received an error (Expected view likeList to be called with a URL keyword argument named "id". Fix your URL conf, or set the .lookup_field attribute on the view correctly.).
Here is my model
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
objects = models.Manager()
image = models.ImageField(upload_to='post_pics')
def __str__(self):
return self.title
#property
def useremail(self):
return self.author.email
#property
def owner(self):
return self.author
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
def get_api_url(self, request=None):
return api_reverse('post-detail', kwargs={'pk': self.pk}, request=request)
def get_like_count(self):
return self.like_set.count()
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
Serializer
class likeserializers(serializers.ModelSerializer):
username = serializers.SerializerMethodField(read_only=True)
post_title = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Like
fields = ('id','created',
'user','username',
'post','post_title')
def get_username(self, obj):
return obj.user.username
def get_post_title(self, obj):
return obj.post.title
Views
class likeList(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'id'
serializer_class = likeserializers
def get_queryset(self):
return Like.objects.all()
URLS
urlpatterns = [
path('users/', API_views.userList.as_view(), name = 'users'),
path('users/id=<int:id>/', API_views.userListbyID.as_view(), name = 'usersid'),
path('posts/', API_views.postList.as_view(), name = 'post'),
path('posts/id=<int:id>', API_views.postListbyID.as_view(), name = 'postid'),
path('likes/', API_views.likeList.as_view(), name = 'likes'),
path('likes/id=<int:id>', API_views.likeListbyID.as_view(), name = 'likesid'),
path('follows/', API_views.followList.as_view(), name = 'likes'),
path('follows/id=<int:id>', API_views.followListbyID.as_view(), name = 'likesid'),
]
As per the error I should either fix my URL conf, or set the .lookup_field attribute on the view correctly. It works as intended if I change my URL conf however, if I use only lookup_field it fix the issue. I have completely the same view for posts and it works.
Post serializer:
class postserializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField(read_only=True)
like_count = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Post
fields = ('url','id',
'title','content',
'date_posted','author',
'useremail','like_count')
def get_url(self,obj):
request = self.context.get("request")
return obj.get_api_url(request=request)
def get_like_count(self,obj):
return obj.get_like_count()
def validate_title(self,value):
qs = Post.objects.filter(title__iexact = value)
#exclude the same instance
if self.instance:
qs = qs.exclude(pk=self.instance.pk)
#if title already exists raise error
if qs.exists():
raise serializers.ValidationError(f"Post with title '{value}' already exists")
return value
and post view:
class postList(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field = 'id'
serializer_class = postserializer
permission_classes = [IsOwnerOrReadOnly]
# permissions can be set up here as well + in settings.py
# permission_classes =
def get_queryset(self):
qs = Post.objects.all()
query = self.request.GET.get("q")
if query is not None:
qs = qs.filter(
Q(title__icontains = query)|
Q(content__icontains = query)
).distinct()
return qs
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
What am I missing? What is the difference between my post and like views/serializers which are causing this issue?

Django: How do you associate an Object_PK in the URL to the Foreign_Key relation field when creating a new object?

I am building an FAQ system. The models extend from Topic -> Section -> Article. When creating a new Article the User will select a Topic then a Section then the create Article button.
The url will look something like //mysite.org/Topic_PK/Section_PK/Article_Create
In Django it should look like this:
url(r'^ironfaq/(?P<pk>\d+)/(?P<pk>\d+)/article$', ArticleCreateView.as_view(), name=’article-create’)
What I am looking to do is to associate the Section_PK to the Article when the user submits the Article. I have the Section_PK in the URL I need help to figure out how to use it to do this.
Alternatively with this set up I can have a form rendered with a choice selection from the Section_FK in the Articles Model. If when creating the Article upon rendering the template if I could limit the Section choices by the Topic in the form.py this will also work for my needs
The url will look something like //mysite.org/Topic_PK/article/create
In Django the url should look like this:
url(r'^ironfaq/(?P<pk>\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’)
Both these methods require the Passing of the Topic or Section PK to the view or form thru the URL. If there is a better way to do this I am open to other suggestions.
In Django I have the following Models
class Topic(Audit):
name = models.CharField(max_length=255)
sort = models.SmallIntegerField()
slug = models.SlugField()
class Meta:
verbose_name_plural = "topics"
def __str__(self):
return self.name
def get_absolute_url(self):
return ('faq-topic-detail',(), {'slug': self.slug})
class Section(Audit):
name = models.CharField(max_length=255)
sort = models.SmallIntegerField()
slug = models.SlugField()
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "sections"
def __str__(self):
return self.name
def get_absolute_url(self):
return ('faq-section-detail',(), {'topic__slug': self.topic.slug,
'slug': self.slug})
class Article(Audit):
title = models.CharField(max_length=255)
sort = models.SmallIntegerField()
slug = models.SlugField()
section = models.ForeignKey(Section,on_delete=models.CASCADE)
answer = models.TextField()
vote_up = models.IntegerField()
vote_down = models.IntegerField()
view_count = models.IntegerField(default=0)
class Meta:
verbose_name_plural = "articles"
def __str__(self):
return self.title
def total_votes(self):
return self.vote_up + self.vote_down
def percent_yes(self):
return (float(self.vote_up) / self.total_votes()) * 100
def get_absolute_url(self):
return ('faq-article-detail',(), {'topic__slug': self.section.topic.slug,
'section__slug': self.section.slug, 'slug': self.slug})
Mysite Forms
class CreateArticleForm(forms.ModelForm):
class Meta:
model = Article
widgets = {
'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}),
}
fields = ('title','section','answer')
Mysite Views
class TopicCreateView(CreateView):
model = Topic
fields = ['name']
template_name = "faq/form_create.html"
success_url = "/ironfaq"
def form_valid(self, form):
topic = form.save(commit=False)
activity_user = self.request.user.username
activity_date = datetime.datetime.now()
topic.save()
return super(TopicCreateView,self).form_valid(form)
class SectionCreateView(CreateView):
model = Section
fields = ['name', 'topic']
template_name = "faq/form_create.html"
def form_valid(self, form):
section = form.save(commit=False)
activity_user = self.request.user.username
activity_date = datetime.datetime.now()
section.save()
self.success_url = "/ironfaq/%s/%s" % (section.topic.slug,section.slug)
return super(SectionCreateView,self).form_valid(form)
class ArticleCreateView(CreateView):
model = Article
form_class = CreateArticleForm
template_name = "faq/form_create.html"
def form_valid(self, form):
article = form.save(commit=False)
activity_user = self.request.user.username
activity_date = datetime.datetime.now()
article.save()
self.success_url = "/ironfaq/%s/%s/%s" % (article.section.topic.slug,article.section.slug,article.slug)
return super(ArticleCreateView,self).form_valid(form)
Let's say that you have this url
url(r'^ironfaq/(?P<topic_pk>\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’)
Where topic_pk will be pk of topic you want to be associated with your Article.
Then you just need to retrieve it in view. And this is done like this
class ArticleCreateView(CreateView):
model = Article
form_class = CreateArticleForm
template_name = "faq/form_create.html"
def form_valid(self, form):
article = form.save(commit=False)
# what are this variables for?
activity_user = self.request.user.username
activity_date = datetime.datetime.now()
# here we are getting 'topic_pk' from self.kwargs
article.topic_id = self.kwargs['topic_pk']
article.save()
self.success_url = "/ironfaq/%s/%s/%s" % (article.section.topic.slug,article.section.slug,article.slug)
return super(ArticleCreateView,self).form_valid(form)
All url params are stored in self.args and self.kwargs. Our topic_pk is named parameter and thats why we can get it by doing self.kwargs['topic_pk']
But be sure to validate existence of Topic with such pk before assigning it to your Article

Create lists in ListView from model field in django

I would like to use ListView to generate lists of degrees by school and state. For example, I would want to use to the degree_awarded field in the Program model to make a list of "Schools in Pennsylvania Where You Can Get A Bachelor Degree."
Models
class State(models.Model):
state_name = models.CharField(max_length=20, default='')
state_slug = models.SlugField()
def __str__(self):
return self.state_slug
class City(models.Model):
city_name = models.CharField(max_length=55, default='')
city_slug = models.SlugField()
state = models.ForeignKey(State, null=True)
def __str__(self):
return self.city_slug
class School(models.Model):
school_name = models.CharField(max_length=55, default='')
school_slug = models.SlugField()
city = models.ForeignKey(City, null=True)
def __str__(self):
return self.school_slug
def sorted_programs(self):
return self.program_set.all().order_by('program_name')
class Program(models.Model):
program_name = models.CharField(max_length=100, default='')
program_slug = models.SlugField(max_length=100, default='')
school = models.ForeignKey(School, null=True)
degree_awarded = models.CharField(max_length=10, default='')
def __str__(self):
return self.program_slug
Views
class SchoolIndexView(ListView):
model = State
def get_context_data(self, **kwargs):
context = super(SchoolIndexView, self).get_context_data(**kwargs)
context['state_list'] = State.objects.all().order_by('state_name')
return context
class ProgramInSchoolView(DetailView):
model = School
template = 'school_detail.html'
def get_object(self):
school_slug = School.objects.get(
school_slug=self.kwargs.get('school_slug')
)
return school_slug
def get_context_data(self, **kwargs):
context = super(ProgramInSchoolView, self).get_context_data(**kwargs)
context['school'] = self.object
context['program_list'] = self.object.program_set.all().order_by('program_name')
return context
class ProgramView(DetailView):
model = Program
template = 'program_detail.html'
def get_object(self):
program_slug = Program.objects.get(
program_slug=self.kwargs.get('program_slug')
)
return program_slug
def get_context_data(self, **kwargs):
context = super(ProgramView, self).get_context_data(**kwargs)
context['program'] = self.object
context['program_classes'] = self.object.classes_set.all().order_by('class_number')
return context
class DegreeView(ListView):
model = Program
template = 'degree_list.html'
def get_context_data(self, **kwargs):
context = super(DegreeView, self).get_context_data(**kwargs)
context['state_for_degree'] = State.objects.get(state_slug=self.kwargs.get('state_slug'))
context['city_for_degree'] = City.objects.get(city_name=self.kwargs.get('city_name'))
context['school_for_degree'] = School.objects.get(school_slug=self.kwargs.get('school_slug'))
context['degree_by_state'] = Program.objects.get(degree_awarded=self.kwargs.get('degree_awarded')).filter(school_slug=school_slug).filter(city_slug=city_slug).filter(state_slug=state_slug).order_by('city_name')
return context
Urls
url(r'^(?P<state_slug>[\w-]+)/$', CityInStateView.as_view(), name='state_detail'),
url(r'^(?P<state_slug>[\w-]+)/(?P<school_slug>[\w-]+)/$', ProgramInSchoolView.as_view(), name='school_detail'),
url(r'^(?P<state_slug>[\w-]+)/(?P<school_slug>[\w-]+)/(?P<program_slug>[\w-]+)/$', ProgramView.as_view(), name='program_detail'),
url(r'^(?P<state_slug<[\w-]+)/(?P<program_slug>[\w-]+)/$', DegreeView.as_view(), name='degree_list'),
I cannot figure out how to write the view and url routing so that I can use the information I already have in the degree_awarded field of the Program model to generate a list.
Can someone please point me in the right direction?
Thank you.
Edit: I've added the relevant model(s) that I left out before. I wanted to be concise. I've also added in the last filter that I tried. It is still not producing the degree lists sorted by state.
I don't think you need all that code in the get_context_data method. You should customize the list of objects to display in the get_queryset method.
class DegreeView(ListView):
model = Program
template = 'degree_list.html'
def get_queryset(self):
queryset = super(DegreeView, self).get_queryset()
# batchelors degrees only
queryset = queryset.filter(program_slug=self.kwargs['program_slug'])
# filter by state
queryset = queryset.filter(school__city__state__slug=self.kwargs['state_slug'])
return queryset
See the docs on lookups that span multiple relationships to explain the school__city__state__slug filter.
Then in your template, you can loop through the programs, for example:
{% for program in object_list %}
{{ program.degree_awarded %}

Categories

Resources