'NoneType' object has no attribute 'DoesNotExist' - python

I would appreciate some help in receiving data from a database by viewing it in another page as you click onto the search button. The problem I am receiving is an AttributeError. after clicking into that button
I have tried to look at similar issues.
Views.py
def act_results(request):
'''
display the acts suitable for a particular user
'''
template = loader.get_template('polls/act_results.html')
try:
Act = request.GET.get('Act')
data = Act.objects.get(act__name=Act)
return HttpResponse(template.render({'Act':Act},request))
except Act.DoesNotExist:
return HttpResponse(template.render({'error_msg':'Act does not exist for this Festival'}))
models.py
class Act(models.Model):
name = models.CharField(primary_key=True,max_length=100)
stage = models.CharField(max_length=100)
start_time = models.TimeField()
end_time = models.TimeField()
date = models.DateTimeField()
def __str__(self):
return self.name
act_results.html
<table style="width:100%">
<tr>
<th>Acts available</th>
</tr>
<tr>
<td>Act : {{ Acts }}</td>
</tr>
</table>
{% endif %}
I expect to receive all the information about that act in the html page.
As of now I am receiving an error.

You've overwritten the name Act by assigning it to the result of the request.GET.get() call. Use a different name there.
Also you should be passing the result of the db lookup, not the request item, to the context. And template.render doesn't take the request as a second parameter. You should be using the standalone render shortcut anyway.
from django.shortcuts import render
...
def act_results(request):
value = request.GET.get('Act')
try:
item = Act.objects.get(act__name=value)
context = {'Act': item}
except Act.DoesNotExist:
context = {'error_msg':'Act does not exist for this Festival'}
return render(request, 'polls/act_results.html', context)
I don't know what the CSV has to do with anything, though. And the lookup filter is suspect; does your Act model have a relationship with another model via an act field? Seems unlikely. And your template should have {{ Act }}, not {{ Acts }}.
Honestly, the summary here is that you really need to take more care with your code.

Related

Django objects.get matching query does not exist

I'm trying to get all attributes of a single object. I keep getting a "Devices matching query does not exist." I just cannot figure out my issue.
Models.py
`class Devices(models.Model):
category_id = models.ForeignKey(Category, on_delete=models.CASCADE)
device_description = models.CharField(max_length=100)
device_status = models.CharField(max_length=50)
device_date = models.DateTimeField()
device_user = models.CharField(max_length=50)`
Views.py
def view_status(request, pk=None):
device = Devices.objects.get(pk=pk)
return render(request, 'homesite/device_status.html', device)
urls.py
url(r'^viewstatus/$', views.view_status, name='ViewStatus'),
here is the url I use to call http://localhost:8000/homesite/viewstatus/?pk=1
device_satus.html
{% extends "base.html" %}
{% block head %}
<title>Device Status</title>
{% endblock%}
{% block body %}
<h3>Device Status Detail</h3>
{{ devices.device_description }}
{{ devices.device_status }}
{{devices.device_date|date:"Y-m-d H:m:s"}}
{% endblock %}
There are 4 records in my able so I know there is a match for PK=1.
Note, that this is not the usual way to build an URL for accessing a specific object. Below I present first the approach that integrates pk in the URI and second the one passing pk as a parameter.
1. Approach
Here you put the pk in the URI and request something like http://localhost:8000/homesite/viewstatus/1/. If you do so, you need to adapt your urls.py by specifying what part of the URI is the pk you want:
# urls.py
url(r'^viewstatus/(?P<pk>\d+)/$', views.view_status, name='ViewStatus'),
The way you wrote the view is fine:
def view_status(request, pk=None):
if pk is not None:
device = Devices.objects.get(pk=pk)
else:
device = None
return render(request, 'homesite/device_status.html', {'device' : device})
Now, views.view_status will be called with both the request object and the pk as arguments and objects.get will behave as you expected, if the pk you put in the URI exists in you database.
Note that this is the preferred way to get an object.
2. Approach
In this case you pass the pk as a parameter, so call http://localhost:8000/homesite/viewstatus/?pk=1, for example. Now pk is a parameter of a GET request. In this case:
# urls.py
url(r'^viewstatus/$', views.view_status, name='ViewStatus'),
And the view only takes the request object as argument. Within the view you can get the pk as follows:
def view_status(request):
pk = request.GET.get('pk', None)
if pk is not None:
device = Devices.objects.get(pk=int(pk))
else:
device = None
return render(request, 'homesite/device_status.html', {'device' : device})
So in this case your view does not take any arguments other than the request object.
Another issue is in your view function: Django's shortcut render takes a dict object for the optional argument context. Currently you directly pass a Devices object. You need to update your return statement in view_status:
return render(request, 'homesite/device_status.html', {'device' : device})
Hope that helps!
I get an error 'Devices' object is not iterable
urls.py
this is how the url is set up.
url(r'^viewstatus/$', views.view_status, name='ViewStatus'),
but is should be like this
url(r'^viewstatus/(?P<pk>\d+)/$', views.view_status, name='ViewStatus'),
so that I can call like this correct? http://localhost:8000/homesite/viewstatus/1/
views.py
def view_status(request):
pk = request.GET['pk']
device = Devices.objects.get(pk=pk)
return render(request, 'homesite/device_status.html', device
so i need the corresponding views.py code to work with
http://localhost:8000/homesite/viewstatus/1/
I've stared at this for hours so I know I'm missing something simple.
Try changing your view function:
def view_status(request):
pk = request.GET['pk']
device = Devices.objects.get(pk=pk)
return render(request, 'homesite/device_status.html', device)
Let me know if it helps :)

