Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
setting up django celery error running instance
I'm learning how to setup django-celery and I'm getting this error [tasks] . revamp.celery.debug_task [2017-08-20 05:58:06,216: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 2.00 seconds... [2017-08-20 05:58:08,230: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 4.00 seconds... [2017-08-20 05:58:12,245: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 6.00 seconds... [2017-08-20 05:58:18,263: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 8.00 seconds... [2017-08-20 05:58:26,283: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 10.00 seconds... [2017-08-20 05:58:36,312: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 12.00 seconds... here's their docs http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html when I run this command is when the error above appears celery -A revamp worker -l info my django project is called revamp and in revamp/revamp/celery.py here's the code from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'revamp.settings') app = Celery('revamp') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: … -
Using Firebase to make a simple group chat app, alongside an already existing django-react app
I have a basic project which uses django as backend and reactJS as frontend. Basically, it just shows a home page when a user logs in, and that's it. The sign up of new users is handles through the django.admin panel. Now, I want to create a group chat for my users who are currently logged in using firebase. Here's the problem since I can't really understand the workflow on how I should proceed. My basic idea is that, 1. frontend gets the username and password from backend, 2. frontend posts them to firebase 3. firebase sends a unique id token to the frontend, 4. now frontend is logged in with both django and firebase, 5. users who are logged in joins in the group chat Is there any guidelines on how I should preceed, I have read the docs but I can't really understand what I should be doing to proceed. -
Learning about python and django
Can I read stack overflow documentation instead of tutorial on internet (Google search) for learning python and django for beginners. -
Git Push Error ( Local to Remote ) in VPS Git Server?
I've written a small django site in my Mac(Sierra OS), and I wanna to put it in my new vps(digital ocean CentOS 7). I have successfully created git server there. My local django project has an local git repository,I set remote url to my centOS git server site. And everything is going well.. I push my project to the server … and finally, it is weird that when the push task has done, I enter the remote file, and found that the ‘push task’ has only push my local .git file directory to the server.. and any other project file is ignored! Even later, I added more commits, but those made no difference. I tried to create a new repo in github.com. and push my project to the github in the exactly same way, but it works well in the github platform --- all of my project files have sucessfully pushed to the github server. How could I solve the problem? -
Django Form and Database
I am working width Django now. But I don't make sense about that. I want to get id and password from the form and check if the password from form is correct to compare with the password of database. Following are the my codes. Please help me. models.py from django.db import models class Doctor(models.Model): doctor_id = models.CharField(max_length=16, primary_key=True) clinic_id = models.ForeignKey(Clinic) doctor_email = models.CharField(max_length=64) doctor_password = models.CharField(max_length=32) doctor_name = models.CharField(max_length=32) create_date = models.DateTimeField(auto_now_add=True) modify_date = models.DateTimeField(auto_now=True) forms.py from django import forms from .models import Doctor class LoginForm(forms.Form): class Meta: model = Doctor fields = ('doctor_id', 'doctor_password',) views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from .forms import LoginForm from .models import Doctor @ensure_csrf_cookie def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): _id = form.cleaned_data['doctor_id'] _password = form.cleaned_data['doctor_password'] b = Doctor.objects.all().filter(doctor_id=_id) if _password is doctor_password: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'apiv1/login.html', {'form': form}) login.html {% extends "base.html" %} {% load staticfiles%} {% block title%}Title{% endblock %} {% block remoshincss %}/static/css/style.css{% endblock %} {% block content %} <div class="container"> <div align="center" class="imgtop"><img id="profile-img" class="profile-img-card" src="/static/img/remoshinlogo.png" … -
django blog archive, index and pagination comprehensive application
Background: I am building a blog about my research group. On the publication archive page I am going to display all the publications of my mentor. Here there is a side column to show the archive index allowing users to view the publications by year. And at the bottom of the page there is a django paginator which separate the publications in to several pages with 7 publications per page. Problem: When the pagination is used, the publications is divided into a list, so the {{publication.published_time}} only contain the data in the current page rather than the whole dataset. Thus, I wrote the hard code of year information in the front end and add the url to the corresponding year. Apparently, I wish I can get the distinct year information about all publications on the basis of the existence of a paginator. Besides, transfer the year value directly in the URL. Code: url.py: url(r'^publications/(?P<year>[0-9]{4})/$', PublicationYearArchiveView.as_view(), name="publication_year_archive"), views.py: class PublicationYearArchiveView(YearArchiveView): queryset = Publication.objects.all() date_field = "published_time" make_object_list = True allow_future = True def listing(request): limit = 7 publication_list = Publication.objects.all().order_by('published_time').reverse() paginator = Paginator(publication_list, limit) # Show 7 publications per page page = request.GET.get('page') try: publications = paginator.page(page) except PageNotAnInteger: # If … -
Passing Instance before create, in a ForeignKeyField, Django
I have to models, in this forms: class Parent(models.Model): .... class Children(models.Model): parent = ForeignKey('Parent') .... when creating a children, i have to pass a Parent as parent, my problem is I want to create the children itself, when I am creating the Parent, just as other fields, like a simple "models.TextField" Can anyone lead me how to do that? -
django: replace patterns (deprecated)
patterns has been deprecated in django 1.1 and there's this line I use to share media files in development in urls.py urlpatterns = [ ... ] after the patterns if settings.DEBUG : #urlpatterns += patterns('', # (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), #) urlpatterns.append( url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) the commented part is the old part, my attempt is getting me this error File "/home/samuel/Documents/code/revamp/revamp/urls.py", line 92, in <module> url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
styling issue in navigation bar with django
I have a styling issue in my navigation bar when the next button be enabled, it has that issue error in next page button but when the button be disabled, it got fixed error fixed here is my code for navigation.html <div class="col-6 col-offset-3 text-center pagination-set"> <nav aria-label=""> {% if queryset.has_other_pages %} <ul class="pagination"> {% if queryset.has_previous %} <li class="page-item"> <a class="page_link" href="?page={{ queryset.previous_page_number }}">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link"><span class="page-link">&laquo;</span></a> </li> {% endif %} {% for i in page_range %} {% if queryset.numbers == i %} <li class="page-item active"> <a class="page-link">{{ i }} <span class="src-only">(current) </span> </a> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if queryset.has_next %} <li class="page-item"> <a class="page-link" href="?page={{queryset.next_page_number}}"></a>&raquo; </li> {% else %} <li class="page-item disabled"> <a class="page-link"><span>&raquo;</span></a> </li> {% endif %} </ul> </nav> </div> {% endif %} and this is my code for pagination in views.py: paginator = Paginator(queryset_list, 2) # Show 2 contacts per page page = request.GET.get('page') try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range … -
How do I handle migrations as a Django package maintainer?
I have been writing a new Django package that will be pip-installable. I've been stuck for awhile because I'm unsure how to make migrations for my particular package so to allow for the normal workflow of an install to be: pip install my package add my package to your "INSTALLED_APPS" run python manage.py migrate Currently, my package looks like this: package_root/ dist/ actual_package/ __init__.py models.py setup.py The problem I am facing is that when I package the app and install it using pip install dist/... and then add it to my example apps "INSTALLED_APPS", running python manage.py migrate does not create any tables for the models in actual_package/models.py and hence I (from a users perspective) need to then run python manage.py makemigrations actual_package first, which is not ideal. Any ideas on how to have the migrations already sorted before a user installs would be excellent. -
Why it my serializer does not recognize all fields when I send a json?
Hello I'm working with an endpoint using django + django rest framework, it endpoint must receive an array objects with a file in every object and once received the file is sent to Amazon S3. Note: Using python-cassandra driver. My object is: class Archivo(UserType): tipo_documento = columns.Text() llave_s3 = columns.Text() bucket = columns.Text() tipo_contenido = columns.Text() subido = columns.DateTime() class Laboratorio(Model): certificado = columns.Set(columns.UserDefinedType(cassandra_types.Prueba)) foto = columns.UserDefinedType(cassandra_types.Archivo) equipamiento = columns.UserDefinedType(cassandra_types.Equipo) And my serializers: class PruebaSerializer(serializers.Serializer): nombre = serializers.CharField() organismo = serializers.CharField() costo = serializers.FloatField() numero = serializers.CharField() norma = serializers.CharField() archivo = serializers.FileField(write_only=True, required=False, validators=[sav_validators.FileValidator()] ) class LaboratorioSerializerCreate(serializers.Serializer): certificado = cassandra_serializers.PruebaSerializer(many=True) foto = serializers.FileField(required=False, validators=[sav_validators.FileValidator( constants.ALLOWED_IMAGE_TYPES)] ) equipamiento = cassandra_serializers.EquipoSerializer(required=False) The problem is when I send request using a Angular Client throw a 400 Bad Request. Reviewing the request I received the next fields in a request: But I don't know why throw exception when I send the request. -
Error Running node server , webpack for React configuration
Ive been digging into this for last long few hours and cant catch the bug. Im following the "Guide on how to create and set up your Django project with webpack, npm and ReactJS :)" this is the error I get when I try: node server.js (bonchans) ➜ bonchans git:(master) ✗ node server.js /Users/JuanPerez/Desktop/Sandbox/DEV/django+reactjs/django-react-boilerplate/bonchans/bonchans/node_modules/webpack/lib/webpack.js:19 throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); ^ WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. - configuration.resolve has an unknown property 'modulesDirectories'. These properties are valid: object { alias?, aliasFields?, cachePredicate?, cacheWithContext?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? } - configuration.resolve.extensions[0] should not be empty. at webpack (/Users/JuanPerez/Desktop/Sandbox/DEV/django+reactjs/django-react-boilerplate/bonchans/bonchans/node_modules/webpack/lib/webpack.js:19:9) at Object.<anonymous> (/Users/JuanPerez/Desktop/Sandbox/DEV/django+reactjs/django-react- boilerplate/bonchans/bonchans/server.js:5:22) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) (bonchans) ➜ bonchans git:(master) ✗ Configuration files: my package.json looks like this: { "name": "bonchans", "version": "1.0.0", "description": "", "main": "index.js", "repository": { "type": "git", "url": "git+https://github.com/juanto85/bonchans.git" }, "author": "Juan Perez", "license": "ISC", "bugs": { "url": "https://github.com/juanto85/bonchans/issues" }, "homepage": "https://github.com/juanto85/bonchans#readme", "devDependencies": { "babel": "^6.23.0", "babel-cli": "^6.26.0", "babel-core": "^6.26.0", "babel-loader": "^7.1.2", "react": "^15.6.1", "react-hot-loader": "^1.3.1", … -
AJAX only works one time
I did a modal with a login form and the submit through a POST AJAX request. I only can login one time, when I logout and try to login again the error message of AJAX request is this (CSRF failed): <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Prohibido <span>(403)</span></h1> <p>Verificación CSRF fallida. Solicitud abortada</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF token missing or incorrect. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/1.11/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to … -
django with apache - website doesn't show properly
I try to handle a website which is running on Apache redirected to Django (wsgi). After a full day of looking up online I was finally able to restart apache and achieve that: website VirtualHost *:80> ServerName geokey.org.uk ServerAlias *.geokey.org.uk DocumentRoot /var/www <Directory /> Options FollowSymLinks Indexes AllowOverride None </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> <Location /> Options FollowSymLinks Indexes SetHandler uwsgi-handler uWSGISocket 127.0.0.1:3031 </Location> SetHandler none Alias /static //srv/apps/geokey/geokey/static/ ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/geokey.org.access.log combined RewriteCond %{HTTPS} !on RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301] -
Best way of combining Django template tags and javascript compression for security
I am currently programming a website that uses Django as its server backend. The website allows users with different levels of privilege to log in. According to the privilege each user has, he should be able to see different elements of the HTML and Javascript of the webpage (ie: administrators can see the full website, managers can see less elements, normal users even less, etc). The easiest way to do this would probably be to just feed every user the same website and send them a variable telling the browser which parts of the site to show and which to hide but I don't like that solution since a savvy user could easily "hack" that variable and have access to information he shouldn't have. So, in order to keep the website easy to mantain by having a single version but keep a bit of security between the different levels of privilege, I just use the Django template tags: {% if administator %} ... { % endif %} This works perfectly fine with HTML. However if I want to do the same with Javascript, I am unable to automatically compress Javascript using Yuglify or similar libraries since they aren't able to … -
Django jquery ajax remote validate returns TypeError: Cannot read property 'apply' of undefined
I am trying to validate one field of a form using JQuery & Validate.js in Django. I've read many posts, but regardless of the various examples, it fails on the same error. Simply use the remote method included in the plugin. is the last one I hit and the simplest code sample, but same result: jquery.validate.js:1594 Uncaught TypeError: Cannot read property 'apply' of undefined. Exception occurred when checking element id_client_code, check the 'remote' method. at Function.$.ajax (jquery.validate.js:1594) at $.validator.remote (jquery.validate.js:1529) at $.validator.check (jquery.validate.js:777) at $.validator.element (jquery.validate.js:492) at $.validator.onfocusout (jquery.validate.js:300) at HTMLInputElement.delegate (jquery.validate.js:423) at HTMLFormElement.dispatch (jquery-3.2.1.slim.min.js:3) at HTMLFormElement.q.handle (jquery-3.2.1.slim.min.js:3) at Object.trigger (jquery-3.2.1.slim.min.js:3) at Object.simulate (jquery-3.2.1.slim.min.js:3) Here is my views.py section for the remote, which returns false as expected when called in another tab: def validate_client_code(request): is_available = 'false' if request.is_ajax(): client_code = request.GET.get('client_code', None) try: Client.objects.get(client_code) except Client.DoesNotExist: is_available = 'true' return HttpResponse(is_available) and here is my script block <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script> <script> $("#new-client").validate({ rules: { client_code: { required: true, remote: "/clients/ajax/validate_client_code/" }, messages: { client_code: {remote: "The client code is already taken"} } } }); </script> HTML as rendered (using Crispy Forms): <form class="form-horizontal" method="post" action="/clients/new/" enctype="multipart/form-data" id="new-client"> <input type='hidden' name='csrfmiddlewaretoken' value='ek...'/> <div id="div_id_client_code" class="form-group"><label … -
django-websocker error: ValueError: message object is not of type RedisMessage
I'm learning how to setup django-websocket with redis https://django-websocket-redis.readthedocs.io/en/latest/api.html#use-redispublisher-from-inside-django-views and I'm calling it like this message = "Percentage {0}% \t {1}/{2} \t {3}".format(percentage, counter, (width * height), delta) print message socket = RenderView() socket.get(request, message) in the view from django.views.generic.base import View from ws4redis.publisher import RedisPublisher class RenderView(View): facility = 'render-view' audience = {'broadcast': True} def __init__(self, *args, **kwargs): super(RenderView, self).__init__(*args, **kwargs) self.redis_publisher = RedisPublisher(facility=self.facility, **self.audience) def get(self, request, message): self.redis_publisher.publish_message(message) I'm getting this error socket.get(request, message) File "/home/samuel/Documents/code/revamp/gallery/socket.py", line 13, in get self.redis_publisher.publish_message(message) File "/usr/local/lib/python2.7/dist-packages/ws4redis/redis_store.py", line 110, in publish_message raise ValueError('message object is not of type RedisMessage') ValueError: message object is not of type RedisMessage -
django-rest-framework list of links to endpoints
Using django-rest-framework, I need to create an endpoint that lists links to other endpoints. router = DefaultRouter() router.register(r'pepperonis', views.PepperoniViewSet, 'Pepperoni') router.register(r'supremes', views.SupremeViewSet, 'Supreme') router.register(r'some-unrelated-endpoint', views.UnrelatedViewSet, 'Unrelated') These viewsets I'm interested in all inherit from the same class: class Pizza(viewsets.ModelViewSet): pass class PepperoniViewSet(Pizza): pass class SupremeViewSet(Pizza): pass I can get all the relevant viewsets from Pizza.__subclasses__(). How can I create an API endpoint that lists hyperlinks to only these endpoints? I'll need the endpoint to return something like this: [{"url": "http://example.com/api/pepperonis/"}, {"url": "http://example.com/api/supremes/"} -
Using sox to trim a sound file within Django form class
I'm trying to build an application which allows users to edit their uploaded sound files. So far the user is able to retrieve their sounds and display as waveform with the wavesurfer js library. The idea is to grab the start and end points on the wavesurfer region selected, and pass those values to the form class (where sox will trim the file) using an updateview. I pip installed pysox and installed sox in my virtual env. This is what I have so far with my urls.py: url(r'^update_sound/(?P<pk>[\w-]+)$', UpdateSound.as_view(), name='update_sound'), my forms.py: import sox class UpdateSound(forms.ModelForm): def trim_sound(self): file = self.cleaned_data.get('sound', False) tfm = sox.Transformer(file) tfm.trim(0,0.3) class Meta: model = Sounds fields = [ 'sound', ] And the update view class UpdateSound(UpdateView): model = Sounds form_class = UpdateSound template_name= 'sound_detail.html' My main question is, 1.Is this a good way of going about editing sound files and 2. What should I add to my form class to make this work? I've looked at the sox docs and still not entirely clear on what to do. Should I be passing the sound file as an argument to the transformer? Any help is much appreciated. -
404 from cron job on google app engine django app
So, everything else works... to preface this. But, I haven't really moved outside the admin interface. I'm trying to get data from an API and insert it into the database if there's changes. I've managed to write a script that can do that (in theory... it can do it locally), but I can't get the app in the cloud to recognize its existence. I've followed Google's suggestion of adding it to the app.yaml and cron.yaml to no avail. Do I need to add this to a urls.py? I haven't mucked with teh handlers at all thus far and I'm not sure what settings.py makes happen, what the yaml files make happen, and how much of this is pixie dust. here are teh relevant files... app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT mysite.wsgi threadsafe: yes beta_settings: cloud_sql_instances: jc-app-176715:us-east4:jc-app runtime_config: python_version: 3 health_check: enable_health_check: False handlers: - url: /static static_dir: static/ - url: /run/get_data/ script: JSONdownload.app login: admin - url: .* script: mysite.wsgi.application cron.yaml cron: - description: "get data" url: /run/get_data/ schedule: every 5 minutes JSONdownload.py #!/usr/bin/env python # /var/spool/cron/crontabs import json import urllib2 from django.http import HttpResponse from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from .models import Game … -
django websocker error: AttributeError: 'super' object has no attribute 'init'
I'm in the process of learning how to use websockets with django, I'm using django-websocket and here's a quick link to how they recommend setting it up https://django-websocket-redis.readthedocs.io/en/latest/api.html#use-redispublisher-from-inside-django-views I've setup redis and it's working okay, I've also got this view to send requests from django.views.generic.base import View from ws4redis.publisher import RedisPublisher class RenderView(View): facility = 'render-view' audience = {'broadcast': True} def __init__(self, *args, **kwargs): super(RenderView, self).init(*args, **kwargs) self.redis_publisher = RedisPublisher(facility=self.facility, **self.audience) def get(self, request, message): self.redis_publisher.publish_message(message) I call it using ... message = "Percentage {0}% \t {1}/{2} \t {3}".format(percentage, counter, (width * height), delta) print message socket = RenderView() socket.get(request, message) got stuck here with this error socket = RenderView() File "/home/samuel/Documents/code/revamp/gallery/socket.py", line 9, in __init__ super(RenderView, self).init(*args, **kwargs) AttributeError: 'super' object has no attribute 'init' [19/Aug/2017 21:14:48] "POST /render-part HTTP/1.1" 500 18828 -
Figuring out why django can't find scripts, stylesheets, and plug-ins for my template right now
I inherited a project and I've been trying to get the file structure correct on my local machine but I haven't been able to figure it out. My django project is called gtr_site. On the home page html file, which is located in a .../templates/gtr_site/home.html path, I am trying to load scripts and stylesheets from a folder called "vendor" and its contents. The file within home.html to attempt to link some bootstrap code is as follows: <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> When I first came across this, I made the assumption that i could be okay by creating a folder called "vendor" in same directory as home.html (in templates/gtr_site/), then creating the following directories and inserting the bootstrap file into the final directory. That hasn't worked. I get the following error messages for various files in the vendor folder: [19/Aug/2017 15:53:35] "GET /gtr/vendor/bootstrap/css/bootstrap.min.css/ HTTP/1.1" 404 1798 Not Found: /gtr/vendor/bootstrap/css/bootstrap.min.css/ So... my original approach of just creating a folder called "vendor" and going from there didn't work. Because of that, I'm left with the question of "where is this html file supposed to be searching for a folder called vendor? Is it able to find one?" I don't know necessarily how to answer … -
How to get attribute of a django model's foreign key object using getattr in python?
Suppose I have two models as such class first(models.Model): name = models.CharField(max_length=20) y = models.ForeignKey(second) class second(models.Model): random = models.CharField(max_length=20) Now if I want value of name for a first object instance using getattr, I can do getattr(x, 'name') where x is a first object but if I try the same with getattr(x, 'y.random') , it throws me an error even though x.y.random is a totally valid query. Is it possible to query x.y.random if all I have is object x and string 'y.random'? -
Geodjango check if Point is inside Polygon not working
I'm using GeoDjango for the first time in one of my projects and I'm having a problem checking if a certain Point object is inside Polygon object. This is a relevant piece of code. print 'POLY START TYPE: ', type(start_poly) print 'POINT START TYPE: ', type(point_start) print 'POLY START - ', start_poly print 'POINT START - ', point_start print 'Contains point: ', start_poly.contains(point_start) print 'Intersects point: ', start_poly.intersects(point_start) And the output POLY START TYPE: <class 'django.contrib.gis.geos.polygon.Polygon'> POINT START TYPE: <class 'django.contrib.gis.geos.point.Point'> POLY START - SRID=4326;POLYGON ((13.08300018310547 45.27488643704894, 13.08300018310547 46.70973594407157, 16.57665252685547 46.70973594407157, 16.57665252685547 45.27488643704894, 13.08300018310547 45.27488643704894)) POINT START - SRID=4326;POINT (46.2259433 14.45591430000002) Contains point: False Intersects point: False I'm not sure why contains or intersects methods aren't returning True. What am I doing wrong? -
Django POST validation seeing number as string
I'm a bit confused where to go with this as I thought it would be part of Django's validation... I'm on 1.8 because I'm using an older database connection library that was last tested with 1.8 (rewriting a frontend for old data). models.py: class Order(models.Model): ~rest of class~ RequestorNumber = models.SmallIntegerField(db_column='requestor_no') class Requestor(models.Model): RequestorNumber = models.SmallIntegerField(primary_key=True, db_column="requester_no") Requestor = models.CharField(max_length=20, db_column = "requester") def __str__(self): return self.Requestor forms.py class OrderForm(forms.ModelForm): RequestorNumber = forms.ModelChoiceField(queryset=Requestor.objects.all().order_by('RequestorNumber'), label="Requestor") So this creates a correct dropdown in the template, with values as integers and text as the descriptions ex: <option value="1" selected="selected">JOHN DOE</option> When the form is submitted, the POST QueryDict has a proper entry when printing the entire request: ... 'OrderForm-RequestorNumber': ['1'] ... but this is coming in as a string (as I would expect), but the validator when doing is_valid() kicks back and the webpage gets: 'JOHN DOE' value must be an integer. Is this by design? I feel like it's trying ignore the value of the selected for the form and referring back to the object's __str__ definition as what needs to be saved. If this is dumb, i'm also all ears to figure out what a more correct method is, the only …