Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not saving file to FileField. IOError: File not open for reading
I have this Django code, I can't save the file to the models FileField: # create stocklist object and populate it stocklist = StockList.objects.create(retailer=retailer) with open("retailer_stocklist.csv", "wb") as csv_file: for row in table_data: writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL) writer.writerow([row["EAN"], row["NAME"], row["QUANTITY"], row["UNIT"], row["SKU"], row["PRICE"]]) stocklist.csv_file.save("retailer_stocklist.csv", File(csv_file)) The model looks like this: class StockList(models.Model): csv_file = models.FileField(null=True, blank=True) I get the error: IOError: File not open for reading -
DJANGO: Displaying a PNG picture into an HTML template
I have been struggling with an issue and similar questions on this website haven't helped me. I am learning Django and I want to print an image PNG (which I generate with Python) into an HTML page (so, following Django's rules, I use an HTML template). To create my picture I have written some code into a SEPARATED views.py file (which I have called views1.py), here is the content: from pylab import figure, axes, pie, title from matplotlib.backends.backend_agg import FigureCanvasAgg import matplotlib.pyplot from django.http import HttpResponse def test_matplotlib(request): f = figure(figsize=(6,6)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15,30,45, 10] explode=(0, 0.05, 0, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True) title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5}) canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image/png') canvas.print_png(response) matplotlib.pyplot.close(f) return response In my views.py I have defined a function, which lets a user search for the ticker of a stock. When he submits the request, the user will see the price of the stock in that moment, here is my function (this function works, I have tested it): # import some packages (for the answer, ignore those that are not related, I have other functions in this views.py file) … -
AttributeError for using spyne package
i used spyne package for django for soap server but i have this error while i use runserver AttributeError: type object 'HelloWorldService' has no attribute 'as_view' views.py from django.views.decorators.csrf import csrf_protect from django.http import HttpResponse , HttpResponseRedirect from django.template.loader import get_template from django.shortcuts import render from spyne import Application, rpc, ServiceBase, Iterable, Integer, Unicode from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication class HelloWorldService(ServiceBase): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield u'Hello, %s' % name application = Application([HelloWorldService], 'spyne.examples.hello.soap', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_application = WsgiApplication(application) if __name__ == '__main__': import logging from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server = make_server('127.0.0.1', 8000, wsgi_application) server.serve_forever() urls.py from django.conf.urls import url from myapp.views import HelloWorldService from . import views urlpatterns = [ url(r'^service/$',HelloWorldService.as_view()), ] -
Django validation on the Many-to-Many save
First time post so my apologies if I go about this wrong. I have the following model: #models.py class Item(model.Model): title = models.CharField() #other properties here class Event(model.Model): #properties class Package(model.Model): title = models.CharField() #other properties items = ManyToManyField(Item) events = ManyToManyField(Event) Packages can have multiple items, and items can be part of multiple packages. Events can have multiple packages, and packages can be used at multiple events. What I want to do is is have a validation on the creation of the event-package relationship so that while you can have multiple packages at an event, none of the packages can have any of the same items in them, and if you tried to add a package to an event that conflicts, an error will be thrown in the admin. So far my research has led me to believe I have to overwrite the save_related property, but I'm not sure how to apply it in this case. Can anyone point me in the right direction? -
/manage.py celeryd : IndexError: list index out of range
when I run python /manage.py celeryd -B -l info error_log: Traceback (most recent call last): File "/opt/python/ansible_ui/manage.py", line 11, in execute_from_command_line(sys.argv) File "/opt/python/env/local/lib/python2.7/site-packages/django/core/management/init.py", line 399, in execute_from_command_line utility.execute() File "/opt/python/env/local/lib/python2.7/site-packages/django/core/management/init.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/env/local/lib/python2.7/site-packages/djcelery/management/base.py", line 77, in run_from_argv return super(CeleryCommand, self).run_from_argv(argv) File "/opt/python/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 238, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "/opt/python/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 219, in create_parser option_list=self.option_list) File "/opt/python/env/local/lib/python2.7/site-packages/djcelery/management/base.py", line 107, in option_list if x._long_opts[0] not in self.skip_opts] IndexError: list index out of range -
How to index newly created objects with Elastic Search
I am connected via Elastic search to my database. Whenever I edit or create a new item, ES updates the individual item with the updated details. EG if I goto http://localhost:9200/xyz/123 my object will have all the details. However, it is not being added to the overall index. All that happens to the index, is the title gets added (no other details). I tried getting signals to run the indexing function, but that said it wants *kwargs Aside from manually calling bulk_indexing(), how can I tell my newly created update to add all its' values to the index? models.py class Task(models.Model): title = models.CharField("Title", max_length=10000, blank=True) def __str__(self): return u"%s (%s)" % (self.title, self.get_typetask_display()) def to_search(self): d = { "title": self.title, "updated": self.updated, } return TaskIndex(meta={'id': self.id}, **d) def indexing(self): obj = TaskIndex( meta={'id': self.id}, title=self.title, updated=self.updated, id=self.id, ) obj.save() return obj.to_dict(include_meta=True) @receiver(post_save, sender=Task) def index_post(sender, instance, **kwargs): instance.indexing() def update_search(instance, **kwargs): instance.to_search().save() def remove_from_search(instance, **kwargs): instance.to_search().delete() post_save.connect(update_search, sender=Task) post_save.connect(update_search, sender=Tag) pre_delete.connect(remove_from_search, sender=Task) pre_delete.connect(remove_from_search, sender=Tag) m2m_changed.connect(update_search, sender=Task.tag.through) search.py class TaskIndex(DocType): title = String() class Meta: index = 'task-index' def bulk_indexing(): TaskIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.Task.objects.all().iterator())) def _search(title): s = Search().filter('term', title=title.text) response = s.execute() return … -
Cannot resolve 'django.utils.log.NullHandler' in Django 1.9
I am trying to install readthedocs server my vm. I am new to python and Django. While doing configuration for Django-allauth I am facing error- cannot resolve Django.utils.log.Nullhandler. I know what to do means I know I have to change the class name to logging.nullhandler in some settings file. Can anybody please tell me the path of settings file where I have to make changes. TIA -
Django Rest Framework - Field username with ".", "-", "_" character
I want allow from my backend API, that any user can be created with characters like .,-,_, ñ between others characters in their username field which is primary_key=True,. I define my custom user (AbstractBaseUser) of this way, in relation to username field which is of my interest: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( _('username'), max_length=30, primary_key=True, unique=True, help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[ RegexValidator( r'^[\w.@+-]+$', _('Enter a valid username. This value may contain only ' 'letters, numbers ' 'and @/./+/-/_ characters.') ), ], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField(max_length=254, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() My UserSerializer is this: class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all(), message='Lo sentimos, existe un fichaje con este nombre de usuario')]) email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all(), message='Lo sentimos, alguien ya ha sido fichado con este correo electrónico')]) class Meta: model = User fields = ('url', 'username', 'password', 'first_name','last_name', 'age','other fields ...',) My UserViewSet is the following: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', ) The router is defined og this … -
Django Naive Chat Implementation , Will it work?
I was asked to make a chat application on django for a special portal where only at a particular time 4 staff users can be talking to 4 selected users from a large (around 500 not all logged in at the same time) user database. I implemented it using django and ajax with the following details -> I used the chat model which stores all the chat messages sent to the server till now.Its fields are 1) userto 2) userfrom 3) message Each user has two states :- 1) He can wait for a chat room to get empty which he can be alloted 2) He can be in a chat room and talk with one of the staff users When in a chat room , using ajax i query all messages in the chat table, and show the messages which belong to the chat. Now a request is sent to the server each 0.5 seconds to update the message list. Note - Inside a chatroom only the messages between the two users should be displayed When not in a chat room , The user is redirected to a normal page (which is not real time) and displays all chat … -
run django with apache2 on ssl
Firstly, I apologize if my question is a bit weired. I have django application which runs perfectly fine in production environment (apache2) but it runs on HTTP port 8000 for which I have configured the file under /apache2/sites-enabled/000-default.conf. One thing more, I have set multiple allowed_hosts in django settings and all of these runs fine on http port 8000(without ssl). I want to run my application on HTTPS 8000. I have tried some other tips(like configure default-ssl.conf anf forwarding from http to https) that are on internet but unfortunately it won't work for me. I would be really thankful if someone could help and take me in the right direction as I am new to deployment side. -
set Django RawQuerySet to do not defer attributes
According to Django documentation if a field is trying to be reached in raw query set, it would fetch it in real time. How can I prevent it from fetching fields not being retrieved from the database? e.g. if I write select name from authors and later a user will write author.gender it would return None and attempt to retrieve it from the database? -
How can I satisfy the URL settings for django-ckadmin?
From https://pypi.python.org/pypi/django-ckeditor/5.0.1, which is in sync with readthedocs: . Add CKEditor URL include to your project's urls.py file:: (r'^ckeditor/', include('ckeditor_uploader.urls')), I can try to add the uploader URLs but ckeditor_uploader does not seem to have a member urls: (pets-env) root@lists:~/pets# python manage.py shell Python 2.7.9 (default, Jun 29 2016, 13:08:31) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import ckeditor_uploader >>> dir(ckeditor_uploader) ['ImproperlyConfigured', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'absolute_import', 'settings'] >>> ckeditor_uploader.url Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'module' object has no attribute 'url' >>> dir(ckeditor_uploader.settings) ['ABSOLUTE_URL_OVERRIDES', 'ADMINS', 'ALLOWED_HOSTS', 'APPEND_SLASH', 'AUTHENTICATION_BACKENDS', 'AUTH_PASSWORD_VALIDATORS', 'AUTH_USER_MODEL', 'BASE_DIR', 'CACHES', 'CACHE_MIDDLEWARE_ALIAS', 'CACHE_MIDDLEWARE_KEY_PREFIX', 'CACHE_MIDDLEWARE_SECONDS', 'CKEDITOR_IMAGE_BACKEND', 'CKEDITOR_JQUERY_URL', 'CKEDITOR_UPLOAD_PATH', 'CSRF_COOKIE_AGE', 'CSRF_COOKIE_DOMAIN', 'CSRF_COOKIE_HTTPONLY', 'CSRF_COOKIE_NAME', 'CSRF_COOKIE_PATH', 'CSRF_COOKIE_SECURE', 'CSRF_FAILURE_VIEW', 'CSRF_HEADER_NAME', 'CSRF_TRUSTED_ORIGINS', 'DATABASES', 'DATABASE_ROUTERS', 'DATA_UPLOAD_MAX_MEMORY_SIZE', 'DATA_UPLOAD_MAX_NUMBER_FIELDS', 'DATETIME_FORMAT', 'DATETIME_INPUT_FORMATS', 'DATE_FORMAT', 'DATE_INPUT_FORMATS', 'DEBUG', 'DEBUG_PROPAGATE_EXCEPTIONS', 'DECIMAL_SEPARATOR', 'DEFAULT_CHARSET', 'DEFAULT_CONTENT_TYPE', 'DEFAULT_EXCEPTION_REPORTER_FILTER', 'DEFAULT_FILE_STORAGE', 'DEFAULT_FROM_EMAIL', 'DEFAULT_INDEX_TABLESPACE', 'DEFAULT_TABLESPACE', 'DISALLOWED_USER_AGENTS', 'EMAIL_BACKEND', 'EMAIL_HOST', 'EMAIL_HOST_PASSWORD', 'EMAIL_HOST_USER', 'EMAIL_PORT', 'EMAIL_SSL_CERTFILE', 'EMAIL_SSL_KEYFILE', 'EMAIL_SUBJECT_PREFIX', 'EMAIL_TIMEOUT', 'EMAIL_USE_SSL', 'EMAIL_USE_TLS', 'FILE_CHARSET', 'FILE_UPLOAD_DIRECTORY_PERMISSIONS', 'FILE_UPLOAD_HANDLERS', 'FILE_UPLOAD_MAX_MEMORY_SIZE', 'FILE_UPLOAD_PERMISSIONS', 'FILE_UPLOAD_TEMP_DIR', 'FIRST_DAY_OF_WEEK', 'FIXTURE_DIRS', 'FORCE_SCRIPT_NAME', 'FORMAT_MODULE_PATH', 'IGNORABLE_404_URLS', 'INSTALLED_APPS', 'INTERNAL_IPS', 'LANGUAGES', 'LANGUAGES_BIDI', 'LANGUAGE_CODE', 'LANGUAGE_COOKIE_AGE', 'LANGUAGE_COOKIE_DOMAIN', 'LANGUAGE_COOKIE_NAME', 'LANGUAGE_COOKIE_PATH', 'LOCALE_PATHS', 'LOGGING', 'LOGGING_CONFIG', 'LOGIN_REDIRECT_URL', 'LOGIN_URL', 'LOGOUT_REDIRECT_URL', 'MANAGERS', 'MEDIA_ROOT', 'MEDIA_URL', 'MESSAGE_STORAGE', 'MIDDLEWARE', 'MIDDLEWARE_CLASSES', 'MIGRATION_MODULES', 'MONTH_DAY_FORMAT', 'NUMBER_GROUPING', 'PASSWORD_HASHERS', 'PASSWORD_RESET_TIMEOUT_DAYS', 'PREPEND_WWW', 'ROOT_URLCONF', 'SECRET_KEY', 'SECURE_BROWSER_XSS_FILTER', 'SECURE_CONTENT_TYPE_NOSNIFF', 'SECURE_HSTS_INCLUDE_SUBDOMAINS', 'SECURE_HSTS_SECONDS', 'SECURE_PROXY_SSL_HEADER', 'SECURE_REDIRECT_EXEMPT', … -
How to retrieve amazon s3 temporary credentials?
I've got a Django Rest API and a React Native app. I'd like to upload some files to my s3 bucket from my app. I could do this : User would like to upload an image --> GET my_api/s3/credentials/ App --> POST image directly to s3 using credentials (access/private keys) The problem is that once the user has the accessKey and privateKey, he can use it indefinitely. Is there a way to retrieve temporary credentials I could give to the user after a call on my_api/s3/credentials/ ? -
Django: Is it possible to limit ContentType by base Parent?
I have an Abstract base class "Parent" from which derive two subclasses "Child1" and "Child2". Each child can have a set of "Status". I used "ContentType", "GenericForeignKey" and "GenericRelation" like so: from django.db import models from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey from django.contrib.contenttypes.models import ContentType class Parent(models.Model): name = models.CharField(max_length=30, blank=True) class Meta: abstract = True def __str__(self): return self.name class Child1(Parent): id_camp = models.PositiveIntegerField() config_type = models.CharField(max_length=30) status_set = GenericRelation(Status) class Child2(Parent): temperature = models.FloatField(null=True, blank=True) status_set = GenericRelation(Status) class Status(models.Model): code = models.CharField(max_length=10, null=True, blank=True) message = models.CharField(max_length=100, null=True, blank=True) content_type = models.ForeignKey(ContentType, limit_choices_to={'name__in': ('child1', 'child2',)}, null=True, blank=True) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') The actual solution works fine, but right now the limitation of choices of content type is by "name" and eventually I will create more subclacess of Parent later. I would like to replace limit_choices_to={'name__in': ('child1', 'child2',)} with somthing like limit_choices_to children of parent is there any straightforward way ? -
Django prefetch_related optimize query but still very slow
I'm experiencing some severe performances issues with prefetch_related on a Model with 6 m2m fields and I'm pre-fetching also few nested m2m fields. class TaskModelManager(models.Manager): def get_queryset(self): return super(TaskModelManager, self).get_queryset().exclude(internalStatus=2).prefetch_related("parent", "takes", "takes__flags", "assignedUser", "assignedUser__flags", "asset", "asset__flags", "status", "approvalWorkflow", "viewers", "requires", "linkedTasks", "activities") class Task(models.Model): uuid = models.UUIDField(primary_key=True, default=genOptimUUID, editable=False) internalStatus = models.IntegerField(default=0) parent = models.ForeignKey("self", blank=True, null=True, related_name="childs") name = models.CharField(max_length=45) taskType = models.ForeignKey("TaskType", null=True) priority = models.IntegerField() startDate = models.DateTimeField() endDate = models.DateTimeField() status = models.ForeignKey("ProgressionStatus") assignedUser = models.ForeignKey("Asset", related_name="tasksAssigned") asset = models.ForeignKey("Asset", related_name="tasksSubject") viewers = models.ManyToManyField("Asset", blank=True, related_name="followedTasks") step = models.ForeignKey("Step", blank=True, null=True, related_name="tasks") approvalWorkflow = models.ForeignKey("ApprovalWorkflow") linkedTasks = models.ManyToManyField("self", symmetrical=False, blank=True, related_name="linkedTo") requires = models.ManyToManyField("self", symmetrical=False, blank=True, related_name="depends") objects = TaskModelManager() The number of query is fine and the database query time is fine too, for exemple if I query 700 objects of my model i have 35 query and the average query time is 100~200ms but the total request time is approximately 8 seconds. silk times I've run some profiling and it pointed out that more than 80% of the time spent was on the prefetch_related_objects call. profiling I'm using Django==1.8.5 and djangorestframework==3.4.6 I'm open to any way to optimize this. Thanks in advance for your … -
Auto Reconnect MYSQL on django
Using Django with MySQLdb connector I'm getting the following error: OperationalError (2006, 'MySQL server has gone away') Using URI like this should work: mysql://db_user:db_pass@localhost/dbname?autoReconnect=true However I'm using django's settings: DATABASES = { 'default': { 'NAME': 'dbname', 'ENGINE': 'django.db.backends.mysql', 'USER': 'db_user', 'PASSWORD': 'db_pass', 'HOST': 'localhost', 'PORT': 3306, } } Was trying multiple things, like settings 'AUTO_RECONNECT': true and 'OPTIONS': { .. } but nothing worked. -
django-nose - Exclude directory in coverage
I'm using django-nose in order to measuring coverage of my test suite. I followed this doc to do this. With the standard configuration works well, and i succeed in cover all my application. I would exclude views directory from the coverage without install new packages, so I tried to use --ignore-files parameter in this way: NOSE_ARGS = [ '--with-coverage', '--cover-package=apps.my_app', '--ignore-files=^views\\.' ] My project structure is +- root |-- src |--- main |---- apps |----- my_app |------ views |--- test |---- main |----- apps |------ my_app |------- views And I run the test suite from project root with the following command: python src\main\manage.py test --noinput main Unfortunately it doesn't work correctly, I mean that django-nose seems ignore this option and views directory is included in the coverage. What i'm missing? -
How to pass parameter from view to form in django shell
I have parameter to MyForm supplied from MyView. How can I use this scenario in django shell >>> f=MyForm() Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: __init__() missing 1 required positional argument: 'request' The parameter 'request' from get_form_kwargs() in MyView def get_form_kwargs(self): kwargs = super(MarkAttendanceView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs Now, how can I set the from django shell, so that I can validate the form output? -
MultiValueDictKeyError at / django
I am learning django after I just learned flask. I had a project I had to do in flask and now have same project in django. I went though with same code and "converted" it over. Its throwing an error of MultiValueDictKeyError at /farm. If someone could direct me in which way to work The full trace back is as follows Traceback: File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner 42. response = get_response(request) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\project7\ningagold\apps\ninjagold\views.py" in building 47. if request.POST["building"] == "farm": File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\utils\datastructures.py" in __getitem__ 85. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /farm Exception Value: "'building'" HTML <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script> <script> </script> </head> <body> <div><P>Farm</P><form action="/farm" method="post"> {% csrf_token %} <input type="hidden" name="building" value="farm" /> <input type="submit" value="Find Gold!"/> </form> </div> <div><p>Cave</p><form action="/farm" method="post"> {% csrf_token %} <input type="hidden" name="building" value="cave" /> <input type="submit" value="Find Gold!"/> </form> </div> <div><p>House</p><form action="/farm" method="post"> {% csrf_token %} <input type="hidden" name="building" value="house" /> <input type="submit" value="Find Gold!"/> </form> </div> <div><p>Casino</p><form action="/farm" method="post"> {% csrf_token %} <input type="hidden" name="building" value="casino" /> <input type="submit" value="Find Gold!"/> </form> </div> <div><p> </p></div> </form> </body> … -
Why do balanced Django templating {% if %} and {% endif %} get Invalid block tag on line 50: 'endif', expected 'empty' or 'endfor'
I'm getting an error specifying that an outer {{ endif }} close tag is not expected; {{ empty }} or {{ endfor }} is expected. That sounds like I have an {{ endif }} that does not match an earlier {% if ... %} and it expects me to close the outermost loop nestingwise (source at http://pastebin.com/Knsbi6bH). (This is intended to be within a {{ for }} loop, but the {{ endif }} AFAIK matches an opening {{ if ... }}. It's the {{ endif }} before the </h2>. The reporter error is line 50: 40 {% else %} 41 {% if pet.shelter.website or 42 pet.shelter.slugline %} 43 this shelter 44 {% endif %} 45 {% endif %} 46 {% if pet.shelter.name or 47 pet.shelter.website %} 48 </a>) 49 {% endif %} 50 {% endif %} 51 </h2> 52 {% if pet.snippet %} 53 {{ pet.snippet }} 54 {% endif %} 55 </td> 56 </tr> 57 {% endif %} 58 {% endfor %} 59 </table> 60 {% else %} Pastebin is at http://pastebin.com/Knsbi6bH Do {% ... %} tags need to be on a single line? I would welcome any ideas on what I am missing. -
ImportError: No module named myapp_o.urls
I have a django-oscar project I am working on. And I have been searching everywhere to solve this problem. Although, I have come across similiar questions here, I still can't solve the problem. I am trying to create other pages such as 'about', and 'contacts'. I have checked the dashboard for pages creating but can't seem to do exact what I want. I want to be able put these pages on the footer area. I was able to display these pages created at the dashboard to my footer but it seems simple displaying just text. Was wondering if I could do more. I have created an app in my apps folder. Here is the folder structure: folder structure Full folder structure Here is my env installs - pip freeze requirements.txt Babel==2.3.4< beautifulsoup4==4.5.1 colorama==0.3.7 coverage==3.7.1 coveralls==0.4.4 detox==0.10.0 Django==1.9.12 django-appconf==1.0.2 django-compressor==1.6 django-countries==4.0 django-debug-toolbar==1.5 django-extra-views==0.6.4 django-haystack==2.5.1 django-localflavor==1.3 django-nose==1.4.2 django-oscar==1.3 -e git://github.com/tangentlabs/django-oscar- paypal.git@76542cefa67170b10694ab431a0b35408d99b16e#egg=django_oscar_paypal django-static-precompiler==1.5 django-tables2==1.0.7 django-treebeard==4.1.0 django-webtest==1.7.7 django-widget-tweaks==1.4.1 docopt==0.6.2 enum-compat==0.0.2 enum34==1.1.6 eventlet==0.20.0 factory-boy==2.7.0 fake-factory==0.7.2 flake8==2.2.3 funcsigs==1.0.2 greenlet==0.4.11 ipaddress==1.0.17 mccabe==0.5.2 mock==1.0.1 mod-wsgi==4.5.11 nose==1.3.7 pbr==1.10.0 pep8==1.7.0 phonenumbers==7.7.5 Pillow==3.4.2 pinocchio==0.4.1 pluggy==0.3.1 purl==1.3 py==1.4.31 pycountry==16.11.27.1 pyflakes==1.3.0 pytest==3.0.1 pytest-cov==2.3.1 pytest-django==3.0.0 python-dateutil==2.6.0 pytz==2016.10 PyYAML==3.12 requests==2.12.3 six==1.10.0 sorl-thumbnail==12.4a1 sqlparse==0.2.2 tox==2.1.0 Unidecode==0.4.19 virtualenv==15.1.0 waitress==1.0.1 WebOb==1.6.3 WebTest==2.0.16` Here is myapp views.py from django.http … -
Data type conversion via sql query
I have problem with data type conversion. Using django and pypyodbc lib I'm trying to recieive data from oracle DB (external) and save it into local app DB. import pypyodbc def get_data(request): conn = pypyodbc.connect("DSN=...") cursor = conn.cursor() cursor.execute("SELECT value FROM table") data = cursor.fetchall() for row in data: d = External_Data(first_val = row[0]) d.save() The output from value is "0,2" and I've received error message: could not convert string to float: b',02' When I changed sql statement to: SELECT cast(value as numeric(10,2) from table) I received error message: [<class 'decimal.ConversionSyntax'>] How to change that data to get float data and save it. I use DecimalField(max_digits=10, decimal_places=2) as model field. -
Best way to upload large files from client to 3rd party (e.g. dropbox) via oauth
I am currently creating a dashboard in django that allows users to upload to various hosting services such as dropbox/google drive/one drive. I am wondering what would be a good way to implement large file (2 gb < ) uploads? Sorry for the broadness of the question, there just doesnt seem to be anyway to phrase this better. I'm basically trying for some sort of client based uploader that is resumable (in order to prevent dropping at 99%) but will disconnect/cancel if the user leaves the page. I was thinking some sort of websocket based uploader client side, but really have no clue what to do server side. Some sort of nodejs streaming connector? Just use a normal django endpoint and split the data into smaller chunks but risk a huge overhead (e.g. sessions/etc) -
RawQuerySet to QuerySet
I read here about an example of how to convert RawQuerySet to QuerySet. However, my raw query set DOES NOT return id as the first column but rather ad_id and country as the unique fields (since I am using GROUP BY) I tried to modify the code like this: class RawQueryToQueryManager(Manager): def raw_as_qs(self, raw_query, params=()): """Execute a raw query and return a QuerySet. The first column in the result set must be the id field for the model. :type raw_query: str | unicode :type params: tuple[T] | dict[str | unicode, T] :rtype: django.db.models.query.QuerySet """ cursor = connection.cursor() try: cursor.execute(raw_query, params) return self.filter(ad_id__in=(x[0] for x in cursor)) finally: cursor.close() This doesn't work also for ad_id - it would return 6 records, while the query returns 1 record (when I do print [x for x in cursor] I get one recrod) How can I filter by both ad_id and country? -
Celery use local settings instead of RabbitMQ settings for an unknown reason
I work with Django 1.9, Celery 3.1.23, Redis 2.10.5 - The site is on Heroku. RabbitMQ is used as message broker (CloudAMQP). My settings.py is as follow: CELERY_RESULT_BACKEND = os.environ['REDIS_URL'] BROKER_URL = 'amqp://xxx:yyyyyy@salamander.rmq.cloudamqp.com/xxx' BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = 100 CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = ['json'] CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' if BROKER_URL == "django://": INSTALLED_APPS += ("kombu.transport.django",) And I always get the following error message: Mar 16 14:59:38 terradiem app/worker.1: [2017-03-16 14:59:37,844: ERROR/Beat] beat: Connection error: [Errno 111] Connection refused. Trying again in 32.0 seconds... Mar 16 14:59:38 terradiem app/worker.1: [2017-03-16 14:59:37,847: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. It seems that local settings (amqp://guest:**@127.0.0.1:5672//) override the cloudamqp setting but I can't identify why. Do you have any idea why Django would not use my settings?