Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django gives 400 Bad request error in image upload using ajax
I am using quill editor to upload an image and the an ajax function is used to send the image to views.py. This is the python function for uploading the image. def upload_image(request): if request.method == 'POST': handle_uploaded_file(request.FILES.get('file')) return HttpResponse("Successful") return HttpResponse("Failed") def handle_uploaded_file(file): with open('upload/', 'wb+' ) as destination: for chunk in file.chunk(): destination.write(chunk) -
Docker compose can not create container for postgresql and redis
I have a problem with docker-compose and can not create containers for service postgresql and redis, after I run docker-compose up -d I've got this error: ERROR: for dockerizingdjango_postgres_1 Cannot create container for service postgres: b'invalid port specification: "None"' Creating dockerizingdjango_redis_1 ... Creating dockerizingdjango_redis_1 ... error ERROR: for dockerizingdjango_redis_1 Cannot create container for service redis: b'invalid port specification: "None"' ERROR: for postgres Cannot create container for service postgres: b'invalid port specification: "None"' ERROR: for redis Cannot create container for service redis: b'invalid port specification: "None"' ERROR: Encountered errors while bringing up the project. The docker-compose.yml file looks like this: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - /usr/src/app - /usr/src/app/static env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000 apache: restart: always build: ./apache/ ports: - "80:80" volumes: - /www/static - /www/media volumes_from: - web links: - web:web postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data I'm using this version of docker-compose: docker-compose version 1.13.0, build 1719ceb docker-py version: 2.3.0 CPython version: 3.4.3 OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014 also I'm using python3.5 for this … -
Django: Right way of using URL patterns: maximum recursion depth exceeded
Im new to Django and im trying to display Hello world from my app. Im stuck in giving the right URL pattern in urls.py My folder str is as: var\www\html\Python_PS\DjangoDemo\boardgames\boardgames\urls.py from django.conf.urls import url from django.contrib import admin from django.conf.urls import include #from boardgames.view import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^views/', include('boardgames.urls')) #url(r'^views/$',views) ] var\www\html\Python_PS\DjangoDemo\boardgames\main\views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello!") var\www\html\Python_PS\DjangoDemo\boardgames\boardgames\settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' #added main here ] After importing the include library in urls.py : I got maximum depth exceeded error. Or otherwise unable to display the Hello!. I need to know the proper way of using the the url patters. My Django version is 1.11 with Python 3.5.2 -
Could not migrate and how to set mysql DB using Django python
I need one help.Actually I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error. Unknown command: 'migrate' Type 'manage.py help' for usage. Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below. settings.py: """ Django settings for mysite project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'mysite.urls' WSGI_APPLICATION = 'mysite.wsgi.application' # Database … -
django-admin makemessages: error: unrecognized arguments: -1 pt_pt
I am trying to implement internationalization in Django. I am trying to have Portuguese as well as English for my site. But every time I try to use the command makemessages I get the error: django-admin makemessages: error: unrecognized arguments: -1 pt_pt As a result I'm not being able to create the .po file. How do I solve this? Thanks in advance. -
How to bring the save buttons on top of User Change admin page in Django?
When I create a user in Django admin the first page is the user creation form. As soon as I create a user it goes to the user change page where I want to show the save buttons on top. I have read the Django docs and know about ModelAdmin.save_on_top method. But how do I integrate this on the default User model? P.S. I've tried using Proxy model, but the user creation page doesn't show when I create a user in the admin. -
ImportError: cannot import name LoginService-After upgrading django1.3 to 1.11
I am upgrading my django application from 1.3 to 1.11.there is an import "from erp.auth.backend import LoginService". This import works in django1.3 but after upgrading django to 1.11 import does't works and raises 'ImportError: cannot import name LoginService'. -
Python Django mysqldb select with unicode value
When I use this clause, everything is right. find in here is モンキー・D・ルフィ sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');" % find.encode('utf-8') self.db.execute(sql_fmt) But when I use this clause, error happened. find in here is (モンキー・D・ルフィ) or ('モンキー・D・ルフィ') sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in %s;" self.db.execute(sql_fmt, find) Error: ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(\\'\xe3\x83\xa2\xe3\x83\xb3\xe3\x82\xad\xe3\x83\xbc\xe3\x83\xbbD\xe3\x83\xbb\xe3\x83\xab\xe3\x83\x95\xe3\x82\xa3\\')'' at line 1") -
Default value for models.GenericIpAddressField
i am trying to add another column in my model: ip_address = models.GenericIPAddressField() and when i run makemigrations, i have to set a default value. what should i put? thanks in advance. models.py class Prospect(models.Model): full_name = models.CharField(max_length=120) email = models.CharField(max_length=80) contact_number = models.CharField(max_length=14) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) user = models.ForeignKey(VendicsUser, null=True) ip_address = models.GenericIPAddressField() def __unicode__(self): return self.full_name def __str__(self): return self.email -
How To Set Sources For Jupyter Notebooks
I've just bought a new computer, and can't remember/don't know how I had Jupyter notebooks set up on my old machine. Specifically, how do you tell Jupyter about sources. If I have a conda environment called django, and I do source activate django followed by jupyter notebook, I end up with a notebook, but then when I do from django.http import HttpResponse I get the error message ModuleNotFoundError: No module named 'django' Which is bizarre (I think), because Django is definitely installed in the Django environment. How do I set up my Jupyter notebooks so that they know about the various sources that I want them to know about? -
How can I access media files in CSS? Django
I'd like to do something like this: div#city{ background-image: url("{{ MEDIA_URL }}{{city.city_image}}"); } If I add the above as inline CSS within HTML it does produce the below path and it renders okay but I can't access it from CSS. <div class="container" style="background-image:url('media/city_pictures/paris-france.jpg');"> <div class="city_header"> <h1> PARIS </h1> </div> </div> I can access Static images from CSS but not media images. -
URL not reversing in template Django
Right now I'm having issues getting the url tag to reverse back to my urls. I'm getting the NoReverseMatch. Specifically its Error django.urls.exceptions.NoReverseMatch: Reverse for 'documents' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I've tried narrowing it down using other url names to reverse, but they also don't work. I'm guessing its something to do with calling the url. Any help will be awesome. If anything else is needed just let me know. urls.py """urls for vivid""" from django.conf.urls import url from . import views app_name = 'website' urlpatterns = [ url(r'^$', views.login_view, name='login'), url(r'^dashboard/$', views.dashboard_view, name='dashboard'), url(r'^home/$', views.home_view, name='home'), url(r'^addshow/$', views.show_add_view, name='addshow'), url(r'^regis/$', views.regis_view, name='regis'), url(r'^show/(?P<show_id>[0-9]+)/$', views.detail_show_view, name='detailshow'), url(r'^show/(?P<show_id>[0-9]+)/documents$', views.documents_view, name='documents'), url(r'^addcardcomp/$', views.add_card_comp, name='addcomp'), url(r'^homecardcomp/$', views.home_card_comp, name='homecomp'), ] templates <a href="{% url 'documents' show_id=showDocumentID %}" -
What is the rpc result backend in Celery?
I was confused by the result backend and the broker. I use the celery in django, and set the the result backend by the tutorial on celery docs. app = Celery('tasks', backend='rpc://', broker='amqp://myuser:mypassword@localhost:5672/myvhost') but the backend seems useless where I have config the value of django_celery_results, so what's the relation between django_celery_results and the backend param of Celery app? -
django markdown() got an unexpected keyword argument 'extensions'
when i am use markdown in django, the error: page error when i am use markdown2, the error: markdown2 error views.py # -*- coding:utf-8 -*- import markdown2 from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def index(request): post_list = Post.objects.all().order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) def detail(request, pk): post = get_object_or_404(Post, pk=pk) post.body = markdown2.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markwdown.extensions.toc', ]) return render(request, 'blog/detail.html', context={'post': post}) models.py def get_absolute_url(self): return reverse('blog:detail', kwargs={'pk': self.pk}) -
Using DRF serializer to validate a list of dictionaries
How do I write a serializer that validates a list of dictionaries? Sample payload being sent is: "payment_discount": [ { "discount_rule_id": 1, "discount_rule_name": "10 day early payment", "discount_earned": "298.00" }, { "discount_rule_id": 2, "discount_rule_name": "Store discount", "discount_earned": "5.50" }, ] Taking from this SO answer and this: class PaymentDiscountSerializer(serializers.DictField): """Serialize discounts""" discount_rule_id = serializers.IntegerField(required=False) discount_rule_name = serializers.CharField(max_length=50) discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3) class PaymentDiscountListSerializer(serializers.ListField): """Serialize discount object""" child = PaymentDiscountSerializer() class PaymentSerializer(serializers.ModelSerializer): payment_discount = PaymentDiscountListSerializer() # Other model fields With this, I can get access to the payment_discount object in the payload using serializer.data but unfortunately no validations are being done against the dictionary if e.g. the payload includes discount_earned value of that is not of type Decimal using: Django==1.10.2 & djangorestframework==3.5.1 -
Django django.contrib.gis.db.models.functions.Distance to return values in feet instead of meters
def nearby(self, latitude, longitude, proximity=None): """Get nearby Merchants. Custom queryset method for getting merchants associated with nearby places. Returns: A queryset of ``Merchant`` objects. """ point = Point(latitude, longitude) # we query for location nearby for places first and then # annotate with distance to the same place return self.filter( places__location__distance_lte=(point, D(ft=proximity))).\ annotate(distance=models.Min(Distance( 'places__location', point))) the following code will filter properly, but the value returned by models.Min(Distance('places__location', point)) Is in meters, is it possible to get it in feet? -
Django ORM distinct query where order is done by annotated field and you need distinct('id')
Merchant has places. Places have a location coordinates. I need to return list of UNIQUE merchants through API call (DRF) filtered by distances of proximity to any place they have associated and return back distance value from a closest place. Right now I get duplicates (i.e. merchant gets returned multiple times if there are several places of the merchant in proximity). If I try to have annotate(distance=...).distinct('pk') I get error message django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON (&quot;merchants_merchan If I add .order_by('pk') I can then use .distinct('pk'), but then I can't sort returning queryset by distance. Any ideas? Queryset class MerchantQuerySet(models.QuerySet): def nearby(self, latitude, longitude, proximity=None): """Get nearby Merchants. Custom queryset method for getting merchants associated with nearby places. Returns: A queryset of ``Merchant`` objects. """ point = Point(latitude, longitude) # we query for location nearby for places first and then # annotate with distance to the same place return self.filter( places__location__distance_lte=(point, D(ft=proximity))).\ annotate(distance=Distance( 'places__location', point)).distinct() Models class Merchant(TimeStampedModel): name = models.CharField(max_length=255, verbose_name=_('Name')) description = models.TextField( blank=True, verbose_name=_('Description'), ) logo = imagekitmodels.ProcessedImageField( max_length=512, upload_to=get_upload_path_for_model, processors=[ResizeToFill(300, 300)], format='PNG', options={'quality': 100}, editable=True, null=True, blank=True, verbose_name=_('Company logo'), help_text=_('Image will be … -
Website Idea - Structure and Management [Django + Angular2]
I'm currently trying to build a website for a game I'm playing. This website is basically just sharing the game information. I'm currently using Django + Django REST framework as back-end and Angular2 as front-end. Client side will use API to retrieve data from server. The displaying(GET calls) part is almost finished. However, according to my personal experience and online research, the Django default Admin is not quite user-friendly (for example, it's difficult for my guild mates to edit/update a character if they don't know the data structure in server). Thus, after doing some researches, I came up two possible solutions: Customize Django Admin (templates, views, ...etc) Use Angular 2 to create Admin page My goal is to allow others to create/edit multiple Django models in one page. Please let me know which way is better and why? Many thanks! -
django admin site - divide in sections object attributes
I've been playing around with the django admin site and so far I've been able to add some attributes into the view where all objects of a model are shown, however (as i have a lot of attributes in the model) i would like to know if there is a way to divide by sections the attributes of the object when creating or modifying the object so readability can be better. I've been trying to find a way but I haven't found it. As english is not my native language maybe I'm not searching for the right key words. If anyone could point me in the right direction I would by grateful. Thanks in advance. -
Start the Page Menu not from root_page, rather from second level
I have a page tree wich begins with 3 pages: /private /business /education in each of those pages there are several other pages inside. Like as the wagtail demosite i built a templatetag to implement the top navigaton in my base template. the special thing is, that my menu is splitted in two sections: the first level (private, business, education) is shown up on the top of my website (section menu) and the child elements of those pages lies in my bootstrap navbar (top menu). how can i tell the top_menu model to ignore the first level, because its allready shown in my section menu? menu_tags.py from django import template register = template.Library() @register.assignment_tag(takes_context=True) def get_site_root(context): return context['request'].site.root_page def has_menu_children(page): return page.get_children().live().in_menu().exists() @register.inclusion_tag('tags/section_menu.html', takes_context=True) def section_menu(context, parent, calling_page=None): menuitems_section = parent.get_children().filter( live=True, show_in_menus=True ) return { 'calling_page': calling_page, 'menuitems': menuitems_section, # required by the pageurl tag that we want to use within this template 'request': context['request'], } @register.inclusion_tag('tags/top_menu.html', takes_context=True) def top_menu(context, parent, calling_page=None): menuitems = parent.get_children().filter( live=True, show_in_menus=True ) for menuitem in menuitems: menuitem.show_dropdown = has_menu_children(menuitem) return { 'calling_page': calling_page, 'menuitems': menuitems, # required by the pageurl tag that we want to use within this template 'request': context['request'], } # … -
Django logging custom attributes in formatter
How can Djang use logging to log using custom attributes in the formatter? I'm thinking of logging the loged username for example. A workaround to this is to build the message attribute include the things that are not part of the default attributes that logging formatters have. But, how can I use my own 'custom' attributes on formatters in Django to say, for example, the loged username, and perhaps other Django session information? -
How to convert a matplotlib.pyplot to a bokeh plot
I have been reading today about how to render a matplotlib.pyplot in a Django template. I found bokeh library and I was trying to convert my matplotib in a valid input to bokeh components. I read .to_boke method is deprecated. datos = np.random.randn(1000) ## Discretizamos el conjunto de valores en n intervalos, ## en este caso 8 intervalos datosbin = np.histogram(datos, bins=np.linspace(np.min(datos), np.max(datos), 9))[0] ## Los datos los queremos en tanto por ciento datosbin = datosbin * 100. / len(datos) ## Los datos los queremos en n direcciones/secciones/sectores, ## en este caso usamos 8 sectores de una circunferencia sect = np.array([90, 45, 0, 315, 270, 225, 180, 135]) * 2. * math.pi / 360. nombresect = ['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE'] ## Dibujamos la rosa de frecuencias plt.axes([0.1, 0.1, 0.8, 0.8], polar=True) plt.bar(sect, datosbin, align='center', width=45 * 2 * math.pi / 360., facecolor='b', edgecolor='k', linewidth=2, alpha=0.5) plt.thetagrids(np.arange(0, 360, 45), nombresect, frac=1.1, fontsize=10) plt.title(u'Procedencia de las nubes en marzo') script, div = components(plt, CDN) return render(request, 'consulta/resultado/imprimir.html', {'variables': variables, 'respuesta3': peticion3.content, 'lugar': lugar, 'hora_actual': hora_actual, 'hora_siguiente': hora_siguiente, 'dias': horas, 'Variables': variables_posibles, 'latitud':latitud, 'longitud': longitud, "the_script": script, "the_div": div}) I have a valueError (obviously matplotlib.pyplot is not a valid … -
How to filter objects by price range in Django?
I have a model Item with field price. class Item(models.Model): title = models.CharField(max_length=200, blank='true') price = models.IntegerField(default=0) My query may contain min_price & max_price values. So, my request may be like this: http://example.com/api/items?min_price=50&max_price=500. Can anybody tell me, how can I query items between min & max values? Can I solve it using Django ORM? Thanks! -
django - custom script in admin form and pre-populating many to many field
I have a model that contains two date fields and and many to many field. Dates are passed to template by admin/foo/bar/add?date=2017-11-11 or can be changed on page. What I need is to prepopulate many to many field with objects whichs quantity is equal to number of days between dates. And if date is changed I need to automatically add or remove items in many to many field is it possible ? -
Django autocomplete light queryset filter
models class Reservation(models.Model): company = models.ForeignKey(GuestContact, on_delete=models.PROTECT) class GuestContact(models.Model): company = models.CharField(max_lenght=30) last_name = models.CharField(max_lenght=30) first_name = models.CharField(max_lenght=30) contact_genere_id = models.ForeignKey(ContactGenere, on_delete=models.PROTECT) # 1 = company 2 = guest form class ReservationForm(ModelForm): class Meta: model = Reservation fields = '__all__' widgets = { 'company': autocomplete.ModelSelect2() } views class GuestContactAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = GuestContact.objects.filter(contact_genere_id=1) return qs this QuerySet filter works in python shell, in my views this not work i see all contacts not only company contacts. Can you help me ?