Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error on deploying Angular 2 + Django REST
I'm deploying my Angular2 + Django REST app on pythonanywhere. And stuck with error: net::ERR_INCOMPLETE_CHUNKED_ENCODINGscheduleTask @ XHR error loading It seems this happening on map part of systemjs.config.js. In localhost all working fine. full stack trace: DevTools failed to parse SourceMap: http://rodion.pythonanywhere.com/static/node_modules/bootstrap/dist/css/bootstrap.min.css.map DevTools failed to parse SourceMap: http://rodion.pythonanywhere.com/static/node_modules/core-js/client/shim.min.js.map zone.js:1274 GET http://rodion.pythonanywhere.com/static/node_modules/@angular/compiler/bundles/compiler.umd.js net::ERR_INCOMPLETE_CHUNKED_ENCODINGscheduleTask @ zone.js:1274ZoneDelegate.scheduleTask @ zone.js:216Zone.scheduleMacroTask @ zone.js:153(anonymous function) @ zone.js:1304send @ VM1436:3fetchTextFromURL @ system.src.js:1051(anonymous function) @ system.src.js:1781ZoneAwarePromise @ zone.js:478(anonymous function) @ system.src.js:1780(anonymous function) @ system.src.js:2809(anonymous function) @ system.src.js:3387(anonymous function) @ system.src.js:3701(anonymous function) @ system.src.js:4093(anonymous function) @ system.src.js:4556(anonymous function) @ system.src.js:4825(anonymous function) @ system.src.js:407ZoneDelegate.invoke @ zone.js:203Zone.run @ zone.js:96(anonymous function) @ zone.js:462ZoneDelegate.invokeTask @ zone.js:236Zone.runTask @ zone.js:136drainMicroTaskQueue @ zone.js:368ZoneTask.invoke @ zone.js:308 (index):51 Error: (SystemJS) XHR error loading http://rodion.pythonanywhere.com/static/node_modules/@angular/compiler/bundles/compiler.umd.js(…)(anonymous function) @ (index):51ZoneDelegate.invoke @ zone.js:203Zone.run @ zone.js:96(anonymous function) @ zone.js:462ZoneDelegate.invokeTask @ zone.js:236Zone.runTask @ zone.js:136drainMicroTaskQueue @ zone.js:368ZoneTask.invoke @ zone.js:308 systenjs.config.js: /** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config({ //static defaultJSExtensions: true, paths: { // paths serve as alias 'npm:': 'static/node_modules/' }, // map tells the System loader where to look for things map: { app: 'static/dist', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', … -
Django: ImportError: No module named sslserver
I have setup a django server on centos 7. When I start the server, I encounter this error Unhandled exception in thread started by <function wrapper at 0x32b6ed8> Traceback (most recent call last): File "/root/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/root/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/root/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/root/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/root/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/root/venv/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/root/venv/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named sslserver -
Django, How to get random posts list result?
CODE: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def get_queryset(self) : elasped_minutes_after = datetime.now() - timedelta(minutes=600) self.list_after = Post.objects.filter(created_date__gte = elasped_minutes_after).order_by("?") return self.list_after Question : What i know is if length of self.list_after was shorter than 33, For example, self.list_after has 20 posts, i want show 20 posts all. And If self.list_after was longer or equal 33, for example self.list_after has 50 posts, i want just show 33 posts for random. Would you help me? -
set page to users browser language preference
I am using Django 1.10 and python 3.5. I have a landing page in different languages (en, en-CA, en-GB, fr, fr-ch, fr-CA, de, de-AT, de-CH, es, es-419, it, it-CH). I have set up a select list of the languages on the landing page, so that the user can change the language of the landing page at will. When the landing page loads, I have in place code to detect the language preference of the users browser and then set the relative language in the language select list. However, there is an issue with this. The issue that I have is that I cannot figure out how to set the selected language of the language select list, when the user's browser language preference is not in the select list. For example, when the users browser language preference is English (United Kingdom) / en-GB, then the code I have correctly assigns the selected to the en-GB language. But, when the users browser language preference is English (Australia) / en-AU, then the code I have does not assign the selected to the en-GB language (Australia is more closely aligned to en-GB not en or en-US). Does anyone have any suggestions so I can … -
Can we use cursor pagination of django rest-framework in ndb project?
Can we use cursor pagination of Django rest-framework in ndb project? -
When capturing Django named groups from a URL, how not to decode them?
I have the following url pattern defined (simplified for clarity) that captures the asset key (an arbitrary string) from a url: url(r'^assets/(?P<key>.+)$', views.AssetDetail.as_view()) And my view is defined like this: def get(self, request, key): ... This becomes interesting when I make these two requests: /assets/some+key /assets/some%2Bkey Both requests result in the view's key parameter containing the string "some+key". So, it looks like url decoding happens when the named group is captured and passed to the view, resulting in two different keys getting the same value. This is a problem because I need to distinguish between these two keys. How do I get the key to be passed into my view raw and not decoded? -
Django rest framework browsable API filters backend not showing
I can't get the browsable API to show the "Filters" button after configuring django to use the filtering backend. According to the documentation all I need to do is add the following few lines of code into the site's settings.py file and the filters should automatically be in the browsable API's web interface, and I just don't see it there. I tried restarting the web server (I'm working with ./manage runserver) and that didn't help. From settings.py: REST_FRAMEWORK = { <snip> 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), Following content of pip freeze: (venv) mba15:server nir$ pip freeze | grep django django-allauth==0.28.0 django-celery==3.1.17 django-filter==0.15.3 django-registration-redux==1.4 django-rest-auth==0.8.2 djangorestframework==3.5.3 -
Is there a more intuitive way to write updateforms?
I am currently working on a webapp for timemanagement and shiftplaning. First things first, I'm pretty new at webops and Django. With my new knowledge I was digging through different blogs ( for example Django Girls - which is almost pretty good!) and through stackoverflow. But there is one question which bothers me. Is there any different way to update saved form data without using class Foo(generic.UpdateView): for example by using a ModelForm which allready displays the value that we want to change? I am a little bit confused at the moment, and like the thing that I can insert HTML-code to the ModelForm-forms. If you can give me any hints, tips or clues to insert HTML-code to my UpdateView I'd appreciate that. Thank you. -
I need help getting started with Mezzanine
I am working on building a blog for my website. I am deploying the whole application on an AWS environment. I want to see my website when i am redirecting to the PublicDNS of my instance and when i use PublicDNS/blog i want to see my blog. I have my web app developed using python/Django framework. I have tried running Django web app and wordpress on the same apache server and that didn't work for me. I am still working on it and I am now thinking to install Mezzanine instead of wordpress to complete my project. I have read that Mezzanine is built using Django framework. Is Mezzanine, a open source? can I have it for free? I want to know if this will make it easier for me if i use Mezzanine instead of using wordpress to achieve what i am desiring for. If yes how can I get started I have my Django web app all set for launch. Please advice. Thanks in advance -
How to use Docker to run various web servers on default ports on one server?
My goal is to have web servers that work on the default port so users don't have to type in a port #. Easy to do with LAMP stack, where A is apache... and no other web server exists. However, if I purchase general purpose hosting with Centos and I want to run 1) Gunicorn/NGINX for Python/Django -> access from example.com from outside (no port required to be entered by the web browser. 2) Spring framework in a Java EE container - Java EE defaults to port 8080 and other ports in that range but people just enter a domain name and expect it to work. -> So reachable from example2.com 3) Node.js - Reachable from example3.com 4) PHP apps such as WordPress, Drupal on LAMP - example3.com Recommendations are appreciated. My closest experience that seems to do this for example would be AWS with load balancer allowing access from public web - app servers accessible from only load balancer. Thanks, Bruce -
When should the hostname be in ALLOWED_HOSTS
I used to leave ALLOWED_HOSTS = [] when going with some hostname other than localhost or 127.0.0.1 with no problems, today I encountered this error: Invalid HTTP_HOST header asking me to add the hostname to ALLOWED_HOSTS, even when I commented out the other hostnames from /etc/hosts. I tried the other projects, it worked with the same settings. Why is it happening now? What's the use of ALLOWED_HOSTS? And Why it worked without filling it? The first time I get the courage to ask why something works. Thanks. -
How do I register a "dynamic" inclusion tag within Django?
How do I use Django's "inclusion tags" to pull a dynamic template based on an argument provided to a View? I'm creating a "Download" page for content on my website. Many different pieces of content can be downloaded, and I want to use just one View for the Download page that pulls in optional parameters from urls.py: urls.py url(r'^download/download-1/$', base_views.download, { 'name':'download-1', 'title':'Download 1', 'url':'https://sample-download-location.com/download-1.zip', 'upsell':'upsell-1' } ), url(r'^download/download-2/$', base_views.download, { 'name':'download-2', 'title':'Download 2', 'url':'https://sample-download-location.com/download-2.zip', 'upsell':'upsell-2' } ), views.py def download(request, name, title, url, upsell): return render(request, 'base/pages/download/download.html', { 'title': title, 'url': url, 'upsell': upsell, } ) download.html Part 1 The information from this View will then be piped into a Download template like so: <div id="thank-you-content"> <div class="wrapper"> <h1>Download <em>{{ title }}</em></h1> <p>Thanks for purchasing <em>{{ title }}</em>! You can download it here:</p> <p><a target="_blank" class="btn btn-lg btn-success" href="{{ url }}">Download Now</a></p> <p>And afterwards, be sure to check out...</p> </div> </div> Here's the tricky part: at the bottom of the download.html page, I want to have an inclusion tag that dynamically populates based on the page specified in the 'upsell' paramter — something along these lines: download.html Part 2 {% upsell %} I then want this tag to pull … -
Django - when I pass all objects of a certain class, how can I check which subcclass the object is in a template?
Obligatory, I'm a django beginner and I don't understand why my code isn't working. I'm trying to sort through a parent class in a view to get an object, then pass that object to a template. In the template, I have certain fields showing for each subclass and some which are inherited from the parent class. I have tried using isinstance() in my template but it raised errors. After that I tried to add a static attribute to each subclass to check via an if statement in my template. When doing this, none of the subclass specific fields show. So I tried to set the attribute in the view and still had none of the subclass specific fields display. Here are the parent object class and one of the subclasses (models): class Chunk(models.Model): name = models.CharField(max_length=250) text = models.CharField(max_length=500) images = models.FileField() question = models.CharField(max_length=250) expected_completion_time = models.IntegerField(default=1) keywords = models.CharField(max_length=250, blank=True, null=True) topic = models.CharField(max_length=250, blank=True, null=True) course = models.CharField(max_length=250, blank=True, null=True) def get_absolute_url(self): return reverse('detail', kwargs={'pk':self.pk}) def __str__(self): return self.name class Concept(Chunk): application = models.CharField(max_length=500) subconcept1 = models.CharField(max_length=500, blank=True, null=True) subconcept2 = models.CharField(max_length=500, blank=True, null=True) subconcept3 = models.CharField(max_length=500, blank=True, null=True) subconcept4 = models.CharField(max_length=500, blank=True, null=True) subconcept5 = models.CharField(max_length=500, … -
How to duplicate a Wagtail page with OneToOneField relation to an external model
I'm looking if it's posible to duplicate or copy a Wagtail page through Wagtail admin interface knowing that this page has a OneToOneField relation with an external model. when I actually do that django raises a Validation Error "There is already a MyPage with this ExternalModel". It is posible to edit an existing Page and save it as "New Page" like in django admin interface so i can select other ExternalModel option and avoid duplicate constraint? Thanks. -
Python call Java causes Error: Could not find or load main class
I am having issues to use the java program https://github.com/antonydeepak/ResumeParser/ in Django project in a localserver in MAC OS. I have installed ResumeParser in the Django Project like: -- Django Project -- app1 -- app2 -- ResumerParser Here is my code but it says "Could not find or load main class". if form.is_valid(): f = form.save(commit=False) resume = form.cleaned_data['resume'] cmd = ['java', '-cp', 'bin/:../GATEFiles/lib/:../GATEFiles/bin/gate.jar:lib/*', 'code4goal.antony.resumeparser.ResumeParserProgram %s textOutput.json' % resume] subprocess.Popen(cmd) Any clues of how to solve this? I've tried every post related to this theme in StackOverflow no success. Thanks in advance -
Django: Pass request.user to form using inlineformset_factory
I have a form where I want to allow people to create a Topic and a Point. Points have a foreignkey to Topic. Both Topic and Point have a poster field that is a foreignkey to the user model. I now have the problem that the poster of a Point should be automatically determined from the request.user. However, I cannot find a way to pass the request.user to the Formset generated by inlineformset_factory. When I want to save my form I always get this validation error: A user id must be associated with a point. How can I set the poster of a point to the request.user? These are my models: class Topic(DatedModel): """ Represents a topic. """ # Category can be empty as assigned by admin later category = models.ForeignKey( 'category.Category', verbose_name=_('category'), related_name='topics', blank=True, null=True) poster = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('Poster'), blank=True, null=True) subject = models.CharField(max_length=191, verbose_name=_('Subject')) class Point(DatedModel): """ Represents a point. A point is always linked to a topic. """ topic = models.ForeignKey( 'forum_conversation.Topic', verbose_name=_('Topic'), related_name='points') poster = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='points', verbose_name=_('Poster'), blank=True, null=True) # Point can be for or against a topic is_for_topic = models.BooleanField(default=False) subject = models.CharField(verbose_name=_('Subject'), max_length=191) I have used inlineformset_factory as was recommended in … -
Detect foreign key relation being added in Django
I have a model named Project that has many fields, one of which is an optional foreign key relation to another model, Status. class Status(models.Model): title = models.CharField(max_length=255) class Project(models.Model): status = models.ForeignKey(Status, null=True, blank=True) When a status is added to a project I need to check the status title and, if it matches a certain value, call a function. I'm wondering what the best way to do this is. One approach that would probably work would be to override the Project model's save function and do a database call and compare the old status field to the current one. However there can be multiple people working on the same project at once so I'm worried about performance and inconsistent data. -
Trigger "auto_now" on related model
I would like the field "updated" to be triggered in the Tag model whenever a M2M relationship is added to a "Tag" in Movie. I have made an attempt, but the error tells me: Task matching query does not exist class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) updated = models.DateTimeField(auto_now=True) class Movie(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): orig = Movie.objects.get(pk=self.pk) for t in self.tag.exclude(pk__in=orig.tag.values_list('pk', flat=True)): t.save() super(Task, self).save(*args, **kwargs) -
fieldsets don't work with django constance
I am using django constance with database and set it up according to this documentation And so far it works fine, except for the Fieldsets-Option. I am using exactly the code from the tutorial here: CONSTANCE_CONFIG = { 'SITE_NAME': ('My Title', 'Website title'), 'SITE_DESCRIPTION': ('', 'Website description'), 'THEME': ('light-blue', 'Website theme'), } CONSTANCE_CONFIG_FIELDSETS = { 'General Options': ('SITE_NAME', 'SITE_DESCRIPTION'), 'Theme Options': ('THEME',), } However, I am getting this So what's missing is the two lines "Generel Options" and "Theme Options". Do I have to customize something in the settings first? I don't think I missed anything from the tutorial here. Any idea? -
Turn Off KeepAlive on Apache for Django application deployed using mod_wsgi on AWS ElasticBeanstalk
I'm looking for a way to deploy my django application on AWS ElasticBeanstalk that allows me to set Apache's KeepAlive configuration to off. This is because I am serving static and media files from cloudfront using s3 so there is no need to Keep the TCP connection alive. I think i can ssh into my EC2 instance and change my httpd.conf file and restart the apache server. However, this won't solve the problem because if an instance replacement is performed, the default settings will be deployed with it. I am looking for something like an .ebextension command that will allow me to configure my httpd.conf settings during deployment of my application package. For example, reading this post: https://realpython.com/blog/python/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/ I figured i can setup wsgi in daemon mode by writing an .ebextension config file with the following: "aws:elasticbeanstalk:container:python": WSGIPath: MyApp/wsgi.py NumProcesses: 3 NumThreads: 20 Which creates the appropriate module to be loaded into my wsgi.conf file. I am looking for something similar to automate my "KeepAlive" setting. Any one know if this can be done? -
{{ form.non_field_errors }} with django-crispy-forms
I have the following django form using crispy-forms: Everything looks amazing except the {{ form.non_field_errors }} part. It just looks like a bullet list as follows: You picked the same team! <div class="panel panel-default"> <div class="panel-heading"> <h2 class="panel-title">TEAM SELECTION</h2> </div> <div class="panel-body"> <form action="" method="post"> {% csrf_token %} <div>{{ form.non_field_errors }}</div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-5">{{ form.team1|as_crispy_field }}</div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-5">{{ form.team2|as_crispy_field }}</div> <div class="col-xs-12 col-sm-2 col-md-2 col-lg-2"><button type="submit" class="btn btn-primary btn-block"; margin-bottom: 2cm;>Submit</button></div> </form> </div> </div> Anyone know how I can have make the {{ form.non_field_errors }} look as exciting as the rest of the form? Many thanks, Alan. -
Slug in url with CBV in django 1.8
I use Django 1.8 and I want to buid blog with slugs in urls. But my code doesn't work. Here is my template with link to post details: {% extends "base.html" %} {% block head_title %}<title>Blog</title>{% endblock %} {% block content %} <div class="container"> <h2>Blog</h2> {% for i in blog %} <p><b>{{ i.date|date:"D, d M Y" }}</b></p> <h4><a href="{% url 'projde:blogdetail' slug=i.slug %}">{{ i.title }}</a></h4> <p>{{ i.text|truncatewords:100 }}</p> {% if not forloop.last %} <hr> {% endif %} {% endfor %} </div> {% endblock %} Here is my model: class BlogPost(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=200, unique=True) text = models.TextField() date = models.DateTimeField() is_online = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("blogdetail", kwargs={"slug": self.slug}) Here is my view: class BlogDetail(DetailView): model = BlogPost template_name = "projde/blogdetail.html" and my url: url(r'^blog/(?P<slug>\S+)$', BlogDetail.as_view(), name="blogdetail"), -
Pytest and Django settings runtime changes
I have a receiver that needs to know whether DEBUG set to True in my settings.py. @receiver(post_save, sender=User) def create_fake_firebaseUID(sender, instance, created=False, **kwargs): # Fake firebaseUID if in DEBUG mode for development purposes if created and settings.DEBUG: try: instance.userprofile except ObjectDoesNotExist: UserProfile.objects.create(user=instance, firebaseUID=str(uuid.uuid4())) The problem is that when I create a user using manage.py shell everything works as expected. However, if I run my tests via py.test, the value of settings.DEBUG changes to False. If I check it in conftest.py in pytest_configure, DEBUG is set to True, it changes somewhere later and I have no idea where. What can cause this? I am sure that I do not change it anywhere in my code. -
504 Gateway Time-out when trying to access a django app using nginx+uwsgi
I am building a docker container for a django app using uwsgi + nginx. As I am kinda new to all of this, I used tutorials in order to set nginx. Everything goes well when I build and run the container. When I visit the website its all fine,however, as soon as I try to log as the admin i get 504 Gateway Time-out. My nginx.conf file looks as follow: upstream django { server unix:///path/to/socket.sock; # for a file socket } server { listen 80 default_server; listen 443 ssl; server_name 192.168.99.100; # substitute your machine's IP address or FQDN charset utf-8; ssl on; ssl_certificate /path/to/certificate.crt; ssl_certificate_key /path/to/key.key; client_max_body_size 75M; # adjust to taste access_log /path/to/accesslog; error_log /path/to/errorlog; location /static { alias /path/to/static; # your Django project's static files - amend as required } location / { uwsgi_ignore_client_abort on; proxy_read_timeout 300; proxy_connect_timeout 90; uwsgi_pass unix:///path/to/socket.sock; include uwsgi_params; proxy_set_header X-Proxy-Forwarded-Protocol $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect http:// https://; } } My guess is, that the IP changes and as soon as I try to access I get the error. When I check the error logs what I found was: [error] 11#0: *17 upstream timed out (110: Connection … -
Django: Someone please share an example or a definitive guide on making a web-page form send user submitted data to be get stored in a model?
I'm new to Django and need to quickly create a custom Q&A forum. I can handle the other pieces of the puzzle, but one thing I'm currently super confused about is updating the model with data from the web-page that the user fills in a form and submits. Also, the user wouldn't supply all fields of the model too- for example: in a question model: he would provide the question text and the question details only and the remaining question id, created date, user id as foreign key need to get automatically saved along with the question text and details when the user hits submit. Can someone please point me towards a working example or a definitive guide on how to do this? I referred to Django Modelforms but it confused me more than helped me as I dont think they have explained all pieces of the puzzle or its for someone more well versed with Django. Specifically, I'm a bit confused on whats the best way to make the form appear on a html template and how to collect and handle the data in the views.py i.e., should I collect the Post data on the view where the form …