Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to control Python's stdout encoding under Apache/WSGI
I'm writing a Django app, and it prints Unicode to stdout. It works perfectly on the development server, but with Apache and modwsgi I get UnicodeEncodeError: 'ascii' codec can't encode characters .... So, the stdout encoding is forced to ASCII. I've found a number of solutions, all of which seem like they should work according to documentation, but none work for me: I tried setting the PYTHONIOENCODING variable to utf-8, using the SetEnv directive. I also tried setting LANG, LC_ALL, LC_CTYPE to en_US.UTF-8 using SetEnv and PassEnv. Finally, I tried adding lang=en_US.UTF-8 locale=en_US.UTF-8 to the WSGIDaemonProcess directive. The variables are seen in the environment (reflected e.g. on Django error pages in debug mode), but the error still occurs. Why don't these things work and what should I do? Overriding stdout in the code that works fine outside Apache or encoding everything manually doesn't feel like the right approach. Versions: Python 2.7.14, Apache 2.4.29, mod_wsgi 4.5.20 on Arch Linux -
Django Oauth2 Implicit Token Authorization Fail
I've written a chrome extension that uses Chrome's identity API to initiate a webauthflow with a Django Site I have made. Through a button in my extension, I am able to launch and interactive webflow, log into my site (supposedly), and receive an auth token the GET request to my site to receive user information. The main issue here though it that my server is not authenticating according to the profile that has just logged in through the app; it always autheticates to the admin. I am confused about how exactly to use all the different backends, middleware, etc. to get my desired flow: My current settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } AUTHENTICATION_BACKENDS = ( # Uncomment following if you want to access the admin 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', # '...', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] My Views.py @login_required() def secret_page(request, *args, **kwargs): if request.method == 'GET': receivedurl = request.GET.get('url') print(receivedurl) currentcacheduser = auth.get_user(request) return HttpResponse(currentcacheduser, … -
Ajax powered like button in Django
I have built the next architecture for the like button, but it does not work: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) archivo = models.FileField(upload_to='media/%Y/%m/%d', null=True, blank=True) slug= models.SlugField(default=0) likes = models.ManyToManyField(Perfil, related_name="likes") def __str__(self): return (self.titulo) @property def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): self.slug=slugify(self.titulo) super(Comentario, self).save(*args, **kwargs) views.py try: from django.utils import simplejson as json except ImportError: import json def like (request): if request.method=='POST': perfil=request.user slug=request.POST.get('slug', None) comentario=get_object_or_404(Comentario, slug=slug) if comentario.objects.filter(perfil__id=perfil.id).exists(): comentario.likes.remove(perfil_id) else: comentario.likes.add(perfil_id) context={'likes_count':comentario.total_likes} return HttpResponse(json.dumps(context), content_type='home/json') urls.py url(r'^like/$', login_required(views.like), name='like') .html <input type="button" id="like" name='{{ comentario_slug }}' value="Like" /> <script> $('#like').click(function(){ $.ajax("/home/like/",{ type: "POST", url: "{% url 'home:like' %}", data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(' likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) </script> When I push the button like it does not do anything. The console tells me: POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found) and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js Which is the problem? thank you for your help -
django - UNIQUE constraint failed: one_file.user_id
I am making a website in which user can upload files and those files are displayed in user's profile. I had displayed a file in user's profile but when I add 2nd file, it gives an error as: IntegrityError at /profile UNIQUE constraint failed: one_file.user_id models.py: class file(models.Model): title = models.CharField(max_length=250) file_type = models.CharField(max_length=12) description = models.TextField(max_length=6000) user = models.OneToOneField(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title views.py: def profile(request): if request.user.is_authenticated(): name= request.user.username form_class = file_form template_name = 'one/profile.html' content = file.objects.all() if request.method=='GET': form = form_class(None) return render(request,template_name,{'form':form,'name':name, 'content':content}) elif request.method=='POST': form = form_class(request.POST) if form.is_valid(): FILE = form.save(commit = False) FILE.user = request.user FILE.save() return HttpResponseRedirect('/profile') tempalte: logged in as: {{name}} <br> <a href="/logout">logout</a> <br> <form method="post" action=""> {% csrf_token %} {% include 'one/form-template.html' %} <button type="submit"> add file </button> </form> <br> <h3>my files</h3> {% for files in content %} <p>{{files.title}}</p> <br> {%endfor%} -
Django - Auto run scripts at certain time on Live Server
Newbie here. I have a lot of different functions in a Python program that downloads a bunch of data from the internet, manipulates it, and displays it to the public. I have bunch of links to different tables of data, and I figure it would be very inconvenient for people to have to wait for the data to download when they clicked the link on my website. How can I configure Django to run the scripts that download the data at say, like 6am? And save some type of cached template of the data so people could quickly view that data for the entire day, and then refresh and update the data for the next day. Your insight and guidance would be very appreciated! Thank you! and Happy holidays! -
Assistance with passing multiple objects via a list to Jsonresponse in Django
I have a code in Django where 5 random numbers are selected and then based on those 5 numbers 5 more queries are made from the database. One this is done I would like to pass all 5 objects from database to the template via json., however I am not sure how to proceed with this. This is what I have now: class multiplePull(TemplateView): template_name = 'gacha/multiplePull.html' def randomStar(self): choice = [5,4,3] probability = [0.1, 0.2, 0.7] star = random.choices(choice, probability) return star[0] def post(self, request): multi = [] characters = [] for x in range(5): star = self.randomStar() multi.append(star) for star in multi: character = Characters.objects.filter(stars=star).order_by('?')[:1] for obj in character: characters.append(obj) return JsonResponse(json.dumps(characters), safe=False) As it is now I get the following error: TypeError: Object of type 'QuerySet' is not JSON serializable How can I do this to make it work? I think I am missing something still but can't really find a solution. This works fine when I simply send this as context data but I don't know how to pass all 5 objects via Json. I would appreciate all help. Thanks you. -
Django Designing Models for Dating App Matches
I’m working on a dating app for a hackathon project. We have a series of questions that users fill out, and then every few days we are going to send suggested matches. If anyone has a good tutorial for these kinds of matching algorithms, it would be very appreciated. One idea is to assign a point value for each question and then to do a def comparison(person_a, person_b) function where you iterate through these questions, and where there’s a common answer, you add in a point. So the higher the score, the better the match. I understand this so far, but I’m struggling to see how to save this data in the database. In python, I could take each user and then iterate through all the other users with this comparison function and make a dictionary for each person that lists all the other users and a score for them. And then to suggest matches, I iterate through the dictionary list and if that person hasn’t been matched up already with that person, then make a match. person1_dictionary_of_matches = {‘person2’: 3, ‘person3’: 5, ‘person4’: 10, ‘person5’: 12, ‘person6’: 2,……,‘person200’:10} person_1_list_of_prior_matches = [‘person3’, 'person4'] I'm struggling on how to represent this … -
How to filter the options for a ForeignKey based on an other ForeignKey
I need to filter the options for a ForeignKey based on an other ForeignKey. class LabValue(models.Model): measurement = models.ForeignKey( 'LabMeasurement', on_delete=models.CASCADE) unit = models.ForeignKey( LabMeasurementUnit, on_delete=models.CASCADE, limit_choices_to={'parameter__id': self.measurement.parameter.id}, ) How can I retrieve self.measurement.parameter.id? If I manually enter an ID like for example "1" the query works. -
Designing code for proper error handling in a Django / Python app?
I'm in the midst of building a Django app and am hoping to get some advice on the proper way to handle errors and bugs in my code. Here's a common situation exemplary of the problems I have: a user purchases a product. To process the purchase, my views need to perform a number of actions: First, the view should create a User object in the database. If that is successful, the view should create an Order object and assign it to the newly-created User. If that is successful, my code should create a Product object and add it to the newly created Order. This is all well and good when no errors occur - but I find that the occasional error is inevitable in my code, and I want my app to deal with errors gracefully, rather than crashing outright. For example, if, for any reason, an Order object cannot be created, the view should show the user an error and remove the User object that was previously created. And, it should throw a graceful error message rather than crashing outright and serving the user a Http 500 error. The only way I can think of to do this … -
model messages on django
I create model for messages , user can have many read messages. Message can read many users. Is similar to group chat in slack. class Message(models.Model): user = models.ForeignKey(User) users_read = models.ManyToManyField(User, related_name='read_messages') date_created=models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=500) Right i make references in my models? sorry for my english, i learning him -
What are the benefit of Python Django?
I would like to know some of the benefits of using Python Django? This can include security features, ease of use or any other aspect that make Django stand out. -
How to solve faceook/linkedin Authentication process canceled error?
I have a project in AWS cloud9, when i tryed to login via LinkedIn or Facebook (i write my code in python and i use Django v1.8.4). After i Press the button "allow access" to my LinkedIn or Facebook account i get this error page: facebook linkedin Traceback: Environment: Request Method: GET Request URL: http://8011118167a14663bf26f276beae74fe.vfs.cloud9.us-east-2.amazonaws.com:80/complete/facebook/?redirect_state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR&code=AQCHwhQV29jyqzxZ8_qtAQD6D_baKZvcdaMOL889co7q6N_rerhEvteJ3-1iE-vIhyX87qAHfCTN4XgoFF0IQT_MyWHsIf28ggfZt3IqUMXFODBsXaYY_PJJCvDRniv20gqMF9Pq1Lm2L1x-OFAOsqLsIboYZDrmG6ceFpADyzdKOXZRsy44uiXKhZIzht3VI45je8JbWowZJa-YUcRD1zY5OQnniW5ujq3IYe2l0z6nha6hq7Lk0lzLD5BR4I5O9sd7CdMxeRXX0NBmc9Qz4av2j2xsiHQq9zBASy03dSwENwQ2veIOhpQCMrIkkXwfNGQ&state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR Django Version: 1.8.4 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_social_project', 'django_social_app', 'social.apps.django_app.default', 'facebook_auth') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/apps/django_app/utils.py" in wrapper 51. return func(request, backend, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/apps/django_app/views.py" in complete 28. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/actions.py" in do_complete 43. user = backend.complete(user=user, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/backends/base.py" in complete 41. return self.auth_complete(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/utils.py" in wrapper 232. raise AuthCanceled(args[0]) Exception Type: AuthCanceled at /complete/facebook/ Exception Value: Authentication process canceled I saw How to solve Authentication process canceled error? but It does not work. -
Having problems with a query in Django
I'm building my first app within Django and I'm trying to query a "load" based on the company that i've attached to the load. Here's the model in question. class Load(models.Model): company = models.ForeignKey(UserCompany, null=True, on_delete=models.CASCADE) load_number = models.IntegerField() carrier = models.CharField(max_length=255) pickup_date = models.DateField() delivery_date = models.DateField() shipper = models.CharField(max_length=255) consignee = models.CharField(max_length=255) po_number = models.CharField(max_length=255) pu_number = models.CharField(max_length=255) pieces = models.IntegerField() description = models.TextField() date_created = models.DateTimeField(blank=True, null=True) def publish(self): self.date_created = timezone.now() self.save() def __str__(self): return str(self.load_number) Now I'm trying to display a list on a page, but only display the loads attached to a specific company. The user needs to be attached to that company as well so here are my user models. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class UserCompany(models.Model): company_name = models.CharField(max_length=200) def __unicode__(self): return self.company_name def __str__(self): return self.company_name # User Model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Additional Classes profile_pic = models.ImageField(upload_to='profile_pics', blank=True) company = models.ForeignKey(UserCompany, null=True,on_delete=models.CASCADE) def __str__(self): return self.user.username Then i'm trying to query the "loads" within this view. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404 … -
Deploying app on Heroku (code=H10 desc="App crashed") Issue
I tried to deploy my app on heroku, but somehow I got this error page. I've run "$ heroku logs" on terminal and got the following messages. 2017-12-23T16:14:37.940528+00:00 heroku[router]:at=error code=H10 desc="App crashed" method=GET path="/" host=www.textory.tw request_id=79f89451-07b7-45b8-bf6d-1230092bcc1a fwd="123.193.63.120" dyno=web.1 connect=5001ms service= status=503 bytes= protocol=https 2017-12-23T16:14:38.308115+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.textory.tw request_id=520f0dab-1a19-42ed-bee5-60846b6c7631 fwd="123.193.63.120" dyno= connect= service= status=503 bytes= protocol=https Here is my Procfile web: gunicorn textory.wsgi VENV *.pyc __pycache__ staticfiles db.sqlite3 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") STATICFILES_STORAGE ='whitenoise.storage.CompressedManifestStaticFilesStorage' -
Why do we pass request as a parameter in the render method of django?
I have noticed that when using the render() function, we pass request as the first parameter, what's the use of this? Also, can somebody explain using an example, when would it be necessary to use render() function instead of render_to_response() function for rending templates? -
How do Meta field names correspond to model attributes
I am writing a Django Model and different Forms to modify the model's data. For simplification let's say my model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField() # (...) some other properties __identity_card_front = models.FileField(blank=True) class IdentityCardForm(forms.ModelForm): class Meta: model = Profile fields = ('__identity_card_front',) My question is: must the fields names correspond to the attributes of Profile class (the exact name of the variables definition)? Do these strings determine the HTML form field name that will be searched in form validation? And if so, how can I customise it? I don't want to have to obligatorily call my field name '__identity_card_front', but instead maybe something like 'id_front', 'idf', etc. I have seen labels might be used, but I was not clear how Django treats fields tags. I could not find either a good explanation on the Docs without getting lost around low-level class definitions and properties. Note: I am using django-2.0 -
How to dynamically delete object using django formset
Imagine E-commerce shop. User opens his cart (order), sees products, want to delete a few. The question is how to delete it dynamically using ajax. here we render template with two "elements" - ORDER (order_form) which contains customer's information and SET_OF_ORDERED_ITEMS (formset) views.py def show_cart(request): OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=0, can_delete=True) order = Order.objects.get(pk=request.session['order_id']) if request.method == 'GET': order_form = OrderForm(instance=order) formset = OrderItemFormSet(instance=order) return render(request, 'ordersys/cart.html', {'order_form': order_form, 'formset': formset}) elif request.method == 'POST': filled_form = OrderForm(request.POST, instance=order) filled_formset = OrderItemFormSet(request.POST, instance=order) if filled_form.is_valid() and filled_formset.is_valid(): filled_form.save() filled_formset.save() return redirect('catalog:index') else: return render(request, 'ordersys/cart.html', {'order_form': filled_form, 'formset': filled_formset}) template cart.html <form action="... > {{ formset.management_form }} # set of ordered_item forms {% for ordered_item_form in formset %} {{ ordered_item_form.id }} {{ ordered_item_form.instance.name }} {{ ordered_item_form.quantity }} <button type="button" onclick="delete_item_with_ajax();"> DELETE </button> {% endfor %} ... # here i render order_form's fields such as ADDRESS, PHONE_NUMBER... but it is not important for our example ... <button type="submit"> SUBMIT </button> </form> If user press "DELETE" button, it removes ordered_item_form element from the DOM and calls ajax function which passes ID of removable item to the function, which unties ordered_item from the order by deleting it from database. views.py def delete_order_item(request): … -
Django: how to send form data from one page to the next?
The basic problem is that I can not find out a way of taking the form data to pass on to the next page? Extra information: I read somewhere that I should use session, which seems sensible, however, serialization appears not to work with forms without a model, however, I could be wrong. When I click submit the error is 'AttributeError: 'BoundField' object has no attribute '_meta'. Form class ItemCounterForm(Form): item = CharField(max_length=30) counter = IntegerFeild(min_value=1, max_value=1000) def __init__(self, *args, **kwargs): super(ItemCounterForm, self).__init__(*args, **kwargs) View class ItemCounterView(View): FormSet = formset_factory(ItemCounterForm) def get(self, request, *args, **kwargs): context = { 'form': self.FormSet() } return render(request, 'app:template', context) def post(self, request, *args, **kwargs): form = self.FormSet(self.request.POST or None) if form.is_valid(): for single_form in form: data_form = serializers.serialize('json', single_form) request.session['form'] = data_form return HttpResponseRedirect(reverse_lazy('app:next_page') else: context = { 'form': self.FormSet() } return render(request, 'app:template', context) Thank you for your time. -
Configuring a uwsgi.ini file so that a DJango project will work within a Docker container
I am trying to set the uwsgi.ini file so that it will work with a docker container. In the Dockerfile, I have exposed port 8888. Below are the pieces of the Dockerfile that are related to this problem: Dockerfile EXPOSE 8888 ENV DOCKER_CONTAINER=1 #CMD ["uwsgi", "--ini", "/code/uwsgi.ini"] <<< right now, this is commented out CMD ["/bin/bash"] Above, the CMD to run the uwsgi.ini file is commented out because, for me, it did not work initially. I changed the CMD to "/bin/bash" so that I could log in to the OS level of the container. After doing so, I then ran the code below: uwsgi --http 923b235d270e:8888 --chdir=/code/backendworkproj --module=backendworkproj.wsgi:application --env DJANGO_SETTINGS_MODULE=backendworkproj.settings --master --pidfile=/tmp/backendworkproj-master.pid --socket=127.0.0.1:49152 --processes=5 --uid=1000 --gid=2000 --harakiri=20 --max-requests=5000 --vacuum Once complete, I was able to go to port 8888 on the machine and see the website. So, in short, everything worked. The problem I am facing now is to convert the command above to something that will work in the uwgsi.ini file If you look at part of the command above, I used : --http 923b235d270e:8888 to specify a port. The 923b235d270e is associated with the container (since 127.0.0.1 did not work) How can I represent this (and env variables … -
How to include an excel spreadsheet during Heroku build
I'm building a Python application using Django, and deploying using Heroku. Because we have a large number of constants (that we occasionally change), we load them from an Excel spreadsheet (or csv file, both would work). When testing code locally, the Excel file is placed in the same folder as the Python code and loads correctly. However, when we deploy the very same project, Heroku does not seem to 'include' the Excel file. Our program crashes whenever we run a Python script that tries to load the Excel spreadsheet. Any idea how to tell Heroku to include the Excel file during deployment, so it runs as it would when testing code? -
Using Select2 autocomplete with Django project does not work while fetching the data
In my project, I have a Search field. I used Select2 autocomplete with it. I needed to fetch the product_list from my Product model. So I created a rest API that returns the product in json formats. Here is my rest API code: serializer.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = ProductList fields = ('product_id', 'product_name', 'product_image', 'product_available', 'product_description') views.py: class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def list(request): if request.method == 'GET': products = ProductList.objects.filter(product_name__icontains=request.GET.get('q')) serializer = ProductSerializer(products, many=True) serializer_data = serializer.data customData = {'results': serializer_data} return JSONResponse(customData) Now in my html, in the javascript portion I used this code mentioned in this Select2 doc. The code I used, looks like this: base.html: <script type="text/javascript"> $(document).ready(function() { $('.js-data-example-ajax').select2({ ajax: { url: "/api.alif-marine.com/search/products", dataType: 'json', delay: 250, type: 'GET', data: function (params) { return{ q: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.results, }; }, cache: true }, placeholder: 'Search for a product', escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepo, templateSelection: formatRepoSelection }); function formatRepo (repo) { if (repo.loading) … -
How do I use allow_tags in django 2.0 admin?
Support for the allow_tags attribute on ModelAdmin methods is removed. -
Celery worker concurrency
I have make as scrapper to scrap around 150 Link Each link has around 5k sub link to get info from them i am using celery to run the scrapper in background and store data on Django ORM , i use beautifulSoap for scrap URL When i running the celery using this command celery worker -A ... --concurrency=50 everything working fine but the workers from 1 to 50 sleep how i can make the celery working till the scrapper finish his task -
Can't load homepage.html in templates folder in Django project
Below is the error message: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /var/www/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/dist-packages/django/contrib/admin/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/dist-packages/django/contrib/auth/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site1222/littlethings/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site1222/resume/templates/homepage.html (Source does not exist) And here is my project layout, sorry about the image quality: homepage.html is located in site1222/templates/homepage.html. I don't know where went wrong. -
Django queryset count() method raise "TypeError: unorderable types: NoneType() > int()"
My environment is Python3.5, Django1.8.3 and cx_Oracle5.3(They are checked by pip3 freeze). Django query set raises a Type Error exception when count() method is called. When it comes to Python2 + cx_oracle or Python3 + sqlite3 works fine without any exception but Python3 + cx_oracle. Thue, I tried to update cx_Oracle version to 6.1(latest version) because I thought I could be some compatibility problem between cx_Oracle and Python3. However, It generates a different error. I detail with the below code block, please refer it. P.S: I Need to keep Django version to 1.8.3 for compatibility with my Apps. models.py from django.db import models class Device(models.Model): deviceClass = models.CharField(max_length=10) class Meta: db_table = 'TST_G2S_DEVICE' cx_Oracle5.3 $ python3 manage.py shell Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type "copyright", "credits" or "license" for more information. IPython 2.4.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: from polls.models import Device; In [2]: dev = Device.objects.all() In [3]: dev Out[3]: [] In [4]: type(dev) Out[4]: django.db.models.query.QuerySet In [5]: dev.count() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-72a7bdf9f7f7> …