Reputation: 5654
I'm trying to retrieve user's created "Instances" db objects in views, I have successfully get and parsed for templates but in views I received complete object but not able to parse it, when I try to access it's models field it through an error as :
'QuerySet' object has no attribute 'name'
Here's my code: Instances/models.py
class Instance(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, related_name='instances')
name = models.CharField(max_length=255, name='name')
serverFile = models.TextField(default='', blank=False)
jsonPackageFile = models.TextField(default='', blank=False)
created_at = models.DateTimeField(default=timezone.now, editable=False)
class Meta:
ordering = ['-created_at']
Images/views.py
class BuildImage(LoginRequiredMixin, CreateView):
form_class = BuildImageForm
model = Image
template_name = 'images/buildImage.html'
success_url = 'user/gui'
def get(self, request, *args, **kwargs):
objectlist = request.user.instances.all()
return render(request, 'images/buildImage.html', {'form': forms.BuildImageForm,
'objectlist': objectlist})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
form = BuildImageForm(request.POST)
if form.is_valid():
data = form.cleaned_data
form.instance.user = self.request.user
form.instance.tagName = data['tagName'].lower()
instance_name = data['instance']
form.instance.instance =instance_name
# writeFiles(request, name=instance_name)
form.save()
img = request.user.instances.filter(name=instance_name)
print(img)
print(img.name)
else:
print(form.errors)
return HttpResponseRedirect(reverse('users:gui'))
print(img) display
<QuerySet [<Instance: Instance object>]>
in console.But print(img.name) throw an error as'QuerySet' object has no attribute 'name'
Upvotes: 0
Views: 229
Reputation: 618
Your code returns a queryset. You need change this :
img = request.user.instances.filter(name=instance_name)
For this:
img = request.user.instances.get(name=instance_name)
Upvotes: 2
Reputation: 9235
The error is because, img
is a queryset. If you want to print out the names, then do it in a loop,
for image in img:
print(image.name)
or,
print(img[0].name) #if you want the first instance's name.
Upvotes: 1