Django built in server keep disconnecting when loading a template - python

I'm using Django built in server for developing a web application. Upon rendering a template for a specific web page, the server stop working without any log or warning on the console. It's just suddenly disconnected everytime i try to access that page.
After a while, i found out that if i remove a block of code which has the function of creating a dropdown list, the problem disappeared. But it's just a very simple code in order to get a list of departments, iterate it and make a dropdown list. I have seen other people do the same on the internet, so i have no idea why this is happening.
Here is the code of the view:
def edit(request):
departments = Department.objects.filter()
# I can iterate the QuerySet normally
for d in departments:
print(d.id, d.name, d.department_code)
return render(request, 'edit/edit.html', {'departments': departments})
and the block of code which creates a dropdown list:
<select name="department1" class="department">
<option value=""></option>
{% for d in departments %}
<option value="{{ d.id }}"> {{ d.name }} - {{ d.department_code }} </option>
{% endfor %}
</select>
Any help would be appreciated. Thank you.

I fixed the problem. I was using MysqlConnector API to connect to the database. I switch to mysqlclient instead and voilĂ , the server works beautifully now.
What i'm really mad about is i still don't know why that happened. The Django document simply said that you can use MysqlConnector API, there is no warning about any problem at all. The server also kept disconnecting without any trace or log, leaving me in the dark. It took me over 1 day of desperately debugging till i felt like there is something wrong with the connection to the database.
Anyway, thank you all for your helps, hope this can help somebody to avoid this problem as well.
P/S: It took me that long to recognized something wrong with the connection because i can still get the data from the database and print it on the console, so i didn't think there is any problem about that.

Related

Django - Is there any way to display multiple {% block content %} side by side?

First of all, I'm new to Python/Django in general. The problem I'm facing right now has been itching me for the past day, can't figure out how to make this work.
So, I'm trying to create a grid layout (using Bootstrap 4) where I would be able to show Movies/Shows which I have completed watching. The closest I found was a blog tutorial in Python/Django, did help me setup everything, from logging in to creating posts.
Now, the website is like a typical blog - everything gets stacked vertically, until it reaches a certain amount of posts, then you see the pagination. What I would like to do, is to display some sort of grid, here's a small example of how it looks now, and what I am trying to create:
[ col-md-9 ][ col-md-3 ]
In the above example, the {% block content %} and {% endblock %} fill in the col-md-9 section of the site, almost like a container-fluid. Ignore the col-md-3, the blog had it as a sidebar, which I don't really need.
What I'm trying to do would need to look something like this:
[col-md-3][col-md-3][col-md-3][col-md-3]
Not sure how to make the {% block content %} smaller and make it float correctly, because I managed to make it float (kinda?) with the display: -webkit-inline-box;, but sadly, I can't seem to make all the elements of a specific size and position them correctly in the [col-md-9].
I appreciate all the help that you guys can give,Thanks in advance.
Kind regards

Personalized/random URLs in Python/Django

