Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Verify error on acme.sh"
I created a new website with Webfaction and I also configured the Django Application. Nothing here is wrong. The problem is when I generate the SSL Certificates: I installed acme.sh and I run this command: acme.sh --issue --test -d mysite.com -w ~/webapps/<my_ssl_app>/ But the command generated this error: Verify error: could not connect to mysite.com How do I resolve this problem ? Thanks for help me !! P.S.: I tried to generate the certificates with this GUIDE -
How to save django model form, crispy, I cannot save the data to database
Welcome friends I need your help. I cannot save the data to my database from a form. It may of course be very simple, but I don't know, how to do this. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^busy/', views.product_busy, name='product_busy'), ] models.py from django.db import models from django.core.urlresolvers import reverse class Busy(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) verbose_name = 'busy' verbose_name_plural = 'busy' def __str__(self): return self.nazwa def get_absolute_url(self): return reverse('konfigurator:product_busy', args=[self.id, self.slug]) forms.py from django import forms from django.utils.translation import ugettext_lazy as _, ugettext from crispy_forms import layout, bootstrap from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, MultiField, Div, Field, Button from .models import Busy class Konfig(forms.ModelForm): class Meta: model = Busy fields = ['name','slug'] def __init__(self, *args, **kwargs): super(Konfig, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = "." self.helper.form_method = "POST" self.helper.form_class = 'order-form' self.helper.layout = layout.Layout( layout.Fieldset( _("Dane personalne"), layout.Field("name"), layout.Field("slug"), ), bootstrap.FormActions( layout.Submit("submit", _("Send"), css_class="right"), ) ) views.py from django.shortcuts import render, get_object_or_404 from .models import Busy from django.shortcuts import render from .forms import Konfig from django.conf import settings from django.http import … -
Multiple DJANGO applications under single url
I'm launching a couple of DJANGO instances under the same url. They all serve files over HTTPS. In order to save money for ssl certificates, I'm launching them under mydomain.com/django1/ , mydomain.com/django2/ etc. The redirection to the correct DJANGO instance is done in NGINX. My problem is, how should I change the DJANGO urls to match this architecture? Or can it be done in settings.py? Documentation: urls and FORCE_SCRIPT_NAME do not seem to give a clue, though I don't really understand the latter... Thanks in advance! DA -
getting status of celery tasks in another server
I have two servers running celery. 1 - Web Server 2 - Workers Server The web server is responsible for sending the tasks to the workers server. The workers performs these tasks. I would like to monitor the status of these tasks on the web server. Any ideas? views.py @user_passes_test(lambda u: u.is_superuser) def taskCompute(request, uuid): """ Now we have the uuid that identifies the image over we want to apply the process as an input. To trigger this view, the url has an uuid, and we receive it to receive the image we are working with """ doc = AnnotationDocument.objects.get(uuid=uuid) image_name = doc.name_id doc.status = 'Q' doc.save() image_processing.delay(uuid, image_name) return HttpResponseRedirect(reverse('list_admin')) tasks.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import subprocess as sub from PIL import Image app = Celery('tasks', broker='amqp://xxxxx', backend='rpc://', ) NFS_PATH = '/home/administrator/nfs' @app.task def image_processing(uuid, image_name): """ WORKERS job: - Get the images from the NFS pre-processing path - Move them to the worker path - Process the images - Create the PDF - Leave the Results in the NFS post-processing path """ current_working_path = os.path.join(NFS_PATH, uuid) local_filename_image = os.path.join(current_working_path, image_name) local_filename_annotations = os.path.join(current_working_path, "annotations.json") if os.path.isfile(local_filename_annotations): local_filename_annotations = local_filename_annotations else: local_filename_annotations … -
django.security.DisallowedHost odd values throwing exception
I have a droplet running on Digital Ocean. I am using gunicorn and nginx with Django 1.10. The web application has been running fine, but I have captured some DisallowedHost exceptions in my logs. My ALLOWED_HOSTS is: '11.11.11.11,.mydomainname.com' The values are the droplet IP address and my public domain name respectively. In the last few days I have seen the following in my log: Invalid HTTP_HOST header: '1389508397'. You may need to add '1389508397' to ALLOWED_HOSTS. Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. Invalid HTTP_HOST header: 'xxnet-403.appspot.com'. You may need to add 'xxnet-403.appspot.com' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '323.good-04y.appspot.com'. You may need to add '323.good-04y.appspot.com' to ALLOWED_HOSTS. -
How to do Django query to list all the first instances of a date?
I have the following model: class Attendance(TimeStamped): employee_id = models.CharField(max_length=10) punch = models.DateTimeField() The employee punches twice everyday, once to get in and once to log out. I want to come up with a QuerySet so that I get only the PUNCH INs of the employee. I tried to use distinct() but can't get it to work. So if an employee goes to office for two days I will have four rows in the model. But I want to only get two rows; only the first result of each date. How can I do this? -
Django form GET dynamically change queryset
I'm new to coding and django and I'm struggling to find the solution to the following problem having reviewed the answers I've found. Im creating a search form with multiple fields. When the user selects the first field category (and before hitting search) I would like to dynamically change the queryset for the second field sub_category such that only related values are shown. I have models.py as follows: class Product(models.Model): category = models.ForeignKey("Category") sub_category = models.ForeignKey("SubCategory") class Category(models.Model): name = models.CharField(max_length=256) class SubCategory(models.Model): category = models.ForeignKey("Category") name = models.CharField(max_length=256) And my forms.py includes: class BasicSearchForm(forms.Form): category = forms.ModelChoiceField( label='Category', queryset=Category.objects.all(), to_field_name="name", empty_label=None, initial="Red") sub_category = forms.ModelMultipleChoiceField( required=False, label='Type', queryset= SubCategory.objects.all(), to_field_name="name", widget=forms.Select) And my views.py includes: def search(request): if request.method == 'POST': form = BasicSearchForm(request.POST) if form.is_valid(): category = form.cleaned_data['category'] sub_category = form.cleaned_data['sub_category'] return render(request, 'myapp/search.html', {'form': form}) else: form = BasicSearchForm() return render(request, 'myapp/search.html', {'form': form}) And finally the search.html includes: <form class="search-form" role="search" action="/search/" method="get"> {{ form }} <input type="submit" value="Search" /> </form> I've played around with a few answers but nothing seems to work. I'd really appreciate some help. Thanks in advance! -
Django csv taking very long time Outputting CSV
I have a model which has a text entry of about 90,000 and I am outputting Django CSV but it is not converting outputting CVS i left browser for half an hour aand no output.But the method i used it worked fine when data is low. My method:- def usertype_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="university_list.csv"' writer = csv.writer(response) news_obj = Users.objects.using('cms').all() writer.writerow(['NAME', 'USERNAME', 'E-MAIL ID','USER TYPE','USER TYPE']) for item in news_obj: writer.writerow([item.name.encode('UTF-8'),item.username.encode('UTF-8'),item.email.encode('UTF-8'), item.userTypeId.userType.encode('UTF-8'),item.universityId.name.encode('UTF-8')]) return response I have testing this for smaller data it worked but for very larger files it is not working. Thanks in advance -
Django. Pass an array to a child template via include tag
I'm trying to create an array on the fly and pass it to a child template: {% include "template.html" with foo = ['one', 'two'] %} but this doesn't work. Does anybody know how to generate an array in parent template and then pass it to another template? -
Django registration issues
I am trying to download registration application from github but i have some problems: - git clone https://github.com/macropin/django-registration.git - python install setup.py - i copied the registration folder to my project folder Than : Url.py from django.conf.urls import * from django.contrib import admin from registration.views import* urlpatterns = ['', url (r'^accounts/', include('registration.backends.default.urls')), ] Setting.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # additional external apps 'registration', 'social.apps.django_app.default', ) SITE_ID=1 ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True When I type python manage.py sqlall **the result is this error : manage.py sqlall: error: Enter at least one application label. Please any help ? -
Django Updating wrong fields when loading from Excel
I am trying to update a django model using data from an excel sheet. I am using the Modelclassname.objects.create() method My View.py def create_user(request): if request.method == 'POST': book = xlrd.open_workbook("C://Users//10613527//Desktop//asd//Invoice List-Jan2017 (1).xls") sheet = book.sheet_by_index(0) r = sheet.nrows a = (sheet.row(1)) ka = (a[3].value) Post.objects.create( active=a[0].value, bu_field=a[1].value, is_org=a[2].value, functional_area=a[3].value, is_stakeholder=a[4].value, area=a[5].value, scope=a[6].value, contracted=a[7].value, #probability=a[8].value, invoice_name=a[9].value, sow_name=a[10].value, project_id=a[11].value, po_number=a[12].value, sow_type=a[13].value, #sow_start_date=a[14].value, #sow_end_date=a[15].value, sow_value=a[16].value, project_manager=a[17].value, apr=a[18].value, may=a[19].value, jun=a[20].value, jul=a[21].value, aug=a[22].value, sep=a[23].value, oct=a[24].value, nov=a[25].value, dec=a[26].value, jan=a[27].value, feb=a[28].value, mar=a[29].value, apr_future=a[30].value, may_future=a[31].value, jun_future=a[32].value, ) return HttpResponse('') My Model.py class Post(models.Model): title = models.CharField(max_length=120) content = models.CharField(max_length=120) file_system=models.FileField(null=True,blank=True) active = models.NullBooleanField() bu_field = models.CharField(max_length=10, null=True) is_org = models.CharField(max_length=120, null=True) functional_area = models.TextField(max_length=120, null=True) is_stakeholder = models.CharField(max_length=120, null=True) area = models.CharField(max_length=120, null=True) scope = models.CharField(max_length=50, null=True) contracted = models.CharField(max_length=50, null=True) probability = models.IntegerField(null=True) invoice_name = models.CharField(max_length=500, null=True) sow_name = models.CharField(max_length=500, null=True) project_id = models.CharField(max_length=500, null=True) po_number = models.CharField(max_length=500, null=True) sow_type = models.CharField(max_length=50, null=True) sow_start_date = models.DateField(null=True) sow_end_date = models.DateField(null=True) sow_value = models.CharField(max_length=50, null=True) project_manager = models.CharField(max_length=500, null=True) Now the problem is that most of the fields update properly but a couple of fields at the last like is_org , Functional_area are updating one field to the left from what is in the source excel. For example … -
Managing server files in django
I see various bits of information in the docs, but I can't seem to form the complete picture. I wish to hold various text, audio and video files on the server. At the moment I'm not planning to add user upload support but it would be nice to expand to that in the future. I just don't understand where to start and what to do. Where do I save those files on the server? What is the best way for django to interact with those files? I hope that you can help me with the confusion :) -
A Schema is required to be provided to GraphQLView
I was following this tutorial to integrate Graphql with Django, I did everything according to that tutorial when I'm hitting graphql URL on my local machine http://localhost:8000/graphql I'm geting the following error AssertionError at /graphql A Schema is required to be provided to GraphQLView. Request Method: GET Request URL: http://localhost:8000/graphql Django Version: 1.11.1 Exception Type: AssertionError Exception Value: A Schema is required to be provided to GraphQLView. Exception Location: /home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages/graphene_django/views.py in init, line 84 Python Executable: /home/psingh/Projects/django_graphql/env/bin/python Python Version: 2.7.6 Python Path: ['/home/psingh/Projects/django_graphql/project', '/home/psingh/Projects/django_graphql/env/lib/python2.7', '/home/psingh/Projects/django_graphql/env/lib/python2.7/plat-x86_64-linux-gnu', '/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-tk', '/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-old', '/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages', '/home/psingh/Projects/django_graphql/env/lib/python2.7/site-packages'] Server time: Fri, 12 May 2017 12:18:31 +0000 Any help would be great.I am new to the coding stuff. Thanks in advance. -
How to document parameters in Django REST Swagger 2?
I used to specify the parameters using YAML Docstring, but they have now been deprecated. I have tried using coreapi.Field, but it only works withlists, and not with, say, create. According to this report, this has been an on-going issue. The solution provided in the comments are quite hackish to me. I hope someone has already found (or came up with) a neater solution or alternative, perhaps a plugin or something. -
Union query from Django ORM
Need to fetch aggregated data from 2 difrent tables. Elements element_type tempcolumn xyz test1 pqr test2 xyz test3 Users: User_names auser buser cuser need output in following format element_type count xyz 2 pqr 1 users 3 SQL Query Example: SELECT element_type, count(*) FROM Elements group by element_type union select 'users',count(*) from Users can we excute same with django orm? -
Query related class for searching name with spaces
I want a query related class for searching name with spaces in the given queryset. orginal_results_search = FlatCrawlAnalysisResult.objects.using(org_db.db_name).filter(analysis_id=crawlanalysis.id,domain_id=userdomain.domain.id).order_by('id').filter(Q(url__icontains=name)) In above i searched name in the given query set and filtered them using filter(Q(url__icontains=name)) If name='site_map' it will return all query which matches with that name. Now what I want is to, if I given name='site_map' i.e. (underscored b/w word), i want the query set matches with that name and also 'site map' and 'sitemap'. Here the name field is dynamic one and not static. Is there any function like i_contains to search the name with space also. -
Django creating dynamic model on Run-time, need to restart the server to reflect it, why?
I'm creating dynamic models by referring this link https://code.djangoproject.com/wiki/DynamicModels, from this I'm able to create Table to the Database on runtime. And can see the created table by below command python manage.py inspectdb test1 it returns in django models.py format, By next step i'm trying to take this created Table to the app's models.py file by below command python manage.py inspectdb test1 > app/models.py Then the mdoels.py I get some thing like this class Test1(models.Model): first_name = models.CharField(max_lengtgh=255) last_name = models.CharField(max_lengtgh=255) Then I'm rendering this models into forms.py from models import Test1 class Test1Form(forms.ModelForm): class Meta: model = Test1 and then calling this form to views.py and rendering it to template as input form. Here every thing is working fine on runtime, but each and every time I need to restart the django server to see the form in the template, why? Why it needs a restart, can you guys please help me for this, is my way is correct or need to change my approach? Please let me know it will be very great full for me. Thanks in advance. -
Cannot access my Django project from LAN
Localy i can access python projection using 127.0.0.1:8000.So,i want to access it via LAN.I've done some search how to figure it out and i've followed these steps: in the settings.py file i did ALLOWED_HOSTS=[192.168.1.11:8000] ,that's my computers LAN ip adress.And then in Django terminal i've done python manage.py runserver 192.168.1.11:8000,it didn't work and i've tried to replace the ip adress with 0.0.0.0:8000 but the same issue.As DEBUG=True i've have the following error message: `Invalid HTTP_HOST header:''.You may need to add '' to ALLOWED_HOSTS,and i've already done it. -
Empty request.GET with DjagoRestFramework and Scorched
I have a project in Django and Django-Rest-Framework. The search is provided by Solr via the Scorched client. It all works fine on the deployed website (Django 1.8 on Python 3.4). I recently updated my development website (Django 1.11 on Python 3.6) and I had to change a couple of things, e.g. substituted the deprecated django.core.context_processors.request with django.template.context_processors on the settings context_processors and the self.resolve_context function with self.get_template_context om my custom_html_renderer.py (see below). Now, it all works fine except the search. Whn I search (i.e. append ?q=something to the address) the template outputs just nothing. I've noticed that I cannot get anything from my request: {{request.GET.q}}, {{request.query_params}} all are just empty on my template. I have tried everything I can think of. As I said, the earlier version of the website works just fine. My old (working) custom_html_render.py: from rest_framework.renderers import TemplateHTMLRenderer class CustomHTMLRenderer(TemplateHTMLRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): renderer_context = renderer_context or {} view = renderer_context['view'] request = renderer_context['request'] response = renderer_context['response'] if response.exception: template = self.get_exception_template(response) else: template_names = self.get_template_names(response, view) template = self.resolve_template(template_names) context = self.resolve_context({'content': data}, request, response) return template.render(context) ``` My new custom_html_render.py: from rest_framework.renderers import TemplateHTMLRenderer from django.utils.encoding import smart_text from rest_framework import renderers … -
rest api django taking two numbers as input and returning the product of two numbers
I am new to Django and searching for how to convert function in REST API where function is taking the two value from user or caller of the api pass two argument say a and b and returning their product(a*b). In which file to write the code and return the value. -
Locale Name vs Language Code
According to Django Documentation: locale name A locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. Examples: it, de_AT, es, pt_BR. The language part is always in lower case and the country part in upper case. The separator is an underscore. language code Represents the name of a language. Browsers send the names of the languages they accept in the Accept-Language HTTP header using this format. Examples: it, de-at, es, pt-br. Language codes are generally represented in lower-case, but the HTTP Accept-Language header is case-insensitive. The separator is a dash. Questions: When I see it in someone's code, how can I tell whether it's a locale name or a language code? When to use locale code, and when to use language code? -
Django translation cannot discover language preference
I have a project named fellow_go, which contains an app named pickup. Relevant code fellow_go/fellow_go/settings.py # ...... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # <--- note this one 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # ...... LANGUAGE_CODE = 'zh_hans' LANGUAGES = [ ('zh_hans', _('Chinese')), ('en', _('English')), ] fellow_go/fellow_go/urls.py from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin urlpatterns = i18n_patterns( url(r'^pickup/', include('pickup.urls')), url(r'^admin/', admin.site.urls), prefix_default_language=False ) fellow_go/pickup/urls.py from django.conf.urls import url from . import views app_name = 'pickup' urlpatterns = [ url(r'^$', views.index, name='index'), ] /fellow_go/pickup/views.py from django.http import HttpResponse from django.utils.translation import ugettext as _ def index(request): return HttpResponse(_('hello, world')) Apart from these, I've executed makemessages -l zh-cn, edited the resulting *.op file, and run django-admin compilemessages. Error output When I tried to access http://127.0.0.1:8000/pickup (I'm debugging on the localhost), Django have me a 404 error with the following message: Using the URLconf defined in fellow_go.urls, Django tried these URL patterns, in this order: ^zh-hans/ The current path, pickup, didn't match any of these. Also, even if I visit http://127.0.0.1:8000/zh-hans/pickup/, I get hello, world, instead of the expected 你好世界 (Chinese translation of hello, world). Question This confuses me: I've set prefix_default_language to False, and the … -
Django - Externalize configurations to a JSON/YAML file
We have a CI pipeline, which requires my Django project to externalize its configurations to a JSON or YAML file, instead of the usual settings.py. One way to do this would be to parse the JSON/YAML file, and assign configurable values individually in settings.py, but that seems cumbersome, and introduces redundancy. Please suggest a better way. -
Django rest framework : POST on many to many
I have the following models : class A(models.Model): b = models.ManyToManyField(B) name = model.CharField() class B(models.Model): name = model.CharField() Urls in A app: url( r'^A/(?P<pk>[a-f0-9-]+)/B/$', AViewSet.as_view({ 'get': 'list', 'post': 'create', 'put': 'partial_update', }), name='A-B', ), Serializer in A app : class ABSerializer(serializers.ModelSerializer): class Meta: model = A extra_kwargs = { 'id': {'read_only': True}, } fields = ( 'b', ) The issue is that when I call the POST call on the A app using the url : A/{idofA}/B and send the post data of : { b : ["idofexistingB"] } I get the error that the required field of A is not sent. This setup works for PUT call however. The issue with PUT call is that when I call the PUT call again, it overrides the existing data in the AB relation field with the new data and not simply appends the data of second API call to the first. How can I POST data so that I am able to link existing B records with A records? -
Errror in outputting CSV with Django?
I am trying to output my model as a CSV file.It is working fine with small data in model and it is very slow with large data.And secondly there are some error in outputting a model as CSV.My logic which I am using is: def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="news.csv"' writer = csv.writer(response) news_obj = News.objects.using('cms').all() for item in news_obj: #writer.writerow([item.newsText]) writer.writerow([item.userId.name]) return response and the error which I am facing is: UnicodeEncodeError :-- 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128) and further it says:- The string that could not be encoded/decoded was: عبدالله الحذ