Alternative way to return HTML as a read only field on the Django Admin

I have a Django admin class that contains a read only field which returns a table in HTML with 2 different links. The first link loads the page of all payments the user has sent, the second loads the page of all payments the user has received. In order to create this functionality, there is a need to return a lot of HTML. Is there an alternative to simply returning it?
Here is my current relevant code:
class UserAdmin(SimpleHistoryAdmin):
readonly_fields = ('payment_history')
def payment_history(self, obj):
return "<table style='border: none'>" \
"<tr><td><a href='/admin/payment/payment/?sender__id=%s'>Sent by this user</a></td>" \
"<td><a href='/admin/payment/payment/?receiver__id=%s'>Sent to this user</a></td>" \
"</tr></table>" % (obj.id, obj.id)
payment_history.allow_tags = True
A preferred alternative would be having this code in a real HTML file that can be returned by the same method.
How about using render_to_string? https://docs.djangoproject.com/en/1.9/topics/templates/#django.template.loader.render_to_string
templates/myapp/payment_history.html:
<table style='border: none'>
<tr>
<td><a href='/admin/payment/payment/?sender__id={{object.id}}'>Sent by this user</a></td>
<td><a href='/admin/payment/payment/?receiver__id={{object.id}}'>Sent to this user</a></td>
</tr>
</table>
admin.py:
from django.template.loader import render_to_string
class UserAdmin(SimpleHistoryAdmin):
readonly_fields = ('payment_history')
def payment_history(self, obj):
return render_to_string('myapp/payment_history.html', {'object':obj})

Django: Delete model object using template

