Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

Passing ID to Django URL

Good day Stack Overflow;

I want to use a url to access data from database base on the data's ID. I know there are duplicates of the same question here on SO but I cant seem to figure out something so basic. Hope you can help me with this.

Everything works out except on my template.

if I pass the url as:

<a href="{% url 'job_details' 5 %}">

It will get the Job with ID of 5. But if I use

<!--- <a href="{% url 'job_details' PropositionItem.id %}"> --->
<!--- 2nd href fixes the details --->
<a href="{% url 'job_details' id=jobItems.id %}">

It will return

Reverse for 'job_details' with arguments '('',)' not found. 1 pattern(s) tried: ['jobs/details/(?P<id>[0-9]+)$']

as Error Message.

My Model is something like this:

class PropositionItem(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey('users.Account', on_delete=models.CASCADE)
    job_title = models.CharField(max_length=100, default='', null=False)

urls.py

path('details/<int:id>', views.job_details, name='job_details'),

views.py

def job_details(request, id, *args, **kwargs):

context = {}
jobObj = PropositionItem.objects.get(id=id)
job_form = PropositionItemForm(
                                initial = {
                                    "job_title" : jobObj.job_title,
                                }
                            )
context['job_form'] = job_form

return render(request, 'jobs/job_form.html', context)

What should I write on my href?

EDIT

My detailsView right now changes with different ID. But my ListView is returning the same error message.

listView

@login_required(login_url='/login/')
def job_list(request, *args, **kwargs):

    context = {}
    jobItems = PropositionItem.objects.all().filter(created_by=request.user)
    context={
      'jobItems': jobItems
    }
    
    return render(request, 'jobs/job_list.html', context)

listURL

path('', views.job_list, name='job_list'),
question from:https://stackoverflow.com/questions/65880813/passing-id-to-django-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the problem is that you are not assigning the ID value, could you try

id=PropositionItem.id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...