0

Need help, Very new to Django.

I have created a model as below

class Redirect_url(models.Model):
    hosturl = models.CharField(max_length=100)
    path = models.CharField(max_length=100)
    redirectpage = models.CharField(max_length=200)

I need the hosturl, path and redirectpage as a variable in my views page for me to make some logic before I render to the html page. I don’t know

from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from .import models

def home(request):
    return render(request,'home.html')

def redurl(request):
    b = request
    data = (models.Redirect_url.objects.all())
    print(data)
    return HttpResponse(data, content_type="text/plain")

I am getting print as Redirect_url object (1)Redirect_url object (2). How to get all the models data. Thanks.

1
  • At the moment you are simply passing the result of models.Redirect_url.objects.all() (which is a QuerySet object) as the response. Python is simply trying to create a readable representation of this object, which in this case is "Redirect_url object (1)Redirect_url object (2)" (a list of the two objects in the QuerySet). You should instead either create and render a template that displays what you want the user to see, or you should create a more readable string Commented Feb 26, 2020 at 10:02

2 Answers 2

1

models.Redirect_url.objects.all() returns a list of QuerySets. You can iterate through the list with for loop and access the properties.

You can also add __str__() method in your model for better representation, see here.

You should check basic Django tutorial to understand it better.

Sign up to request clarification or add additional context in comments.

Comments

0
import json

data = Redirect_url.objects.all()
list = []
for record in data:
    dict = {'Host URL':record.hosturl,'Path':record.path,'Redirect Page':record.redirectpage}
    list.append(dict)
    list_as_json = json.dumps(list)
return HttpResponse(list_as_json)

Redirect_url.objects.all() will return queryset which contains number of obhects that we have stored in database by iterating over queryset you can get all objects one by one. you can do number of operations on queryset as below: django queryset

3 Comments

Are you sure this will work - passing list of dictionaries to response with setting the content type as text?
just giving example. Changed to json
I think you still need to exlicitly define the content type because browser may or may not guess what you respond with. Another thing is that OP mentioned this render to the html page so json will not help him much unless he suppose to use the endpoint with some JS code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.