Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vagrant to Docker communication via Docker IP address
Here's my situation. We are slowly migrating our VMs from Vagrant to Docker but we are mostly still Docker newbs. Some of our newer system's dev envs have already been moved to Docker. We have test code that runs on an older Vagrant VM and used to communicate with another Vagrant running a Django Restful API application in order to run integration tests. This Django API is now in a Docker container. We are using Docker compose to initialize the docker container the main compose yaml file is shown below. services: django-api: ports: - "8080:8080" build: context: .. dockerfile: docker/Dockerfile.bapi extends: file: docker-compose-base.yml service: django-api depends_on: - db volumes: - ../:/workspace command: ["tail", "-f", "/dev/null"] env_file: - ${HOME}/.pam_environment environment: - DATABASE_URL=postgres://postgres:password@db - PGHOST=db - PGPORT=5432 - PGUSER=postgres - PGPASSWORD=password - CLOUDAMQP_URL=amqp://rabbitmq db: ports: - "5432" extends: file: docker-compose-base.yml service: db volumes: - ./docker-entrypoint-initdb.d/init-postgress-db.sh:/docker-entrypoint-initdb.d/init-postgress-db.sh environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: django-api-dev I would like the tests that are running on the vagrant to still be able to communicate with the django application that's now running on docker, similar to the way it could communicate with the api when it was running in a vagrant. I have tried several different types of … -
pip3.6 install django fails with [Errno 30] Read-only file system
I have installed the latest version of Python on my CentOS 6.9 using the root user and this has been successful. I have basically run the following commands; wget http://python.org/ftp/python/3.6.2/Python-3.6.2.tar.xz tar xf Python-3.6.2.tar.xz cd Python-3.6.2 ./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib" make && make altinstall strip /usr/local/lib/libpython3.6m.so.1.0 wget https://bootstrap.pypa.io/get-pip.py python3.6 get-pip.py This has worked. I have exited the root login via ssh and have logged in with another Cpanel user to try and install and run a django app. I have created and activated a virtualenv by running this; mkdir myproject cd myproject virtualenv mydjangoproject source mydjangoproject/bin/activate Now I am trying to install Django in my virtualenv using Python3.6 When I run this; pip3.6 install django I get the following error; Exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python3.6/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python3.6/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python3.6/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python3.6/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python3.6/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python3.6/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/local/lib/python3.6/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/local/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) OSError: [Errno 30] … -
Custom view does not show results in Django Haystack with Elastic Search
I'm starting using Django Haystack with Elasticsearch. All right until I started make a Custom View following the simple example in readthedocs. search_indexes.py: class ExperimentIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) owner = indexes.CharField(model_attr='owner') def get_model(self): return Experiment def index_queryset(self, using=None): return self.get_model().lastversion_objects.all() urls.py: url(r'^search/?$', NepSearchView.as_view(), name='search_view') urls.py before (without Custom View): url(r'^search/', include('haystack.urls')) views.py class NepSearchView(SearchView): def get_queryset(self): queryset = super(NepSearchView, self).get_queryset() if not self.request.user.is_authenticated and \ self.request.user.groups.filter(name='trustees').exists(): return queryset # (with some filter) else: return queryset search.html: {# ... #} {% for result in page.object_list %} {% if result.model_name == 'experiment' %} {% include 'search/experiments.html' %} {% endif %} {% if result.model_name == 'study' %} {% include 'search/studies.html' %} {% endif %} {% if result.model_name == 'group' %} {% include 'search/groups.html' %} {% endif %} {% if result.model_name == 'experimentalprotocol' %} {% include 'search/experimental_protocol.html' %} {% endif %} {# ... #} Well, the fact is when using default Haystack SearchView I've got the correct matches, while when introducing NepSearchView, page.object_list is empty and I get No results found. in template. I already ran manage.py rebuild_index, searched extensively in web but couldn't find nothing that explains what I'm missing. -
Form not valid in django
Hi I am learning Django for a project and I am trying to upload a file along with a on option in dropdown list through a form using POST. Here are my files: views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from .forms import UploadFileForm # Imaginary function to handle an uploaded file. from save_uploaded_file import handle_uploaded_file def index(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return render(request, 'viewer_app/display_image.html') else: print('error') return render(request, 'viewer_app/index.html', {'form': form}) else: return render(request, 'viewer_app/index.html') forms.py from django import forms class UploadFileForm(forms.Form): file = forms.FileField() displayType = forms.ChoiceField(widget=forms.Select(), required=True) save_uploaded_file.py def handle_uploaded_file(f): with open('static/viewer_app/temp.exr', 'wb+') as recieved_exr: for chunk in f.chunks(): recieved_exr.write(chunk) index.html <div id="formDiv" style="display:none;" class="form" > <form method="post" enctype="multipart/form-data" class="form-style"> <label for="browse">Upload file</label> <input type="file" value="Browse" id="brow" /><br></br> <label for="display">Display type</label> <select id="display-type" name="display"> <option id="RGB1" value="RGB1">RGB1</option> <option id="RGB2" value="RGB2">RGB2</option> <option id="RGB3" value="RGB3">RGB3</option> <option id="RGB4" value="RGB4">RGB4</option> </select><br></br> <input type="submit" value="Show file" id="showimage"/><br></br> {% csrf_token %} </form> </div> So, after I run the server to display the page and I select the upload and click submit, it doesn't upload and save the file and in the terminal I see the "error" text in the terminal … -
Localhost and 127.0.0.1 can't be reached with django/apache
I created a django project completely fine, and now I am looking to deploy it so I am attempting to create a test django test prog (to make sure all is good with apache/mod_wsgi before I add my code). When I place my IP in the url, I get the apache2 default page. However, I cannot get my test django proj to work through my browser. I either get a localhost refused to connect, or 127.0.0.1 refused to connect (depending on what one I tried). Any thoughts? Here is what I tried: Add 'localhost' to ALLOWED_HOSTS Add '*my IP Address' to ALLOWED_HOSTS Made sure my proj location is in /var/web/ I am running windows and using an SSH client (putty) to access a Ubuntu box. -
Django Queryset - How do I do math on related models with prefetch_related?
I have three models: class Variety(models.Model) name = models.CharField(max_length=24) class Item(models.Model) name = models.CharField(max_length=24) in_stock = models.IntegerField() class ItemPart(models.Model) variety = models.ForeignKey(Variety) product = models.ForeignKey(Product) qty = models.IntegerField() I would like to tell how much of each Variety has been made into Items by getting all the related ItemParts and multiplying their qty by the in_stock of their related Items. I've gotten this far: Variety.objects.all().prefetch_related('itempart_set').values('name').annotate( Sum(F("itempart_set__qty") * F("itempart_set__item_set__in_stock") ) Will this work? Will it sum the products, or will it simply multiply the sums? -
Django sendmail SSL error EOF occurred in violation of protocol
I have this nasty error that i can't wrap my head around. Have been trying to solve it for quite a while now. Any help would be highly appriciated. I'll paste the stacktrace, I also made some debugging with Wireshark and i'll post that as well. I have tried to upgrade python packages that could be related to the ssl communication without any success. This problem only happens when EMAIL_USE_TLS is True and it will happen for both debug mode and production. I first thought that maybe the SMTP server is using on old version of ssl but that was not the case. As the Wireshark capture will tell the ssl seems to be established, then in the next request the server will close unexpectedly. The settings i use is: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp_server' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_username' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_USE_TLS = True I do nothing strange when sending the mail, here is the code: def email_user(self, subject, message, from_email=None, **kwargs): return send_mail(subject, message, from_email, [self.email], **kwargs) The error stacktrace is: Traceback (most recent call last): File "C:\Users\Metadeath\Envs\dropin\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Metadeath\Envs\dropin\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) … -
Configure a remote project
I am starting a Django project. I'd like to connect this project in such a way my partner could work remotly and we can see the trackings and modifications on that project. What do you suggest to set up those configurations? -
Django extends not working
I have a problem with execute html view. I have base.html which do not showing the child views from another files. Can anybody help me what I doing wrong? Here are my files: models.py from django.db import models from django.utils import timezone class Kategorie(models.Model): glowna = models.CharField(max_length=150, verbose_name='Kategoria') class Meta: verbose_name='Kategoria' verbose_name_plural='Kategorie' def __str__(self): return self.glowna class Witryna(models.Model): nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony') adres_www = models.CharField(max_length=70, verbose_name='Adres www') slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url') email = models.CharField(max_length=100, verbose_name='Adres e-mail') text = models.TextField(max_length=3000, verbose_name='Opis strony') kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria') data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji') class Meta: verbose_name='Strona www' verbose_name_plural = 'Strony www' def publikacja(self): self.data_publikacji=timezone.now() self.save() def __str__(self): return self.nazwa urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^strony$', views.widok_strony, name='widok_strony'), url(r'^$', views.widok_kategorii, name='widok_kategorii'), ] views.py from django.shortcuts import render from .models import Witryna, Kategorie from django.utils import timezone #from django.db.models import Count def widok_strony(request): firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji') return render(request, 'firmy/widok_strony.html', {'firmy': firmy}) def widok_kategorii(request): kategorie = Kategorie.objects.all() wpisy_kat = Kategorie.objects.count() return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie, 'wpisy_kat': wpisy_kat}) widok_kategorii.html {% extends 'firmy/base.html' %} {% block kategorie %} {% for kategoria in kategorie %} <table> <tr> <th> <a href="#">{{ kategoria.glowna|linebreaksbr }} </a>({{ wpisy_kat }}) … -
Django Rest Framework - Changing the labels of the fields
In Django Rest Framework, can we change the labels / names of the fields to more Human Readable format? For example, in below JSON data can we change the "mainline_revenue" to "Maineline Revenue" with space inside? [{"mainline_revenue":18743.0,"regional_revenue":2914.0,"other_revenue":3198.0}] -
Django - Signature of method does not match signature of base method in class
I am learning Django and I am following a lynda.com course. In one of there courses "building an elearning site", the have the following code: class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'courses/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return redirect('manage_course_list') return self.render_to_response({'course': self.course, 'formset': formset}) But I am getting an error message from PyCharm (my IDE) on: def dispatch(self, request, pk): And the error is: Signature of method 'CourseModuleUpdateView.dispatch()' does not match signature of base method in class 'View' less... (Ctrl+F1) This inspection detects inconsistencies in overriding method signatures. Is there a way for me to troubleshoot the issue and see how to begin fixing the error? What is Pycharm even trying to tell me?? I am using python 3 and DJango 1.11 -
How can I add more views to my project/app?
I made another ask here, but know I see what is my real problem. So, I have a django website called www.confiam.com.br, in this site, at .../palestras, I would like to add a view (detail_view, as a blog), so that I have unique url (I think regular expression will be good here). The way I did it, I got 7 views, but I want to add the detail_view page in only 2. I have no idea what I have to do. I would like to do this because I would like to add facebook comments on my site. Many thanks to anyone who can help me. views.py def index(request): posts = Evento.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'core/index.html', {'posts': posts}) def sobre(request): posts = Sobre.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'core/programacao.html', {'posts': posts}) def palestras(request): posts = Palestras.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'core/palestras.html', {'posts': posts}) def minicursos(request): posts = Minicursos.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'core/minicursos.html', {'posts': posts}) def restaurantes(request): posts = Restaurantes.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'core/restaurantes.html', {'posts': posts}) def patrocinio(request): posts = Patrocinio.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'core/patrocinio.html', {'posts': posts}) def hoteis(request): posts = Hoteis.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'core/hoteis.html', {'posts': posts}) obs: I don't have a slug in any model. and urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^programacao$', views.sobre, name='sobre'), url(r'^palestras$', views.palestras, name='palestras'), … -
Django 1.10 & Django-cms 3.4.4 - NoReverseMatch for some browsers
I stumbled across on a very strange issue. The dev env is Django 1.10 & django-cms 3.4.4. When I try to load localhost in Chrome & Firefox everything works fine, but if I try to open it in Safari, it fails with NoReverseMatch at / and it fails with random urls. I also tried to curl http://localhost:8000/ and it works fine. Also tried on Windows and different browsers and it fails for some browsers with the same error. Does someone have any idea what could be the issue? Thanks! -
Django: Change HTML template's font in the middle of a text string that is generated by a {{variable}}
I have a character string generated in views.py like this: context_dict['advice'] = "Please consider selecting " + var1 + " as your next choice." This is displayed in a page whose template has invokes it like this: {% if advice %} My advice: <p style="font-size:20px; color:blue"> <b>{{advice}}</b> </p> Thus the entire setence comes out with the same font: 20px, blue, and bold. However, I would like the word contained in var1 to be green instead of blue (with the rest of the sentence still blue), so that it stands out. I don't see a way to do this. I considered moving more of the static text to the template, so that I could just make var1 the variable and apply a different font to it. This kind of approach won't work for though, because the text that appears static in this example could actually change to 100+ different things depending on what happens in the control flow logic of views.py. -
Django - Aggregate within Annotate
According to the docs, Unlike aggregate(), annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet; this QuerySet can be modified using any other QuerySet operation, including filter(), order_by(), or even additional calls to annotate(). Does this mean I can also use .aggregate() within a .annotate() call? For example, is this valid? class VarietyManager(Manager): def current_stocks(self): self.model.objects.annotate(stock=(Sum(productpart_set.aggregate(Sum(F('units') * F('product__qty')))))) -
Django OAuth Toolkit examples not working
I am trying to test OAuth2 authentication using Django 1.11.4 and Django OAuth Toolkit. After following the tutorial (like, literally verbatim) the consumer application on heroku refuses to exchange the code generated in order to grant me an authentication token with a non-specific error. After much fiddling, I found out that even on DEBUG configuration the OAuth framework would through an insecure transport protocol exception (as it was through local Django server which uses http not https). Thus I ported the web application to an apache instance which was SSL enabled but still the consumer app throws me an unspecified error. Please do note that I am following verbatim the tutorial outlined here and the heroku application when I have my secret key and everything setup as shown in the docs. Although the authorization link (and database entry) is generated when I go back to exchange the code for a token things fail, with a non-specific error. The result looks like this (the full server address is omitted due to obvious reasons). Any idea on what might be wrong? -
Creating Decorators in python with txt output
Implement a python decoraotor that should take whatever the decorated function returns and writes it to the new line. For the sake of this problem, let us assumes that the decorated functions always return a string. Constraints: The Decorator should be named log_message and shloud write to the file /tmp/decorator_logs.txt Example : @log_messgaf Def a_function_that_returns_a_string(): Return “A string” @log_messgaf Def a_function_that_returns_a_string_with_newline(s): Return “{}\n”.format(s) @log_messgaf Def a_function_that_returns_another_string(string=””): Return “Anohter string” On running in python shell: >>> a_function_that_returns_a_string() >>> a_function_that_returns_a_string_with_newline(“Newline”) >>> a_function_that_returns_another_string(string= “Another”) Should write the string to the file $ cat /tmp/decorator_logs.txt A string Newline Another -
Integrating Phone number app in django
I am a beginner in python. I am trying to integrate phonenumber app which I installed from the following url https://github.com/stefanfoulis/django-phonenumber-field Reference url is Good way to store phone numbers in django models I have added 'phonenumber_field' in installed apps in settings.py. forms.py code looks like this from django import forms from django.contrib.auth.models import User from phonenumber_field.modelfields import PhoneNumberField from . import models class SignUpForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField() But in my signup form there is no phone field showing.Is it that I have to call the function inside the model instead in forms. Any help is highly appreciated. -
Customizing Longclaw ProductIndex page
Longclaw/Wagtail newbie here. Wagtail CMS provides an overridable get_context method that makes it possible to pass dictionary values into the template. From the documentation: class BlogIndexPage(Page): ... def get_context(self, request): context = super(BlogIndexPage, self).get_context(request) # Add extra variables and return the updated context context['blog_entries'] = BlogPage.objects.child_of(self).live() return context Longclaw is an eCommerce project built on top of Wagtail. Longclaw has an inbuilt Page model called ProductIndex. Is there any way to pass variables into the ProductIndex template, like I can with get_context? -
Reset Password URL in Angular/Django
I have a Django web application, with an Angular front end. On my sign in page, I have a forgot password link that takes you to a form where you enter in your email. This will send out an email with a reset url. The crux of the problem is that when a user clicks on that link they receive in an email, or copy/paste it into a web browser, it tries to look for a Django url first, before it looks for an angular route. Once the app taps into the angular javascript the url will than work, but if just going straight to that link from the email like it is intended for, it does not work because there is no Django url for it, and Angular hasn't been touched yet. I hope that makes sense. For example here is what the url will look like http://domain-name/dportal/#/reset_password/d7/4oe-0f63050ac947ba024563 Django URLs app tries first # Webapp Urls urlpatterns = [ url(r'^dportal/', include('dealer_portal.urls')), url(r'^views/(?P<page_name>[-\w]+.html)/?$', webapp_views.angular_views), url(r'^simple_page/(?P<page_name>[-\w]+.html)/?$', webapp_views.simple_page), url(r'^home/', webapp_views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^account/', include('account.ajax_urls')), url(r'^vehicle/', include('vehicle.ajax_urls')), url(r'^messages/', include('messaging.ajax_urls')), url(r'^dealer/', include('dealer.ajax_urls')), url(r'^api/homenet/test/', 'data_feed_homenet.views.test_conveyor_interface', name='api_homenet_test'), url(r'^api/homenet/', 'data_feed_homenet.views.conveyor_interface', name='api_homenet'), url('', include('social.apps.django_app.urls', namespace='social')) ] # dealer_portal urls urlpatterns = [ url(r'^home', home, name='home'), url(r'^views/(?P<page_name>[-\w]+.html)/?$', angular_views, … -
Django "no such table" when serializing queryset
I am trying to serialize some data, so that I can export it to xml/json/yaml, however, when following the documentation I am getting the following error: django.db.utils.OperationalError: no such table: AppName_SomeModel I have added only the two lines from the documentation, which are as follow: from django.core import serializers data = serializers.serialize("xml", SomeModel.objects.all()) Can the error be, because my database is in a separate docker container? -
Filter some special characters
Until now, when a user is registering in my app, he can't create a username with special character. I do like this : if username.isalnum() is False: .... But now is I want to enable some special character. I want to enable a list of special characters like ! - _ $ What is the right way to do it ? Thanks -
How am I getting a 502 bad gateway error in browser?
I'm using Django to develop a website for practice. I'm using Digital Ocean as cloud storage. I got my IP address, username, password. The problem is, upon entering my IP address in my browser, I get a 502 bad gateway error written in big bold letters and not my HTML. I tried downgrading my python version via pip install django==1.9 to see if this would work but it doesn't. How can I get rid of this error? -
How to make a variable from django server clickable and open to new tab
<td>{{variable.atr}}</td> How to make above element clickable and open new tab? Thanks -
Recursive __str__ property in Django class
I have this class with a self-referential foreign key in my Django models @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100) parent = models.ForeignKey('Category', blank=True, null=True) def cadena(self): if self.parent is None: return self.name else: return self.cadena(self.parent) + ' - ' + self.name def __str__(self): return self.cadena I want to get a string with a parent of this Category with the method "cadena" like this: Cat - SubCat - SubSubCat With this Code c = Category.objects.get(id=12) print c.cadena() And I get this error: TypeError: cadena() takes exactly 1 argument (2 given) What is the problem? Why that error for 2 given params?