I am currently using models to have users enter data, using templates (not admin) that is then stored, at which point the users can then see all the data they entered. I would like to also give users the ability to delete specific entries, this would be done using object ids to identify and delete specific objects.
Here is my views.py:
#login_required(login_url='/login/')
def fav(request):
context = RequestContext(request)
#This returns all of the data the user has entered
favorites_list = StockTickerSymbol.objects.filter(user=request.user).order_by('-added_date')
`
#This is to try to get the ID of every object in favorites_list and append it to a list
for obj in favorites_list:
stock_id = []
stock_id.append(obj.id)
#Here is where the form is processed to save the data the user has entered
if request.method == 'POST':
form = FavoritesForm(request.POST)
if form.is_valid():
stock = form.save(commit=False)
stock.user = request.user
stock.save()
return redirect(fav)
else:
print form.errors
else:
form = FavoritesForm()
context_dict = {'favorites': favorites_list, 'form':form, 'stock_id':stock_id}
return render_to_response('favorites/favorites.html', context_dict, context)
def delete(request, id):
stock_to_delete = get_object_or_404(StockTickerSymbol, pk=id).delete()
return redirect(fav)
Here is my urls.py:
url(r'^favorites/$', views.fav, name='favorites'),
url(r'^add_favorites/$', views.add_fav, name='add favorites'),
url(r'^delete/(?P<id>\d+)/$', views.delete, name='delete')
And this is the part of my template file responsible for deleting
{% for id in stock_id %}
<div align="right">Delete</div>
{% endfor %}
My problem with this code, is that the delete link in my template only gives the first object ID for all the links. For example if there are three submissions for the user, and there id's are 1,2,3. The delete link will read "/delete/1" for all the submissions, thus only allowing users to delete their first submission. Any idea on how I can solve this?
Your problem is here:
for obj in favorites_list:
stock_id = []
stock_id.append(obj.id)
You are reinitializing inside the loop.
Try this
stock_id = []
for obj in favorites_list:
stock_id.append(obj.id)
Note that you can also do:
favorites_list = StockTickerSymbol.objects.filter(user=request.user).order_by('-added_date')
stock_ids = list(facorites_list.values_list('id', flat=True)) #IMO - It is a good idea to name a list with plural for readability
Also, in your delete method - See if the user does have permission to delete the object. If not, anyone can hit this url with some random id and start deleting the objects in the database.
I would start off by adding the login_required decorator, followed by adding a created_by or attaching a group associated with the model, which need to be verified before allowing the user to delete the object.
EDIT
{% for fav in favorite_list %}
<div class="fav">
{{fav.name}}
</div>
Delete me
{% endfor %}
Now you can do away with the id list.

Django: How to return all models associated with a ForeignKey including all attributes of those models?

I have an app that I want to simply display all the URL links a page has associated with it when that page is visited.
It's similar to reddit in that there are many userpages (aka subreddits) and each page has an infinite possible amount of submitted links associated with it. The newlinkposts records are associated with a certain page via a ForeignKey.
Given a page, wow can I get all the related newlinkpost objects (including their corresponding likes, link comment, and post date) returned, in order to display them in a template?
My newlinkpost object is defined as follows:
class newlinkpost(models.Model):
newlink_tag = models.ForeignKey('userpagename') #tags link to which userpage it belongs to
link_comment = models.CharField(max_length=128) #comment to go along with post
post_date = models.DateField(auto_now=True, auto_now_add=False, null=False) #submission datestamp. later make it track editable posts if edit function is implemented
url = models.URLField(max_length = 1024, null=False) #actual submitted link
link_likes = models.IntegerField(null=False, default=0) #need to later create like button which will +1 the value
def __unicode__(self):
return self.url
When you add a ForeignKey within a model, as well as creating an attribute in the source model (in your case, newlinkpost) allowing you to find the one associated object, Django also creates a corresponding attribute inside the target model (in your case apparently userpagename).
By default this attribute is named after the source table, so in your case it will be newlinkpost_set.
That allows you to ask the question you're looking to answer: which newlinkpost objects have this userpagename?:
all_links = userpagename_instance.newlinkpost_set.all()
If you wish to apply additional filters, you can use the filter method instead:
some_links = userpagename_instance.newlinkpost_set.filter(...)
The newlinkpost_set attribute contains a RelatedManager object, which is a subtype of Manager, allowing you to use the same set of methods you could use on newlinkpost.objects, along with some additional methods allowing you to create new related objects.
Here's an example view using this technique: (this assumes you've got the model classes imported into the views module):
from django.shortcuts import render
def user_page(request, user_id):
page = userpagename.get(pk=user_id)
links = page.newlinkpost_set.all()
return render(
request,
"myapp/user_page.html",
{
page: page,
links: links,
}
)
...and here's an example of using that "links" variable in the template:
<ul>
{% for link in links %}
<li><a href="{{ link.url }}">{{ link.link_comment }} - {{ link.link_likes }} likes</li>
{% endfor %}
</ul>
You just use the reverse relationship.
my_userpagename.newlinkpost_set.all()

parse template tag to XML in Django

I am trying to print get some value from database and print into xml dynamically.
This is my model:
class Somemodel(models.Model):
Party_Id = models.CharField(max_length=500)
Label = models.CharField(max_length=500)
Party_Id = models.CharField(max_length=500)
Name = models.CharField(max_length=500)
This is my view function
def xmlcontent(request):
obj = Somemodel.objects.get(pk=1)
obj.Party_Id = obj.pk
pprint.pprint(obj.DDEX_Party_Id)
return render(request, "content.xml", {"DDID": "obj"},
content_type = "application/xhtml+xml")
My content.xml looks like this
<?xml version="1.0" encoding="UTF-8"?><br/>
<</MessageHeader>MessageHeader><br/>
{% for i in DDID %}<br/>
{{ i.pk }}<br/>
{% endfor %} <br/>
<</MessageHeader>/MessageHeader><br/>
Its suppose to print Party_id but not printing.. Am i miss something ?
A few problems:
You are sending the string "obj" instead of the object obj in your context dictionary.
In your xml template, you have a loop, but the context variable DDID is going to be a single object, not a collection or queryset, because you are using .get.
You have extra < in your XML, and XML does not include <br /> tags. The resulting file will be invalid.
To save yourself some trouble, just use the built-in serializers. The first example shows you how to export XML:
from django.core import serializers
def some_method(request):
XMLSerializer = serializers.get_serializer("xml")
xml_serializer = XMLSerializer()
xml_serializer.serialize(SomeModel.objects.filter(pk=1).values('id'), stream=request)
With this line
return render(request, "content.xml", {"DDID": "obj"},
you are passing string "obj" to template rather than the obj object. Update it to
return render(request, "content.xml", {"DDID": obj},
Also obj is not a list but single object, so you cannot use {%for i in DDID %} ...

Categories

Resources