I have created a model in my Djano project and the name of the model is Questions in which I have created a primary key called questionid. I am able to get all listings as summaries on one page however when I try to get a detailed listing of one query (say question number 4 out of the several in the table) by going to the http://127.0.0.1:8000/qanda/4 (here 4 is the question number), I get an error that says
TypeError at /qanda/4
question() got an unexpected keyword argument 'question_questionid'
Please see the code below
In my model's views file
def question(request):
questionsm = Questions.objects.order_by('-published_date').filter(is_published=True)
context = {
'questionid': questionsm
}
return render(request,'qanda/question.html', context)
In my model url file
path('<int:question_questionid>', views.question, name='question'),
I will appreciate any help. thanks
You are not passing the var to the view.
def question(request, **id_what_you_want**):
# and if you want an individual view, you should get by id
Questions.objects.get(pk=id_what_you_want)
Related
i want to show related posts by tag name However i got the error " get() returned more than one Tag -- it returned 2!"
def post_detail(request,slug):
post=get_object_or_404(Post,slug=slug)
comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')
comment_count=len(Comment.objects.filter(post=post, statusc=2))
tag=get_object_or_404(Tag,post=post)
related_item=Post.objects.filter(tag__tag_name__icontains=tag.tag_name,status=2).order_by('-created_date').distinct()[:3]
You can just query like:
def post_detail(request,slug):
post=get_object_or_404(Post,slug=slug)
comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')
comment_count=len(comments)
related_items = Post.objects.filter(
tag__post=post
).order_by('-created_date').distinct()[:3]
# ...
Or if you want to exclude the current post:
def post_detail(request,slug):
post=get_object_or_404(Post,slug=slug)
comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')
comment_count=len(comments)
related_items = Post.objects.exclude(pk=post.pk).filter(
tag__post=pos
).order_by('-created_date').distinct()[:3]
# ...
It is also better to perform a len(..) on the comments, since that will result in making a query to fetch the comments, whereas using two separate queries, will hit the database twice.
As per documentation, get() is used for retrieving 1 item. If there are multiple items, here there could be multiple tags used in single Post, it will throw error.
So, you can change it like this:
tags=Tag.objects.filter(post=post)
related_item=Post.objects.filter(tag__in=tags,status=2).order_by('-created_date').distinct()[:3]
I just started learning Django and Python a few weeks ago and have been tasked with a project to manage form processing using a Django/Python/MySQL combination. My background is in C++, so if there are any C++ analogies in Python/Django syntax please feel free to reference them.
So far I understand what the HTTPRequest objects do, but can't understand this snippet of code:
#login_required(login_url="/some_directory/")
def xyz(request):
item1 = request.GET['item1']
user = request.user
page = Page.objects.get(title = item1)
item1info = {}
perm_all = get_perms(user,page)
item1info["industry"] = page.industry.split(',')
For the first line what does "#" do? Is "#login_required" a Django command or was was it defined by the coder already?
I know "def xyz(request)" defines a function, but is the parameter "request" something that's been pre-defined in another file (urls.py)?
What does request.GET['item1'] do? Is it retrieving the value of the element "item1" from the query string?
"#" is a Decorator. Login required is a decorator provided by Django that requires the current user (in request.user) to be logged in to visit this view.
The "request" parameter is passed to the View function when its called, by Django itself. Any valid view function must receive the request as a paramete
Request.GET is a python dictionary that contains all the parameters passed in the request by GET method (as part of the URL querystring).
I was wondering what is the correct approach,
Do I create HiddenInput fields in my ModelForm and from the
View I pass in the primaryKey for the models I am about to edit into
the hiddenInput fields and then grab those hiddenInput fields from
the AJAX script to use it like this?
item.load(
"/bookmark/save/" + hidden_input_field_1,
null,
function () {
$("#save-form").submit(bookmark_save);
}
);
Or is there is some more clever way of doing it and I have no idea?
Thanks
It depends upon how you want to implement.
The basic idea is to edit 1. you need to get the existing instance, 2. Save provided information into this object.
For #1 you can do it multiple ways, like passing ID or any other primary key like attribute in url like http://myserver/edit_object/1 , Or pass ID as hidden input then you have to do it through templates.
For #2, I think you would already know this. Do something like
inst = MyModel.objects.get(id=input_id) # input_id taken as per #1
myform = MyForm(request.POST, instance=inst)
if myform.is_valid():
saved_inst = myform.save()
I just asked in the django IRC room and it says:
since js isn't processed by the django template engine, this is not
possible.
Hence the id or the object passed in from django view can't be accessed within AJAX script.
I have the following model:
class mark(models.Model):
title=models.CharField(max_length=35)
url=models.URLField(max_length=200)
user=models.ManyToManyField(User,blank=True)
and then I use a form to save some data to the db. My code inside the view that saves the data is:
new_mark= mark(url=request.POST['url'],
title=request.POST['title'],
user=request.user)
new_mark.save()
Of course I have all the data validation, login required validation, etc.
When I run this it throws me an unexpected
'user' is an invalid keyword argument for this function
on theuser=request.user) line. Any ideas what might be wrong?
Please provide the whole traceback and make sure your view has no function named "mark" etc (You probably also want to change mark to Mark to follow Python and Django style guides.) test via print type(mark) before the "new_mark = …" line.
Also I am not 100% sure if a ManyToMany field allows settings data like that, eg try:
new_mark= mark(url=request.POST['url'],
title=request.POST['title'])
new_mark.user.add(request.user)
new_mark.save()
And since it's an m2m field you probably want to rename the field to users.
I use django-tables2 to show some data in page,and now I want to make the cell link to some url,but the link url such as :
url(r'^(?P\w+)/(?P\d+)/$', 'pool.views.pooldatestock',
name="pool_date_stock"),
and I read the documents of django-tables2,but I can't find some excample about this problem.
the tables show in the page's url just like:http://127.0.0.1:8000/pool/20111222/
I try to write this in my tables.py :
class PoolTable(tables.Table):
number = tables.LinkColumn('pool.views.pooldatestock', args=[A('number')])
date = tables.Column()
and then I try to write:
class PoolTable(tables.Table):
number=tables.LinkColumn('pool.views.pooldatestock',
args=[A('date')],
kwargs=A('number')])
date = tables.Column()
but it's error too...
somebody can tell me how to solve this problem?or should I create my own table view, without django-tables.
Thanks.and Merry Christmas:)
It makes no sense for the kwargs parameter to be given a list, it should be given a dict. However as your URL doesn't used named groups, it doesn't need keyword arguments anyway. Just put both URL parameters in the args parameter:
class PoolTable(tables.Table):
number = tables.LinkColumn('pool.views.pooldatestock',
args=[A('date'), A('number')])
date = tables.Column()