Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with migrations
I created app on pyhonanywhere.com, but cant execute that command: python manage.py migrate If i try do it, appear error: Traceback (most recent call last): File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main_site_sponsor The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/conf/urls/__init__.py", line 50, in include File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/home/oriflame/site_oriflame/myvenv/lib/python3.4/importlib/__init__.py", … -
Django / PostgresQL jsonb (JSONField) - convert select and update into one query
Versions: Django 1.10 and Postgres 9.6 I'm trying to modify a nested JSONField's key in place without a roundtrip to Python. Reason is to avoid race conditions and multiple queries overwriting the same field with different update. I tried to chain the methods in the hope that Django would make a single query but it's being logged as two: Original field value (demo only, real data is more complex): from exampleapp.models import AdhocTask record = AdhocTask.objects.get(id=1) print(record.log) > {'demo_key': 'original'} Query: from django.db.models import F from django.db.models.expressions import RawSQL (AdhocTask.objects.filter(id=25) .annotate(temp=RawSQL( # `jsonb_set` gets current json value of `log` field, # take a the nominated key ("demo key" in this example) # and replaces the value with the json provided ("new value") # Raw sql is wrapped in triple quotes to avoid escaping each quote """jsonb_set(log, '{"demo_key"}','"new value"', false)""",[])) # Finally, get the temp field and overwrite the original JSONField .update(log=F('temp’)) ) Query history (shows this as two separate queries): from django.db import connection print(connection.queries) > {'sql': 'SELECT "exampleapp_adhoctask"."id", "exampleapp_adhoctask"."description", "exampleapp_adhoctask"."log" FROM "exampleapp_adhoctask" WHERE "exampleapp_adhoctask"."id" = 1', 'time': '0.001'}, > {'sql': 'UPDATE "exampleapp_adhoctask" SET "log" = (jsonb_set(log, \'{"demo_key"}\',\'"new value"\', false)) WHERE "exampleapp_adhoctask"."id" = 1', 'time': '0.001'}] -
Comparing string from sqlite before current string in django
In DB i have many users with parameters like group, password etc. But some users have equal groups, for example user1 have group "member", and user3 have group "member" so i want to put there into dropdown with group name. This code doesn't work for me, where is my mistake? <div class="dropdown"> {% for user in users %} {% if user.group != user.group %} <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> {{ group }} <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> *dropdown here* </ul> {% endif %} {% endfor %} -
Django - NoReverseMatch after adding a second form to a page
I have a Django webpage, on which a number of 'Presentation' icons are displayed. Each icon represents a version of Budget object that exists in the database (The Budget object has a one-to-many relationship with the Project object in the database- one Project can have many Budgets). The user can edit an existing Budget by clicking the 'Edit' button displayed on its Presentation icon (each Presentation represents a Meeting object in the database- and a Meeting has a Project as a foreign key). When the user clicks the 'Edit' button on an existing Presentation, or clicks the button to create a new Presentation, a form is displayed on the webpage, to allow the user to enter the details for that meeting. At the moment, they can also upload a 'Drawing' image to the form by clicking a 'Browse' button on the form, navigating to the location of the image file using the explorer window that's opened up, and clicking the 'Upload' button at the bottom of the form. When they've done this, the image file that's uploaded replaces the 'Browse' button on the form. I want to also add another button to the page to allow them to upload a … -
Set a custom queryset (select_related) for a list field in the admin change page?
I have an using the Django admin interface to manage a lot of objects, and one of the page is giving me issue, this page has a field to a related object (Foreign Key) that has a __str__ that also goes to its related objects, this make a lot of queries and is barely useable (Around 3000 queries to show the page as there are a LOT of objects). I would like to know if there is a way to set a custom queryset ? I would like to add a select_related or prefetch_related to this element. The part causing issue is this certificate request list : This model has this __str__ : def __str__(self): return "{state} certificate request for {domain} from {creation_date}".format( state=dict(self.STATUS).get(self.status), domain=self.domain.fqdn, creation_date=self.creation_date ) What would be the way to fix this ? How can I set a queryset on this part ? -
how to add a link to selectpicker
I have a selectpicker Which displays list of articles from database, and i want add a link that allows me to add a new article if it does not exist in DB class facture_form(forms.Form): description_article = forms.ChoiceField(required=True, widget=forms.Select(attrs={'class': 'selectpicker','data-live-search':'True'}), label="") def __init__(self, *args, **kwargs): super(facture_form, self).__init__(*args, **kwargs) articles = article.objects.values_list('ref_article','description') self.fields['description_article'].choices = articles -
Can't see background image on overlay
I have an overlay containing a django form and the background image doesn't show up. I have a silhouette image in the background and that fills the page, and ideally moves with the page size. Then a table on top in the centre of it containing my form which I have tried to make transparent. I was blindly fiddling with the css yesterday and it has disappeared! <iframe name="hiddenFrame" class="hide"></iframe> <div id="overlay"> <form id= "person-form" target='hiddenFrame' method = 'POST' action="" class="overlay-form" enctype="multipart/form-data">{% csrf_token %} <table id="add-person-form" class="overlay-table"> <tr></br></br>{{ personform.first_name }}</tr> <tr></br></br>{{ personform.surname }}</tr> <tr></br></br>{{ personform.email }}</tr> <tr></br></br>{{ personform.position }}</tr> <tr></br></br>{{ personform.contract_type }}</tr> <tr></br></br>{{ personform.mentor }}</tr> <tr></br></br><font color="white">Assign as a coach?&nbsp;</font>{{ personform.make_person_coach }}</tr> </table> </br> <input type = "submit" id = "save" value = "Add person"> </br> </br> <strong>Click here to [<a href='#' onclick='overlay()'>close</a>]</strong> </form> </div> <a href='#' class='class1' onclick='overlay()'>Add person</a> Here is my stylesheet #overlay { visibility: hidden; position: absolute; left: 0px; top: 0px; width:100%; height:100%; text-align:center; z-index: 1000; background-image:url('{% static 'tande/images/silhouette.png' %}'); background-repeat: no-repeat; background-size: 90%; background-position: center; } #overlay div { width:800px; margin: 100px auto; background: #cccccc; border: 1px solid #000; padding:15px; text-align:center; } form.overlay-form { width:800px; margin: 350px auto; } table.overlay-table tr td { background: rgb(54, 25, … -
Django ArrayField with different types
I need to configure a django.contrib.postgres.fields.ArrayField with a list of pairs in which the fist element is a float and the second, a small positive integer: data = [[1.23, 3], [2.42, 1], [3.72, 29]] How could I do this? Is it possible? I tried something like this, but didn't work: class MyModel(models.Model): my_field = ArrayField( models.FloatField(default=0), models.PositiveSmallIntegerField(default=0), null=True ) -
Working example of using pyspider with Django ORM?
Playing with nice PySpider project (http://docs.pyspider.org/en/latest/), but have no idea how to pass results for further processing via database, ideally into Django ORM. With defined custom ResultWorker http://docs.pyspider.org/en/latest/Working-with-Results/#working-with-resultworker pyspider hangs on start. from pyspider.result import ResultWorker class MyResultWorker(ResultWorker): def on_result(self, task, result): print(result) # do something with data Here is the project, that i'm using for testing. It parses top questions from StackOverflow: #!/usr/bin/env python # -*- encoding: utf-8 -*- # Created on 2017-02-03 10:38:54 # Project: so_question_analyzer from pyspider.libs.base_handler import * class Handler(BaseHandler): crawl_config = { } @every(minutes=24 * 60) def on_start(self): self.crawl('http://stackoverflow.com/questions?pagesize=50&sort=votes', callback=self.index_page) @config(age=10 * 24 * 60 * 60) def index_page(self, response): for each in response.doc('a[href^="http"]').items(): if each.attr['class'] == 'question-hyperlink': self.crawl(each.attr.href, callback=self.detail_page) @config(priority=2) def detail_page(self, response): return { "url": response.url, "votes": response.doc('.question [itemprop="upvoteCount"]').text(), "title": response.doc('h1 > a').text(), "text": response.doc('div > [itemprop="text"] p').text() } -
Django import statement within html
I'm very new to django and am trying to generate some thumbnails in my html programmatically. They do a similar thing in this tutorial, except they are populating a list from a database. <div class="container-fluid" > {% from os import listdir %} {% for img in listdir(get_static_prefix) %} <div class="row-md-3"> {% load static %} <img src="{% static "{get_static_prefix}/img" %}" class="img-thumbnail"/> </div> {% endfor %} </div> I get an error on the import line currently. Is what I'm trying to do possible, or is there a better way to do this? -
Are php memcached and django memcached storage different?
I am trying to implement Caching into my new Django project, the problem here is, the cache is set through a PHP server, and I need to read it from Django code. I am able to set the cache in Django, and read in Django, I can also set the cache in PHP, and read in PHP. But, I am not able to do it cross platform. i.e. I am not able to read the cache set in PHP, in Django and vice versa. Although, If I do a telnet localhost 11211 and fetch both the keys, I am only able to get the Keys set in PHP. I have done a pip install python-memcached installation to use Memcached with Python. So, my question is how do I use a common cache server for both Django and PHP? Here is my PHP snippet $memObj = new Memcached(); $memObj->addServer('localhost', 11211); $memObj->set('php_key', 'hello php'); var_dump($memObj->get('django_key')); #prints False echo $memObj->get('php_key'); #prints 'hello php' Following is my Python/Django snippet In settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'localhost:11211', } } In views, from django.core.cache import cache cache.set('django_key', 'Hello world') php_cache = cache.get('php_key') print(php_cache) # Outputs None django_cache = cache.get('django_key') print(django_cache) # Outputs … -
Django - serialize models to json for use as JavaScript object
I need to get the data from my models as an object in Javascript. I use this in my JS code ("data" being part of the context returned in my Django view) : var data= {{ data|safe }}; And in my view I have : context = {'data': { 'model1': serializers.serialize('json', model1.objects.all()), 'model2': serializers.serialize('json', model2.objects.all()), } The problems I have are : 1) I get an error in JS unless I use "safe" on the context variable, 2) Even if I use "safe", the object is unusable because it is just a string (i.e. data.model1[0] return "[" instead of the first element in the array). What is the proper way of doing this ? -
Run linux command from django view script
I try to use avconv for my web-app (Django on pythonanywhere). I have to extract a thumbnail from a video file. Using the bash console, I can run: avconv -ss 00:01:00 -i myapp/myapp/media/inputvide.mp4 -vsync 1 -t 0.01 myapp/myapp/media/videothumb.png This works fine. When I want to use this command by script (view.py) I tried: cmd = 'avconv -ss 00:01:00 -i '+inputfile+' -vsync 1 -t 0.01 '+outputfile os.system(cmd) inputfile is the path to my video and outputile is the path to my video + '.png' There are no errors thrown, but I can not find the output file anywhere in my folders? Any ideas? Thanks! -
Back slash in my Django url
My django url works only when I use a back after my url. Among the following two only second will work. First one will not work 1). http://10.165.19.167:8000/downloady9cHTML/Intro.html/ 2). http://10.165.19.167:8000/downloady9cHTML/Intro.html What can I do if I want my second url to work? i.e. I dont want to put a back slash at the end of my url? Thanks.. -
ModuleNotFoundError: No module named 'api.serializers'
I have an installation of Django 1.10 and Django REST framework. I am trying to perform the serealization but I get the following error: python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f3a65e76840> Traceback (most recent call last): File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/projects/django/webserv/lib/python3.6/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/home/user/projects/django/webserv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/home/user/projects/django/cfdi/cfdi/urls.py", line 22, in … -
Deploy django on apache with other other php sites
I have a problem with django deployment on apache. I want to start using apache with django but the problem I get is I'm unable to make the default django homepage work, however if I go the admin, it works without any problems. I'm attaching some images of my current settings in django. I'm using django in a virtual env with ubuntu 16.04. I don't want my other php sites links to be broken. I've tried so many times, still no progress. I have my ALLOWED_HOSTS set to localhost.I have also provided some screenshots on some of the parts for further description. 000-default.cnf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available … -
What is optimal way to find out mismatch records in columns over 100 million records?
Let's say I have more than 100 million record ,I am using postgres database with python.What is the optimal way to find out the data mismatch in columns ? col A abc bdc 12-12-17 123 output required : mismatch records at line 3,line 4 -
Django - Ldap Authentication Token
I have a Django server , that would authenticate the users against the LDAP . Once the user is authenticated , i need to set a authorization token to the user and send it in the response . How to do it ? Thanks -
How to filter values in a django 1.7 form using ModelForm?
The problem is that I have a model secciones that is associated with a user and a productos model that is also associated with a user and model secciones, class secciones(models.Model): name = models.CharField(max_length=50) user = models.ForeignKey(User) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(secciones, self).save(*args, **kwargs) def __unicode__(self): return self.name class productos(models.Model): user = models.ForeignKey(User) secciones = models.ForeignKey(secciones) name = models.CharField(max_length=50) image = models.ImageField(upload_to = 'productos') precio = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) descripcion = models.TextField(max_length=300, null=True,blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(productos, self).save(*args, **kwargs) def __unicode__(self): return self.name I am creating a form so that the user can enter a new product in the productos model, but I just want to leave the sections of the model secciones of the user that I log in This is the view def agregar_producto(request): if request.method == "POST": modelform = AgregarProducto(request.POST,request.FILES) print modelform if modelform.is_valid(): modelform.save() return redirect("/editar-perfil/") else: modelform = AgregarProducto() return render(request, "home/AgregarProducto.html", {"form":modelform}) This is the form class AgregarProducto(forms.ModelForm): class Meta: model = productos How can I get the form to display only the sections of the model secciones of the user that logged in -
Mixing Websockets and REST
I'm writing a RESTfull api, where for example user can create new threads or new posts in a thread. This is where I would use normal POST request. My API also allows users to send messages to each other. And when a user receives a message I want notification in browser, this is where I would use websockets instead of polling every few seconds. My questions are Since I already have open connection with websocket where messages will come, should I also use this connection to send messages, create new threads or posts? Can I use POST request for creating messages and websockets to receive them in realtime and GET request to get history of messages? Is this good practice? I'm using django rest framework, which handles validation of fields for me, how would I handle validation if I create resource using websocket instead of normal POST request. I'm farily new in developing a RESTfull API, and I have only started developing with websockets. Sorry for any stupid questsions that may seem so logical for you :) Thanks -
Remove the first-line block during HTML rendering by marked
I am using marked to parse markdown content. During rendering, I get the first line of every post in blocks. How to get rid if it ? Image : Displays first-line as a block I am using marked cdnjs https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js I am using jQuery 1.12.4 (minified) <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> I am using class = "content-markdown" to allow javascript to find the contents to parse. <script type="text/javascript"> $(document).ready(function(){ $(".content-markdown").each(function(){ var raw_content = $(this).text() var marked_content = marked(raw_content) $(this).html(marked_content) }) }) </script> The content : <div class = "content-markdown"> <p> {{post.body|safe}} </p> </div> -
queryset objects not appending in mongoengine
this is models.py, I am trying to add the journals to the matched tags,i am unable to append the tags,i am getting an empty list. class Journal(Document): title = StringField() journal_title = StringField() abstract = StringField() full_text = StringField() class GeneratedTag(Document): title = StringField() journals = ListField(ReferenceField(Journal)) here to code to append the tags, here i am generating the tags checking whether the tags are matched in journal title,if it matches i append to Generated tag object for tag in triwords: t = GeneratedTag(title = tag) reg = re.compile('.*%s.*'%t.title, re.IGNORECASE) journal_queryset = Journal.objects(__raw__={'title': {'$regex': reg}}) for j in journal_queryset: GeneratedTag.objects(id=t.id).update(add_to_set__journals= j) t.reload() After the append , when i check the GeneratedTag objects, journal field is showing empty. To retrieve the results: for g in GeneratedTag.objects: print i.title print i.journals #Is this correct method to query a ListField with reference Any help would be appreciated...Thanks in Advance...:) -
Is it possible to modify http request timeout in Auzre App Service - Django
I tried modifying the timeout by multiple ways: Modifying the web.config file. <system.web> <httpRuntime targetFramework="4.5" executionTimeout="600"/> </system.web> Modifying SCM_COMMAND_IDLE_TIMEOUT value in application settings in azure portal. One more solution I got here: https://azure.microsoft.com/en-us/blog/new-configurable-idle-timeout-for-azure-load-balancer/. I think this doesn't apply to azure app service. None of these are working. Is there a way we can modify timeout value? -
Can i make google reCaptcha 2.0 only show the checkbox every time
I'm working on a voting application where people can vote as many times as they want, and i would like to have a reCaptcha checkbox in it, but rather than making people have to fill check the images thingy after a few votes, i'd rather have them just have the fill the checkbox every time. I tried changing the security level to the lowest setting but it keeps showing the test after about two or three votes. I know it's not a very good idea security wise, but it just doesn't feel good to have people check several images every time rather than just clicking it once which would already to some fine help holding back spambots. I'm working on a Django application and implemented reCaptcha with Django-reCaptcha 2 . -
Regex to accept anything in url django
I am trying to have a url that accept anything passed in the url parameters but when i am trying it says Http 301 redirect.. my url is /reply/?agent_type=web&input=anything and my regex for this in django url is url(ur'^reply/(.*)/$', views.visit),