I'm a Python beginner (and English language beginner too, by the way).
I just created a simple form in Python/Django that creates, edit and remove items.
I have HTML links that refers to my URLs like:
FILE.HTML:
<INPUT Type="BUTTON" VALUE="Edit" ONCLICK="window.location.href='/edit/{{ object.id }}/'">
URLS.PY:
url(r'^edit/(?P<id>\d+)/$', 'app.views.editobj'),
VIEWS.PY:
def editobj(request, id):
But of course, there's a problem, I wouldn't like people go direct on URL (only if the button was clicked) because somebody could just type on URL: /removeobj/1 and remove the object ID=1. What I would like to do is create differente URLs, maybe random, so the user would never guess what is the URL that the button will open, and of course, that it does work with the ID argument, so when it's goind to edit/remove, opens the right object.
I'm Hoping I was clear on my needs. Thanks.
Generating random URL's would be highly inefficient, not to mention unnecessarily difficult to implement. The common way to do what you are asking is to POST to a URL. I think you should do a little more reading on Django POSTing, as it will help you get a better understanding of what it does. In any case, here is an example of using this:
urls.py
url(r'^delete/$', 'app.views.delete_object', name="delete_obj"),
views.py
def delete_object(request):
""" Get the ID of an object via POST, then delete it. """
if request.method == 'POST' # This makes sure the request is a POST
obj_id = request.POST['obj_id']
obj = MODELNAME.objects.get(id=obj_id) # Use your model name here
# You can use if conditions here to make sure the object you just
# retrieved is allowed to be deleted by this user, or in general.
obj.delete()
messages.success(request, 'Object successfully deleted!')
return redirect(reverse('index')) # Make sure you use a name that exists
.html
<form method="POST" action="{% url 'delete_obj' %}">
{% CSRF_TOKEN %}
<input type="hidden" value="{{ obj.id }}" name="obj_id" />
<button type="submit">Submit</submit>
</form>
You can use more logic in the views.py to make sure that the object is allowed to be deletable, but for the most part, the code I wrote should give you somewhat of an understanding of the way to create a POST -> Delete Object workflow. Feel free to ask questions in the comment section below my answer.
The simplest way I see to do a "random" url would be to add a UUIDField (https://docs.djangoproject.com/en/1.8/ref/models/fields/#uuidfield or https://github.com/dcramer/django-uuidfield for Django <1.8) with a default to your model.
Your url can then become
url(r'^delete/(?P<uuid>[\da-f-]+)', 'app.views.delete_object', name='delete_obj')
uuid's are virtually impossible to guess.
Now if you don't add extra security to check that the user has the right to delete the object, anyone could still run a robot that would go through every single possible uuid and flush your database.
And if it is just a matter of not "guessing" #Hybrid's solution is probably a better starting point.

How to use <select> information in django form

So I have my django project which includes a HTML page that shows a list and a submit button.
I want to use the submit button to send the selected item ID to the server and than use it.
That`s my code :
<form>
<select>
{% for item in list %}
<option value={{item.name}}>{{ item.name }}</option>
{% endfor %}
</select>
<input type="submit"/>
</form>
The things I want to know are :
What to write in the action of the form so it will only reload the page.
How to enter the form data into a view.
As i understand, you want to take the value on your select and do something with it in the server.
I would advise you to read the documentation, as it is pretty detailed about what you need to know to work with forms. You should also read a little about forms, as you are missing a couple details.
Now, the action must point to one of your urls. Your url must be pointing to a view and in your view, if everything is ok, you should be getting a request object.
Depending on your post method, you have a python dictionary in request.GET or request.POST, filled with the values in your form.
That is assuming you are using your form created from scratch. In django you can use the Form class, which creates the html (or lets you create it, but giving you some constraints), validates the form, saves the form to a model (in the case it is a ModelForm). It is a valuable class for me and prefer it over working with raw html.
Also, assuming you haven't, i strongly advice you to go through the getting started. Even if it keeps things basic, it does a good job at introducing core django modules.

What does pk__in mean in Django?

Model.objects.filter(pk__in=[list of ids])
and
Model.objects.filter(pk__in=[1,2,3])
How do I show this data in a template?
def xx(request):
return HttpResponse(Model.objects.filter(pk__in=[1,2,3]))
It means, give me all objects of model Model that either have 1,2 or 3 as their primary key.
See Field lookups - in.
You get a list of objects back you can show them in the template like every other list, using the for template tag:
{% for object in objects %}
Some value: {{ object.value }}
{% endfor %}
To learn how to create a Django application you should read the tutorial or the Django book.
A tricky way to batch select (a best practice when dealing with a lot of data).
it would be faster than calling get/get_or_create in a loop due to the fact that only one SQL query is sent.
Try to time this :
Model.objects.filter(pk__in=[list of ids])
and this :
[Model.objects.get(pk=i) for i in ids]
Also note that running on your laptop there is minimal latency when django communicates with the database (production might be different).

Django Template if tag not working under FastCGI when checking bool True

I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI.
If I have a template as such:
{% with True as something %}
{%if something%}
It Worked!!!
{%endif%}
{%endwith%}
it should output the string "It Worked!!!". It does not on my production server with mod_fastcgi.
This works perfectly when I run locally with runserver.
I modified the code to the following to make it work for the sake of expediency, and the problem went away.
{% with "True" as something %}
{%if something%}
It Worked!!!
{%endif%}
{%endwith%}
It seems that the template parser, when running under FastCGI, cannot ascertain Truthiness (or Truthitude)[kudos if you get the reference] of bool variables.
Has anyone seen this? Do you have a solution?
Hmm... True is not a valid token in django template language, is it? I have no idea how it worked locally -- unless it's being added to the context with a non-zero value somewhere. Therefore, I think your second problem may not be related to the first one.

Categories