Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view didn't return an HttpResponse object
I'm having an issue with getting ajax to work with my django view. The exact error is CustomMembers.decorators.formquestioninfo didn't return an HttpResponse object. It returned None instead. The view is limited by a custom decorator which is the following. def is_god_admin(f): def wrap(request, *args, **kwargs): # This checks to see if the user is a god admin. If they are not, they get thrown to their profile page if 'userID' not in request.session.keys() and 'username' not in request.session.keys(): return HttpResponseRedirect("/Members/Login") else: # lets check the roleID to what ID we need. god_admin = Roles.objects.get(role_name='System Admin') if request.session['roleID'] != god_admin.id: return HttpResponseRedirect("/Members/Profile/" + request.session['userID']) return f(request, *args, **kwargs) wrap.__doc__ = f.__doc__ wrap.__name__ = f.__name__ return wrap The view right now only contains a return to show the template along with a check if ajax was used to post a request. View @is_god_admin def formquestionsinfo(request, formid, catid, mainid): """ Displays the forms information.""" # need the following values in both post and get methods forms = Form.objects.all() if request.is_ajax(): print('ajax request') # this fires then errors else: return render(request, formquestions.html, 'forms':forms) # this works just fine with a get request The ajax code that is being executes is: (the getCookie is based … -
Django + Postgres: save JSON string directly into model as JSON type
I have a Django model in which I would like to save schema-less key-value metadata, so I'm using a JSONField. The key-value data is a Pandas series, which is not JSON-serializable by default (due to numpy.int64, numpy.float64 types), so I use the handy series.to_json() which returns an already serialized JSON string. To save it to my model, I run json.loads on it. But I know that json.dumps is called on this when the data is saved to Postgres. How can I avoid this unnecessary deserialization/re-serialization step? Code example: def create_model(pandas_series): mdl = Model() metadata = pandas_series.to_json() # gives a JSON string mdl.metadata = json.loads(metadata) # string->dict, then dict->string mdl.save() -
Making iOS or Android apps that makes REST API calls to Django, and setting up backend servers
My friends and I want to build an app iOS and Android that makes REST API calls to Django, and Im in charge of setting up the backend server. I've heard a lot of things like about nginx and stuff, but I can't find anywhere how to start things off and make a useable server and such. Ive heard good things about Digital Ocean, but I dont know where to start off. Thanks for your help! -
service abstraction layer for django
I would like to know how I can set up an abstraction layer and access the correct service depending on my settings (local or prod) ? How would you you structure this and adjust your views to access the right service ? -
How to add an external object as a field panel in Wagtail CMS
I've a pre-existing Django project where I started a Wagtail-driven app. In the Django project, I have a model Map which I need to make available also in the wagtail-app. Django-project Map class in model.py class Map(..): Wagtail-app model.py: class Wagtail-appPage(Page): main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) map = models.ForeignKey(Map, related_name="map_set", null=True, blank=True) date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), FieldPanel('body', classname="full"), ImageChooserPanel('main_image'), <MapChooserPanel>('map') ] My goal is to add the possibility to load map objects in a wagtail panel (for ex. MapChooserPanel()) in the wagtail/admin, as it happens for standard images. How would you proceed? Does it sound very difficult? I'm totally new to Wagtail.. Thank you in advance for any help you will provide. -
Django-photologue retrieve images/galleries on angular2 frontend
I am using Django-photologue to create a few galleries and attaching them to specific model. On backend side everything works fine. I have written a model like following: class News(models.Model): title = models.CharField(max_length=150) gallery = models.ForeignKey(Gallery, related_name='news') def __str__(self): return u"%s" % (self.title) How can I retrieve those galleries/ photos on my Angular2 frontend when I am accessing say News model? I wrote a serializer like following, but looks like it's not the way to do so. class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' -
export cx_oracle cursor to python django class
I have an Oracle table that i want to import into a Django class. models.py class Element(models.Model): id = models.CharField(max_length=10) name = models.CharField(max_length=20) description = models.TextField() class Meta: ordering = ["id", "name"] unique_together = (("id", "name"),) def __str__(self): return self.name **Oracle table: TB_NAME ** +----+------+---------------+ | id | name | description | +----+------+---------------+ | 1 | n1 | description1 | | 2 | n2 | description2 | | 3 | n3 | description3 | | 4 | n4 | description4 | | 5 | n5 | description5 | +----+------+---------------+ db_manage.py import cx_Oracle try: con = cx_Oracle.connect("user/password@host:port/sid") cur = con.cursor() cur.execute("select * from TB_NAME ") except: print ("connection error") please help me to insert all the elements to the class "Element" thanks! -
Add context to the view for the pages of Mezzanine
Context: I am making a website using Django Mezzanine. To use an HTML template, I made an app extending the Page mezzanine model and added a class extending Orderable with a one to many relation. The second class represent the different rows of the page. Now I want to make the rows load "on scroll", so I added Django EL(Endless) Pagination, to use the "Twitter-style Pagination". For this, if I do understand, I need to change the view of the page, and set it to something like: def entry_index(request, template='myapp/entry_list.html'): context = { 'entry_list': Entry.objects.all(), } return render_to_response( template, context, context_instance=RequestContext(request)) However, I want to keep the mezzanine page view. I saw that the code for the view as an extra_content attribute, so I supposed that I can use that. But can I just "extend" this view? If yes how should I proceed? -
XlsxWriter autofilter oldest to newest date Django/Python
Does anyone knows how can I set up a cell to filter the date from the oldest to the newest using XlsxWriter? I have checked the XlsxWriter documentation, but there is nothing straight on that. I can upload my code if is needed. Than you for your time. -
How can I serialize (with Django REST API) when class relates to the same generic relation multiple times?
I have a class that has multiple references to the same generic class for different information: class Resort(models.Model): id = models.PositiveIntegerField(_('HapNr.'), primary_key=True) symbol = models.CharField(_('Kurzzeichen'), max_length=3, blank=True) short_description = GenericRelation('MultiLingualText', verbose_name=_('Beschreibung (ML)'), related_query_name='resortshortdescriptions') long_description = GenericRelation('MultiLingualText', verbose_name=_('Einleitung (ML)'), related_query_name='resortlongdescription') class MultiLingualText(models.Model): language = models.ForeignKey(hmodels.LanguageCode, verbose_name=_('Sprache')) valid_from = models.DateField(_('Gültig ab'), default=timezone.now) text = models.TextField(_('Text')) content_type = models.ForeignKey(ContentType, verbose_name=_('Typ')) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() atu_id = models.CharField(_('ATU Text Id'), max_length=12, editable=False, blank=True) atu_context = models.CharField(_('ATU Kontext'), max_length=1, editable=False, blank=True) When I need to work with this class using the Django Admin I have two Inlines, each with a queryset selecting the correct texts for that relation. This works fine. I tried doing something similar by using individual serializers and viewsets for each relation, but when I retrieve a resort, it still shows all texts with each relation. class ResortSerializer(serializers.HyperlinkedModelSerializer): short_description = MultiLingualTextSerializerRSD(many=True, read_only=True) long_description = MultiLingualTextSerializerRLD(many=True, read_only=True) class Meta: model = Resort class MultiLingualTextSerializerRSD(serializers.HyperlinkedModelSerializer): language = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = MultiLingualText class MultiLingualTextViewSetRSD(viewsets.ModelViewSet): serializer_class = MultiLingualTextSerializerRSD queryset = MultiLingualText.objects.exclude(atu_id='').order_by('resort', 'content_type', 'object_id', '-valid_from') So basically my question is, how can I use different querysets for each set of texts? Or is this at all possible? Regards, Richard -
Celery infinite task which listens to a queue
I've got a celery task which is supposed to run in infinite loop, listening to a few queues (not related to Celery internals) in RabbitMQ. When message is retrieved from queue this long running task dispatches this message to be processed by some other task. How to implement such a use case appropriately in Celery? I run celery with concurrency 3 and Ofair flag. My current observation is that after a few days this setup stops processing tasks from celery internal queue. It seems that this long running tasks is being restarted for some reason and ultimately all 3 workers are busy only with this long running task, so there are no workers left to process tasks from celery queue. I thought about some file-based lock to make sure only one worker is able to get the lock and become this long-running task, but not sure if it's a good option, i think there are better solutions for this problem. def init_couriers_consumers(self): logger.info("lock acquired") logger.info("TASK ID: {}".format(init_couriers_consumers.request.id)) with Connection('amqp://guest:guest@localhost:5672//') as conn: couriers_consumer_worker = ConsumerWorker(conn) couriers_consumer_worker.run() couriers_consumer_worker.should_stop = False # cache.set('reboot', False) self.retry(countdown=2) class ConsumerWorker(ConsumerMixin): def __init__(self, connection): self.connection = connection self._create_queues() def _create_queues(self): from courier.models import Courier self.queues = [] … -
Combining multiple filters on querysets with django-filter
Say, I have the following two Django models: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() author = models.ForeignKey(Author) With django-filter, how can I write a FilterSet, that allows me to filter somewhat like: Author.objects.filter( (Q(book__name__contains='How') & Q(book__pages=100)) | (Q(book__name__contains='Why') & Q(book__pages=50)) ) That is, I want to have a set of filter Fields, that are all applied to a related model and that I can combine. In my case, that set contains many more fields, so a custom MultiValueField is probably not really applicable. Is there any standard way to solve this using django-filter, or should I implement my own filtering logic in the view? -
MultiSelectField in django
I have a form that contains a MultiSelectField and when I choose 2 or more options they are displayed next to each other. I want to know if there is an option to make every selected option in a newline so that it will be clearer . thanks this is the case : x = MultiSelectField(blank=True, null=True, help_text="choose one or more options", choices=(('text1', 'text1'), ('text2', 'text2'), ('text3', 'text3'), ('text4', 'text4'), ('Other', 'Other'),)) Output when I select text1 and text2 : text1,text2 -
Django Query - create with foreign key in statement?
im getting the error: ValueError: Cannot assign "<ConfigTemplates: STR-RTR-01-ADSL>": "Circuits.internet_device" must be a "ConfigTemplates" instance. When i try create a record using queryset. I know its telling me but not how to solve it. below is the code, im basically copying data from one model to another and the fields are the near enough the same. the internet_device field is a foreign key in both tables, so i thought it would just work, but im getting the error instead. data = ShowroomConfigData.objects.exclude(id=56) for sr in data: c_data = CircuitInfoData.objects.filter(showroom_config_data=sr.id) d = SiteData.objects.get(location=sr.location) for c in c_data: new_data = Circuits.objects.create( site_data = d, order_no = c.order_no, expected_install_date = c.expected_install_date, install_date = c.install_date, circuit_type = c.circuit_type, circuit_preference = c.circuit_preference, circuit_speed = c.circuit_speed, circuit_bearer = c.circuit_bearer, provider = c.provider, ref_no = c.ref_no, dsl_username = c.dsl_username, dsl_password = c.dsl_password, dsl_tel_no = c.dsl_tel_no, install_location = c.install_location, cost_per_month = c.cost_per_month, contract_length = c.contract_length, service_service_contacts = c.service_service_contacts, subnet = c.subnet, default_gateway = c.default_gateway, subnet_mask = c.subnet_mask, internet_device = c.internet_device ) -
Download a file, the name is not known
I have an API for downloading excel file. The API URL is http://domain.com/export. The name of this file is not predictable. Also, I need to pass few parameters while calling the API URL. What is the best way to do it at the frontend (JS, jQuery)? It has to support IE 9+. For a test, I have developed one hidden form and jQuery submit. It works, but in the end, I need to put the download button to every row in a table and export data related to the row. So maybe it is not the best solution. My demo solution: HTML <form id="tool-export" method="post" action="export/">{% csrf_token %} <a id="export-link" class="btn btn-sm btn-primary" href="#">DOWNLOAD</a> </form> JS $('#export-link').click(function(e) { window.onbeforeunload = null; e.preventDefault(); var link = $(this); var form = link.closest('form'); var project_id = proj_id.find(":selected").val(); var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id); form.append($(input)); var project_type = proj_type.val(); input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type); form.append($(input)); form.submit(); }); -
Accessing list of objects inside a dictionary
How would i print out dictionary values that are a list of objects. More specifically attributes from the objects Output from a print of the dictionary for keys,values in Dict.items(): print(keys) print(values) Five [<VocabContent: Seven - 7>, <VocabContent: Ten - 10>, <VocabContent: Six - 6>, <VocabContent: Eight - 8>, <VocabContent: Five - 5>] Eight [<VocabContent: Ten - 10>, <VocabContent: Eight - 8>, <VocabContent: Six - 6>, <VocabContent: Five - 5>, <VocabContent: Seven - 7>] These objects have spanish and audio attributes. I'm trying to print the objects spanish attribute with for keys,values in Dict.items(): print values.spanish But it does not work. My webpage just returns a server error 500 How can i access the object attributes from the dictionary Thanks -
Can't save images in jpg and jpeg format
I have application in Django 1.8.15 (env: python2.7). I want to upload images but I can upload only png files (not jpg or jpeg) I had installed: Pillow==2.6.1, libjpeg, libjpeg-dev, libfreetype6, libfreetype6-dev, zlib1g-dev I get an error: ValueError at /admin/files/select/1 Invalid quality setting Exception Type: ValueError Exception Value: Invalid quality setting I have no idea how to solve this problem. -
Migrate from User to AbstractUser in Django
I need to add fields in User model and for this purpose i decide to use AbstractUser. How can i migrate from User to AbstractUser? Using makemigration and after this migrate does not work. IN SF i found only solution for South, which deprecated and a lot of commands does not exist now. Database - PostgreSQL ValueError: Unhandled pending operations for models: api.user (referred to by fields: admin.LogEntry.user, api.Album.user, api.Like.user, api.Photo.user) models.py: import os import uuid from django.db import models from django.contrib.auth.models import AbstractUser def get_image_path(instance, filename): return '{}.{}'.format(uuid.uuid4(), filename.split('.')[-1]) class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) avatar = models.ImageField(upload_to=get_image_path, blank=True) location = models.CharField(max_length=30, blank=True) class Album(models.Model): user = models.ForeignKey(User, related_name='albums', on_delete=models.CASCADE) title = models.CharField(max_length=80, default='New album') creation_date = models.DateField(auto_now_add=True) private = models.BooleanField(default=False) @property def total_photos(self): try: return Photo.objects.filter(album_id=self.id).count() except Photo.DoesNotExist: return 0 @property def total_likes(self): photos = Photo.objects.filter(album_id=self.id) return sum(x.total_likes for x in photos) def __str__(self): return self.title class Meta: ordering = ['-creation_date', ] class Photo(models.Model): user = models.ForeignKey(User, related_name='photos', on_delete=models.CASCADE) album = models.ForeignKey(Album, related_name='photos', on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=80, default='New photo') image = models.ImageField(title, upload_to=get_image_path) creation_date = models.DateField(auto_now_add=True) @property def total_likes(self): try: return Like.objects.filter(photo_id=self.id).count() except Like.DoesNotExist: return 0 @property def private(self): if self.album: return self.album.private return False def … -
super() method resolution in python
I am creating two custom widgets for django to use the chosen jQuery plugin, one for ForeignKey model fields and the other ManyToManyField. So, respectively, I override forms.Select and forms.SelectMultiple. I put the common functionality in a common parent class as: class ChosenWidgetParent(object): class Media: css = { 'all': ( 'sub/staticfull/css/plugins/chosen/chosen.css', ) } js = ( 'sub/staticfull/js/jquery-2.1.1.js', 'sub/staticfull/js/plugins/chosen/chosen.jquery.js', ) def render(self, name, value, attrs=None, **kwargs): attrs['chosen'] = 'chosen' rendered = super().render(name, value, attrs, **kwargs) return rendered + mark_safe(u''' <script> $(document).ready(function () { $('#id_%(name)s').chosen({ disable_search_threshold: 10, }) }) </script>''' % {'name': name}) Note there is a call to super, which should refer to Select's and SelectMultiple's render methods respectively. And then, I define my classes: class ChosenWidgetMultiple(widgets.SelectMultiple, ChosenWidgetParent): pass class ChosenWidget(widgets.Select, ChosenWidgetParent): pass This does not work unfortunately, but when I swap the parent classes, it works. class ChosenWidgetMultiple(ChosenWidgetParent, widgets.SelectMultiple): pass class ChosenWidget(ChosenWidgetParent, widgets.Select): pass Can someone explain me why? -
Dynamic URL by using java script variable
I am developing a RP in SSO and I get the user data by java script and JSON: if (token !== null) { $.get('http://OP/userinfo/?access_token='+token, function( data ) { JSONdata= JSON.stringify(data); alert('USERINFO: '+ JSONdata); window.location.replace('http://RP/account/'+data.email); }); } After getting the data page redirect to new page with addition of email address. So my problem is how should I change the urls.py and views.py of my django project in order to produce those pages. -
django - applications in a project
I am little bit confused about the term application in a django project. I know that applications can be built that can be part of a project and the reason of this is to create reusable components (BTW it is brilliant idea). I am building a web applications that will have 3 admin page (managing 3 different entities, eg. list/update/create/delete them). Also I will have a monitoring page and 1-2 other pages. The question is that should I use 5-6 separate applications (3 + 1 + 1-2) or just one? Or create one for the administration and other one for the others? I don't want to use them outside this web application. I began with the 5-6 separate applications but I have common stuff, like base structure (header on top, menu on left and footer at the bottom) of the web app, the jquery javascript file, etc. How would you split the django web app? Or shouldn't I worry about using more applications? Not sure it is important but coming from the Java world. Thanks, V. -
How to add users listing grid in customers listing page in django
I have created customer app and registered model in django admin, where I want to display users listing grid in customer listing. How do I do that. I 'm not getting exactly how to extend the current users listing template in customer listing in django admin. How do I extend only users listing grid block to show up in customers listing. -
pass data from database to template cms plugin
I want to pass data from models to template using CMS_plugins.py I've made an app and standalone works. When i open link manualy localhost:port/en/post_list.html all values are shown and works. If i go on admin page and add plugin, values in mysql are stored but not presended in my template.html . I want to pass values in template.html class pricing(CMSPluginBase): model = Post name = _("pricing") render_template = "post_list.html" cache = False def render(self, context, request, placeholder): context = super(pricing, self).render(context, request, placeholder) return context plugin_pool.register_plugin(pricing) -
How to avoid Django sub thread being killed by uWSGI respawn
I created a web server by Django + uWSGI. The basic flow is: when a request is received, Django will initiated a sub thread by python build-in lib "Threading" to write db asynchronously, and in main thread it will respond immediately back to client. How, uWSGI sometimes will respawn the worker process(maybe when there is no request handling by the process?), which caused the background sub thread is also killed even when it's not finished yet. Any clue to avoid uWSGI not to respawn a worker process which has a running sub-thread? uWSGI respawn log: DAMN ! worker 4 (pid: 31161) died, killed by signal 9 :( trying respawn ... uWSGI ini config (version 2.0.12): [uwsgi] # Django's wsgi file wsgi-file = /home/fh/dj_uwsgi/dj_site/dj_site/wsgi.py master = true processes = 10 http = :8001 threads = 2 enable-threads = true http-timeout = 10 max-requests = 5000 chmod-socket = 664 vacuum = true pidfile = /home/fh/dj_uwsgi/dj_site/uwsgi.pid daemonize = /home/fh/log/uwsgi_dj.log Django(version 1.8) app pseudo code: in handlers.py: import threading class SubThreadClass(threading.Thread): daemon = True def run(self): # actions to write db def myHandler(): my_sub_thread = SubThreadClass() my_sub_thread.start() in views.py: from handlers import myHandler def url_handler(request): myHandler() return HttpResponse() -
Unable to connect to pyodbc with Nginx and gunicorn
I am getting: [01000] [unixODBC][Driver Manager]Can't open lib '/usr/local/nz/lib64/libnzodbc.so' : file not found (0) (SQLDriverConnect)" error while creating connection using PyODBC. This works fine when I use it via Django Development server. But on using it via. Gunicorn and Nginx, it fails. I faced this issue in the past (while configuring the Development server) when: Some of the libraries needed by UnixODBC were missing. Since, it is working with Django development server, this couldn't be the issue When environment variables PATH and LD_LIBRARY_PATH do not had the path to my driver. Most likely I think 2nd is the cause. I tried setting up the environment variables in /etc/profile and /etc/environment but no luck. Does anyone have idea regarding what might be wrong here?