Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
missing static file django cms
I have working with django cms and I have this error http://127.0.0.1:8000/static/ 404 (NOT FOUND) my setting file is this import os from base import * from config import * gettext = lambda s: s DATA_DIR = os.path.dirname(os.path.dirname(__file__)) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '...' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition ROOT_URLCONF = 'portal.urls' WSGI_APPLICATION = 'portal.wsgi.application' LANGUAGE_CODE = 'en' TIME_ZONE = 'America/New_York' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(DATA_DIR, 'media') STATIC_ROOT = os.path.join(DATA_DIR, 'static') STATIC_HEALTH_URL = '' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'portal', 'static'), ) I create a new extension like this this works perfectly, after that I reorder my aplication see image. and now when I use the component save the image but dont showme nothing. Any idea! -
Can't decode JSON response from Javascript in Python
I'm trying to send a simple message using JQuery.post(), but it gives this error on Python : JSONDecodeError at /editPessoa/ Expecting value: line 1 column 1 (char 0) Javascript : data = { "pessoa" : [ ["1","joão","321","camarão"] ] } $.post('editPessoa/', data, function(response) { updatePessoas(); }, 'json'); views.py : @csrf_exempt def editPessoa(request): data = json.loads(request.body.decode('utf-8')) print(data) return HttpResponse('Done!') The error is raised while trying to print, if I remove the .decode() it raises that bytes can't be printed -
Using braces in blocktrans
Hoe can I escape {{ or }} inside a blocktrans tag. Solutions like {% verbatim %) or {% templatetag openvariable %} are not allowed inside blocktrans -
Django POST method giving 500 internal server error
I am currently working on a Django project. When I am using GET request it is working fine, but in case of POST request it is giving me 500 internal error. I think it has something to do with csrf token and I have no idea what to do with it or how csrf will solve my error. I have also set DEBUG = False and ALLOWED_HOSTS = ['*'] in settings.py, but then also I am getting the same error: Server Error (500) Here is some piece of my code: urls.py from django.conf.urls import patterns, url urlpatterns = patterns( 'project.views', url(r'^users/$', 'userList', name='userList'), url(r'^users/(?P<pk>[0-9]+)$', 'userDetail', name='userDetail'), ) This is a function from views,py @api_view(['GET', 'POST']) def userList(request): if request.method == 'GET': user = users.objects.all() serializer = UsersSerializer(user, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UsersSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the command I am using in the terminal: curl -X POST http://127.0.0.1:8000/user/ -d '{"username":"root", "email":"abc@gmail.com"}' -H "Content-Type: application/json" Django version number : 1.9 -
Django Template Data
I have the following models: class Contactnumber(TimeStampedModel): phone_number = models.CharField(max_length=100, unique=True) contact = models.ForeignKey(‘contacts.Contact') class Contact(TimeStampedModel): contact = models.CharField(max_length=100, db_index=True, verbose_name='Contact Name') practice = models.ManyToManyField(‘practice.Practice’, related_name=“contacts",) class Practice(TimeStampedModel): practice = models.CharField(max_length=150, db_index=True, verbose_name='Practice Name') I have a template including data tables in which I want to show the following: Practice, Contact, Contact Phone The following gives me the contact for the practice: {% for contact in practice.contacts.all %} {{ contact }} {% endfor %} My question is how do include the contact phone number as I seem a bit lost. Any help would be appreciated. Apologies if this is a simple question! -
Executing a function as source in Django's Serializer
I have the following models: class A(Model): pass class B(Model): a = ForeignKey(A, related_name = 'b') b_field = CharField(max_length=64) And I now want to serialize an A object, in which I want to have the first b object. I used to have this code: class BSerializer(ModelSerializer): class Meta: model = B fields = '__all__' class ASerializer(ModelSerializer): b = BSerializer(source='b.first') class Meta: model = A fields = '__all__' This used to work, but now my unit tests are failing: AttributeError: Got AttributeError when attempting to get a value for field `b_field` on serializer `BSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `method` instance. Original exception text was: 'function' object has no attribute 'b_field'. Obviously, b.first is a function, and that indeed has not such an attribute. I want the source field however to execute that function. I tried the following line: b = BSerializer(source='b.first') But that gave met the following error: AttributeError: Got AttributeError when attempting to get a value for field `b` on serializer `ASerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `A` instance. Original exception text was: 'RelatedManager' object has no … -
How to use Async Task in django 1.10 to run in background?
I am looking for an option to use in my Django 1.10 web project where I need to run some task every hour. I know I can use DJCELERY but it is not updated for Django 1.10 and I am getting these errors, Error fetching command 'celerymon': type object 'BaseCommand' has no attribute 'option_list' Command 'celerymon' skipped Error fetching command 'celerybeat': type object 'BaseCommand' has no attribute 'option_list' Command 'celerybeat' skipped Error fetching command 'celeryd_multi': type object 'BaseCommand' has no attribute 'option_list' Command 'celeryd_multi' skipped Error fetching command 'celeryd': type object 'BaseCommand' has no attribute 'option_list' Command 'celeryd' skipped Error fetching command 'celerycam': type object 'BaseCommand' has no attribute 'option_list' Command 'celerycam' skipped Error fetching command 'celery': type object 'BaseCommand' has no attribute 'option_list' Command 'celery' skipped Error fetching command 'celeryd_detach': type object 'BaseCommand' has no attribute 'option_list' Command 'celeryd_detach' skipped Error fetching command 'djcelerymon': type object 'BaseCommand' has no attribute 'option_list' Command 'djcelerymon' skipped So is there any other option that I can use to run task(s) in background? Does django offer anything like this in new version? Thank you. -
JavaScript function not saving changes to HTML 'date' field on form
I have the following JavaScript function, which should be listening for changes to a 'date received' field on a form on a page in my Python/ Django project: $('#id_date_received').on('change', function messageDepositPaid(){ /* ERF(18/11/2016 @ 1500) The 'if' statement below is only checking for when the original-value is null, so if the original value isn't null, when the value is changed, it won't be saved... add an else to save the value if it's changed when the original value isn't null, Or- remove the 'if', so that the save always happens... */ /*if ($(this).data('original-value') === ''){ Code inside this commented 'if' should be indented if I uncomment the 'if' */ if (window.confirm("Would you like to send an email confirming we have received a deposit?")) { var date = $(this).val() if (date){ date = date.split('/') var new_date = []; new_date = new_date.concat(date[2]).concat(date[1]).concat(date[0]); new_date = new_date.join('-'); } if (new_date != $(this).data('original-value')){ // CDI fee date has been changed from nothing to something console.log("It's changed") // Set the original-value so it won't send multiple times $(this).data('original-value', new_date) // Send email to relevant people var url="{% url 'comms:open_email_template' project.id %}?template=5" console.log('Url', url) $.post(url) .done(function(response){ console.log('Email sent') }) } } /*} */ else{ var date = … -
DRF returns 404 not found on DELETE
When I request a 'DELETE .../id/delete', I get a 404 not found in response by DRF. I have a successful API with one part of my model, but this error happens on an other part. I can't see the difference, and I don't know how to debug it. url.py: url( regex=r'^thirdparties/(?P<pk>[0-9]+)/delete/', view=ThirdPartyDestroyAPIView.as_view(), name='thirdparties_delete' ), view.py: @python_2_unicode_compatible class ThirdPartyDestroyAPIView(LoginRequiredMixin, PermissionRequiredMixin, CurrentUserThirdPartiesMixin, DestroyAPIView): serializer_class = ThirdPartyReadSerializer permission_required = 'cashflows.delete_thirdparty' raise_exception = True my request: DELETE /api/v1/thirdparties/5/delete/ my response: django_1 | 172.18.0.1 - - [18/Nov/2016 16:02:11] "DELETE /api/v1/thirdparties/5/delete/ HTTP/1.1" 404 - -
In Django ORM, get records whose field value is maximal in a queryset
Consider a simple model: class Person(models.Model): name = models.CharField(max_length=256) age = models.IntegerField() I would like a single expression which returns a QuerySet of all of the Person objects whose age is maximal in the table. I.e. say there are 20 Person records, and the largest age is 70 but there are 3 distinct records which have that value. I would like my queryset to contain exactly those 3 Person objects. I suppose I could do: Person.objects.filter(age=Person.objects.aggregate(models.Max('age'))['age__max']) But wow that seems like a real mess. And it hits the database twice. Yuck. Better alternatives? -
I am facing this error while running django-admin runserver command
I am facing this error and cannot run django-admin runserver command "django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. " -
Django updating model with composite primary keys
I am trying to update a model, with two primary keys. Since django is not officially supporting it, I am using the workaround: class myModel(models.Model): class Meta: unique_together = (('key1', 'key2'),) key1= models.IntegerField(blank=False, primary_key=True) key2= models.CharField(blank=False, max_length=30) attr3 = models.CharField(max_length=30) attr4 = models.CharField(max_length=30) But whenever I try to update an existing object I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: myApp_myModell.key1, myApp_myModel.key2 I tried the following to update my model: myModel.objects.update_or_create( key1=kw1, key2= kw2, defaults={ 'attr3':attr3_str, 'attr4':attr4_str, }) and the following: defaults={ 'attr3':attr3_str 'attr4':attr4_str, } try: obj = myModel.objects.get(key1=kw1, key2=kw2) for key, value in defaults: settatr(obj, key, value) obj.save() except myModel.DoesNotExist: print("DOESNT EXISIT") new_values = {key1': kw1, 'key2': kw2} new_values.update(defaults) obj = myModel(**new_values) obj.save() Any ideas how I can update my model without getting an integrity error? -
Define special html files django
I'm beginning to use The Django Framework and I'm reading lots of tutorials but I get a problem and I would like some explanations to solve it. My project is named : Etat_civil My first app is named : BirthCertificate I have the views.py file in BirthCertificate App : from django.shortcuts import render, redirect from django.http import HttpResponse # Create your views here. def BirthCertificateAccueil(request) : # Fonction permettant de créer la page d'accueil de la rubrique Acte de Naissance text = """ <h2 align="center"> Vous êtes actuellement dans la partie : Acte de naissance </align> </h2> <p> Vous souhaitez : </p> <p> </p> <p> * Créer un acte de naissance </p> <p> * Consulter un acte de naissance </p> <p> * Modifier un acte de naissance </p> <p> * Supprimer un acte de naissance </p> """ return HttpResponse(text) def BirthCertificateCreationAccueil(request) : # Fonction permettant de créer la page de création du formulaire de la partie : Acte de Naissance text = """ <h2 align="center"> Vous allez désormais pouvoir créer un formulaire d'acte de naissance </align> </h2> """ return HttpResponse(text) My question is : I must have to create a templates directory in order to put some .html files and … -
Django: ForeignKey not None in save method when setting it to null from Django Admin
This is my model: class Becario(models.Model): apellido1 = models.CharField(max_length=200) apellido2 = models.CharField(max_length=200, blank=True) dni = models.CharField(primary_key=True, validators=[dni_validator], max_length=8) estado = models.CharField(max_length=1, choices=ESTADOS, default='N') plaza_asignada = models.OneToOneField(Plaza, on_delete=models.SET_NULL, blank=True, null=True) and this is my overriden save method: def save(self, *args, **kwargs): print(unicode(self.__plaza_previa) + ' - ' + unicode(self.plaza_asignada)) # If an object is assigned to a Plaza object if self.__plaza_previa == None and self.plaza_asignada != None: self.estado = 'A' HistorialBecarios.objects.get_or_create(dni_becario=self.dni, anyo=datetime.datetime.now().year) # If an object becomes not assigned elif self.__plaza_previa != None and self.plaza_asignada == None: self.estado = 'R' try: hist = HistorialBecarios.objects.get(dni_becario=self.dni, anyo=datetime.datetime.now().year) hist.fecha_renuncia=datetime.datetime.now() hist.save() except ObjectDoesNotExist: print('historial does not exist') super(Becario, self).save(*args, **kwargs) self.__plaza_previa = self.plaza_asignada __plaza_previa is set on the __init__ method: def __init__(self, *args, **kwargs): super(Becario, self).__init__(*args, **kwargs) self.__plaza_previa = self.plaza_asignada My problem is that when I save a Becario object from the Django Admin with plaza_asignada as Null (as shown here) it gets to the save() method as the previous value, instead of None. However, if I save from the django shell with plaza_asignada = None, it gets to the save method as None (my expected behaviour). After doing some research I found that this may be caused by my ForeignKey being a OneToOneField (Django: Can't … -
How to run tests from external apps in django?
I have some django (reusable) apps that act like a template. When I start a new project I use them in order to get some standard functionalities for my webpages. I install them like external packages using pip (In my reusable app project directory using virtualEnv -> "pip install . --upgrade"). I have an issue with running tests. Some tests are always the same regardless of the webpage where the app is used, so it would make sense to write the tests inside the "reusable apps", but when I run "python manage.py test --keepdb" the external tests are not included. I tried also "python manage.py test myAppName --keepdb" but I only get a success message that says that 0 tests were run: py27 runtests: commands[1] | python manage.py test myAppName --keepdb Using existing test database for alias 'default'... ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Preserving test database for alias 'default'... When I expand my site-packages file I can see the test file. Is there a way to run these external tests from my webpage project together with all the other tests? -
Django rest return base 64 from view
I have implemented django-photologue and I am trying to return a base64 encoded image from my django view as following: @api_view(('GET',)) def get_gallery(request, id): gallery = Gallery.objects.get(id=id) data = [] for photo in gallery.sample(): data.append(photo.image_url) return Response(data) for Response(data) I get ["data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAFeCAIAAAD8M3pVAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ\nbWFn --string continues--"] notice '\n'in the string I am trying this (http://codebeautify.org/base64-to-image-converter) converter to see if I get the image back and it fails with the returned response. If I change it to HttpResponse(data) I get: data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAFeCAIAAAD8M3pVAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ bWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG --string continuous-- notice '\n' is now gone. This result renders image when I try it in this converter. What is the correct way of returning such base64 images from Django view? I am using angular2 frontend and I am confused what can be returned so that it can be handled on the frontend to render images. -
Python/ Django- how to automatically save a form whenever a value is changed?
I have a Django project, and on one of the pages, there is a form on one of the pages, on which the user can enter the value of a deposit, and the date that the deposit was received. When the page is first loaded, these fields are populated with values retrieved from the database. If the user then manually changes these values, and refreshes the page, the values revert back to what they were originally... I want the form to automatically save any time any changes are made to its values, so that if the user changes a value and refreshes the page, the new value should be displayed automatically. How would I do this? The HTML for this form is: <form method="POST" enctype="multipart/form-data" data-vat-status="{{project.vat_status}}" data-view-url="{% url 'projects:concept_save_ajax' project.id %}" class="autosave_form full-width"> {% csrf_token %} <div class="col-12 box"> <div> <table class="right fixed m-t-md"> <tr> {% for hidden in deposit_form.hidden_fields %} {{hidden}} {% endfor %} {% for field in deposit_form.visible_fields %} <td class="p-r-md">{{field.label}}</td><td class="p-r-md">{{field}}</td> {% endfor %} <td><a class="email_trigger button" data-view-url="{% url 'comms:open_email_template' project.id %}?template=7">Raise invoice</a></td> </tr> </table> </div> </div> <div class="col-6 box"> <div> <div class="expand-header"><strong class="m-t-md">Costing notes</strong></div> <table class="vertical-table left"> {% include "projects/includes/stacked_form.html" with form=budget_notes_form %} </table> </div> </div> … -
add html plugin to django
I am new to django and I have been using the plugins as child's to sections.text/accordion/ etc. In one page I want to have a google map snippet inside the column , but as a plugin not via the google_map app and inside the INSTALLED_APPS in settings.py ... So in general wonder if it is possible to have an html plugin that will be added also via the cms like the other plugins and in that html section to do things like, image gallery for example , google maps,animations, forms etc ... -
Django works fine on local host,but when using eb deploy and viewing it in the browser it comes up with a 500 error?
Im not sure what i am, doing wrong, when on my Django app, I run the app locally and it works fine with Amazon RDS. But when I deploy(eb deploy) then use (eb open) it doesn't work. It comes up with a 500 error. Any ideas on how i could fix this? Thanks! -
Django Rest Framework + django_filter: filter for name or none if nothing is provided
I'm using Django rest Framework together with django_filters. (I've tried to simplify/reduce the code here as much as possible) How can I force django_filters to filter for constraints__name=None (or constraints=None) if no constraint is specified in the request? Let's say I have this model: class Resource(models.Model): constraints = models.ManyToManyField(Feature, related_name='constraint+', blank=True) class Feature(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) And this view and filter: class ResourceFilter(FilterSet): constraints = django_filters.CharFilter(name='constraints__name') class Meta: model = Resource fields = ['constraints'] class ResourceViewSet(viewsets.ModelViewSet): serializer_class = ResourceSerializer filter_class = ResourceFilter filter_backends = (filters.DjangoFilterBackend,) /api/resource/?constraints=testconstraint works fine, but I want /api/resource/ to only return the Resources that have no constraints. I can reduce the queryset, but it feels like something django_filters could solve. Is it?: def get_queryset(self): if 'constraints' not in self.request.query_params: return Resource.objects.filter(constraints=None) else: return Resource.objects.all() -
Node.js or python socket whats suits in Django for real time notification
I have a Django application which is similar to facebook. It's purpose is social networking. Now to make it efficient should I opt for python or node.js or any other third part library. What is the best solution for scalable system -
Model Array in Django
I'm new to Django and I'm trying to model something like: "Field":[ { "opt1":val1, "opt2":val2}, { "opt1":val1, "opt2":val2}]. class Test(models.Model): Name = models.TextField(required=True) Specialty = models.???? What should I write? -
Jinja 2 does not iterate over my python dict (read from Redis)
API /api/v1/version returns all the version of applications in a specific pod . The return type is an OrderDict. I feed it to my jinja template to display the same on dashboard. As the number of servers increased, I needed to cache my object in Redis. Strangely, my jinja2 template doesn't display the dictionary I read from redis. The only difference I found was the impending 'u' in front of the keys, which was absent in the dictionary I got from redis. Example: Dictionary from Redis {'pod1': "{'server1': {'status': 'failed', 'comment': 'Server is offline.'}, 'server2': {'status': 'failed', 'comment': 'Exception ConnectTimeout while extracting response'}", 'pod2': "{'server-3':{'status':'success', 'build_number': '74', 'githash': '601a62162ad3cdd2e13f0728f1a9979281acefd4', 'timestamp': '2016-11-17 16:00:01', 'version': '1.0.74-RELEASE', 'tagname': 'release_2016_11_17'} }" } Dictionary generated by Django(before caching it) {u'pod1': "{'server1': {'status': 'failed', 'comment': 'Server is offline.'}, 'server2': {'status': 'failed', 'comment': 'Exception ConnectTimeout while extracting response'}", u'pod2': "{'server-3':{'status':'success', 'build_number': '74', 'githash': '601a62162ad3cdd2e13f0728f1a9979281acefd4', 'timestamp': '2016-11-17 16:00:01', 'version': '1.0.74-RELEASE', 'tagname': 'release_2016_11_17'} }" } The above dictonary is stored in the variable version_details. The line below renders it return render_to_response("version.html", {'pods': version_details, 'teams': APP_DETAILS.keys()}) The code snippet below is the jinja2 implementation <div class="uk-container uk-container-center uk-margin-top"> <ul class="uk-grid" data-uk-grid-margin> {% for pod, details in pods.iteritems %} {% for … -
What is a better option to use django-highcharts package to render charts in template or regular ugly rendering in django?
I am having some confusion to decide what to use for highcharts with django, do I use normal ugly rendering in to <script></script> tag or I use the django-highchart (package here)? -
Django: graceful way to deal with missing ID not 404()
At present, if no project is found, a 404 is raised. What I would like to do is return the user to the previous page and issue a message "Sorry no such project". Is there a quick and easy way to do this? def show(request, pk): try: project = Project.objects.filter( pk=pk, source_language=source_language, target_languages__in=[target_language] ).first() except Exception as e: raise Http404() if not project: #instead of this do what? print message no project, return to previous page raise Http404()