Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django translation date from views.py
I am still a novice in django development. I could not translate date content: I need some help forms.py self.fields['date'] = forms.ChoiceField( choices=[(d, format_html('<span>{}</span> {} {}', '{:%a}'.format(d), '{:%b}'.format(d), d.day)) for d in days], ) myhtml.html: {{form.date}} output (as expected): <span>Sat</span> Nov 4 Here the days are dynamically computed (today plus n number of days). I manually entered day strings in .po file. which is not considered., also tried {{form.date|date:localize}}., How to make translation work for this? -
Issues with URL conf in Django
So I'm working on a project that displays titles of and songs and albums released by a particular artiste from a database. I'm kinda stuck. I'm trying to create a page that displays the songs in an album when you click on the album link. When the link is clicked, I want the URL to display the name of the artiste and the title of the album but i keep getting served with the same error. It is matching the name of the album with artiste names. How do I make the page display the songs in the album. Here's the codes for views def home(request): artistes = Artiste.objects.all() return render(request, 'music/home.html', locals()) def details(request, artiste): artistes = get_object_or_404(Artiste, name=artiste) album = Artiste.objects.get(name=artiste).album_set.all() single = Artiste.objects.get(name=artiste).song_set.filter(single=True) return render(request, 'music/details.html', {'artistes': artistes, 'single': single, 'album':album}) def album_details(request,name,album): albums = get_object_or_404(Album, title=album) artistes = get_object_or_404(Artiste, name=name) single = Album.objects.get(title=album).song_set.filter(single=False) return render(request, 'music/album_detail.html', {'albums': albums, 'single': single}) url patterns app_name = 'music' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^(?P<artiste>.+)/$', views.details, name='details'), url(r'^(?P<name>.+)/(?P<album>.+)/$', views.album_details, name='album_details') ] album details page <body> {% if artistes.album_set.all %} {% for songs in album %} <h4>Albums</h4> <!--<img src="{{album.art}}"><br> --> <a href="{% url 'music:album_details' songs.artiste songs.title %}">{{songs.title}}</a> <h5>{{songs.artiste}}</h5> <h5>{{songs.title}}</h5> {% … -
Django Please supply the ENGINE value error
hey I keep getting the please supply engine value error when trying to connect my amazon rds to django. Thanks!. This is the code : if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['name'], 'USER': os.environ['name'], 'PASSWORD': os.environ['name'], 'HOST': os.environ['xxxxxxx.xxxxxx.us-west-2.rds.amazonaws.com'], 'PORT': os.environ['5432'], } } -
Django: custom HTML tag
I want to clean up views where something like this is very frequent: <div class="some-class {% if x %} {% if x.a %} class_x_a {% else %} class_x_b {% endif %} {% elif y %} class_y {% else %} class_z {% endif %}" data-a="{{ a }}" data-b="{{ b }}" data-c="{{ c }}" > ... </div> I wonder if there is any way to create a custom tag to clear this up, something like this: {% custom_tag x y z a b c %} And that would render the HTML from above. I have tried using simple_tag but I cannot work around the closing tag. I mean, I could just do this: {% custom_tag x y z a b c %} ... </div> But this doesn't seem like a good solution. Or even: {% custom_tag x y z a b c %} ... {% close_tag 'div' %} Also, using simpletag is a bit dirty as well because string format needs to be used. I wonder if there is a HTML element builder class or factory, so your tag could be built this way: custom_tag = HTMLTag('div') if x: custom_tag.add_class('x.a' if x.a else 'x.b') elif y: custom_tag.add_class('y') else: custom_tag.add_class('z') custom_tag.data('a', a) custom_tag.data('b', … -
Django app using nginx+uwsgi in a docker container
So I am trying to create a docker container for my django app and so far it is not going the way I was hoping. I am using supervisor to start both nginx and uwsgi, and they both seem to start up properly, I can enter via http, however, as soon as I try using https it stops working, so I am guessing the fault is in nginx. The nginx part in my Dockerfile looks as follow: # setup all the configfiles RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN rm /etc/nginx/sites-enabled/default RUN ln -s /home/docker/code/nginx-app.conf /etc/nginx/sites-enabled/ The nginx-app.conf file looks like this: # the upstream component nginx needs to connect to upstream django { server 192.168.99.100:8000; # for a web port socket (we'll use this first) } # configuration of the server server { #listen 80 default_server; listen 443; # the domain name it will serve for server_name 192.168.99.100; # substitute your machine's IP address or FQDN charset utf-8; ssl on; ssl_certificate /home/docker/code/app/cert.crt; ssl_certificate_key /home/docker/code/app/key.key; # max upload size client_max_body_size 75M; # adjust to taste access_log /var/log/nginx/lb_access.log; error_log /var/log/nginx/lb_error.log; location /static { alias /home/docker/code/app/static; # your Django project's static files - amend as required } location / { proxy_set_header X-Proxy-Forw-Proto … -
Django Haystack & Whoosh Search Working, But SearchQuerySet Return 0 Results
I seem to be having the same problem as in this (unresolved) question: django-haystack + Whoosh SearchQuerySet().all() always None I've set up Haystack with Whoosh on my Django project and all was working fine at first (SearchQuerySet used to return results), but after an aborted attempt to create a new custom search form (rolled back from git) it appears that indexing and the original search page still all work fine, but now SearchQuerySet() always returns 0 results! Running: manage.py rebuild_index --verbosity=2 Correctly shows: Indexing 14 assets indexed 1 - 14 of 14 (worker PID: 1234). These indexed assets can then all be correctly searched on from the original search form. However, opening a Django shell and running: from haystack.query import SearchQuerySet SearchQuerySet().all().count() Now always returns 0! Relevant "pip freeze": Python 3.5.2 Django 1.9.3 django-haystack 2.5.0 Whoosh 2.7.4 /myapp/search_indexes.py: from haystack import indexes from .models import Asset class AssetIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.NgramField(document=True, use_template=True) asset_description = indexes.CharField(model_attr='asset_description') manufacturer = indexes.CharField(model_attr='asset_manufacturer') def get_model(self): return Asset def no_query_found(self): return self.searchqueryset.exclude(content='foo') def index_queryset(self, using=None): return self.get_model().objects.all() /myapp/templates/search/indexes/myapp/asset_text.txt: {{ object.asset_description }} {{ object.asset_details }} {{ object.asset_manufacturer }} {{ object.asset_model }} ... etc. /myapp/urls.py: urlpatterns = [ .... url(r'^search/', include('haystack.urls')), .... ] -
How to limit number of concurrent users logging in to same account in Django
My site is a digital marketplace website written in Django. Digital content(text, images, videos) on the site is 'locked' by default. Only users who bought those content can view it. There's a story that certain user(who bought the content) give away username/password for free to many people(1,000+ people in Facebook groups, for example). Is it possible to limit number of concurrent login to the same account? I've found this package: https://github.com/pcraston/django-preventconcurrentlogins but what it does is logging previous user out when someone logged in using the same username/password. That would not help because each user only need to type in username/password each time to access 'locked' content. -
Django generic modification to widgets
I'm actually developing user-created forms, where the user enters the type of question, the possible answers, and the form is available to be filled by another user on the website. I'd like to add the form creator the possibility of adding an image affiliated to the question. To do that, I'd need to change a widget's render() method so that , before the tag, I can add my tag. This, in itself, is no problem. However, I use multiple differents widgets , and doing so would make me create a new class for each widget class, and repeat the process above in the exact same way for every widget I use. I'd like to do it the DRY way instead, so I tought of something along these lines : def ImageWidget(<inherits any widget>): def __init__(self, image=None): self.image = image return super().__init__() def render(self, name, value, attrs=None): result = super().render(name, value, attrs) if self.image not None: return "<img></img>" + result else: return result And then, to define my form field, i'll do it this way : field = return forms.FloatField(required=question.required, label=question.text, widget=ImageWidget(NumberInput, image=image)) However, the widget declaration here is clearly flawed, and I can't seem to think of a way to … -
Can not assign None to Django DateTimeField()
Can I judge this is a bug? DateTimeField is inherited from DateField and it can be an optional I have read: How to make Django's DateTimeField optional? How can I make my model fields optional in Django? models.py class Circuit(SoftDeletionModel): ... created_datetime = models.DateTimeField(default=timezone.now) updated_datetime = models.DateTimeField(auto_now=True) expiry_datetime = models.DateTimeField(null=True, blank=True, default=None) At terminal $ python -B manage.py makemigrations --settings=config.settings.docker apps.circuits is ready apps.circuits_networkdevices is ready apps.core is ready apps.customers is ready apps.networkdevices is ready apps.networkscripts is ready apps.portal is ready apps.bod is ready apps.scheduler is ready You are trying to add a non-nullable field 'updated_datetime' to circuit without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now() >>> None Migrations for 'circuits': 0022_auto_20161102_1714.py: - Add field expiry_datetime to circuit - Add field updated_datetime to circuit migration_file.py # -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-11-02 10:14 from __future__ … -
Get aggregate in a template
I have this Django model: class Customer(models.Model): name = models.CharField(primary_key=True, max_length=100) class Order(models.Model): amount = models.PositiveIntegerField(default=0) customer = models.ForeignKey(Customer, default=0) in my view I get them like this: customers = models.Customer.objects.all() and the template lists them like this: {% for customer in customers %} {{ customer.name }} {% endfor %} I would like to add a sum of all amount of all Orders connected that client, something like: {% for customer in customers %} {{ customer.name }} ordered {{ customer.orders.sum(amount) }} items {% endfor %} And according to this question, I should do that in the view, but how? -
Django update context processor variable using ajax
I have items variable in my context processor to count cart items and display on page. How is it possible to do it with ajax? and update number of cart items when user adds new item? context_processors.py def ToyCartItems(request): try: user_cart = Cart.objects.get(user=request.user) cart_items = user_cart.cart_item.all() except Cart.DoesNotExist: cart_items = 0 return {'NumberOfItems': cart_items} -
How can I schedule Celery Group to run at specific time?
I have following normal function which creates Celery Group and tries to run all the subtasks in the Group at specific time: def run_sms_task(smstask): if smstask: phones = [] for user in smstask.userlist.users.all(): phones.append(user.profile.phone) tasks = [] for phone in phones: tasks.append(send_sms_async.s(phone, smstask.text)) job = group(tasks) result = job.apply_async(eta=smstask.starts_at) result.save() return result.id return None All the subtasks are fired when I call this function and not at the defined 'starts_at'. What is wrong? Thanks! -
How to dynamically make an existing non-abstract django model, abstract?
I think I have a more or less unorthodox and hackish question for you. What I currently have is django project with multiple apps. I want to use a non-abstract model (ModelA) of one app (app1) and use it in another app (app2) by subclassing it. App1's models should not be migrated to the DB, I just want to use the capabilities of app1 and it's model classes, by extending its functionality and logic. I achieved that by adding both apps to settings.INSTALLED_APPS, and preventing app1's models being migrated to the DB. INSTALLED_APPS += ( 'App1', 'App2', ) # This is needed to just use App1's models # without creating it's database tables # See: http://stackoverflow.com/a/35921487/1230358 MIGRATION_MODULES = { 'App1': None, } So far so good, ugly and hackish, I know... The remaining problem is now that most of app1's models are non-abstract (ModelA) and if I try to subclass them, none of the ModelA's fields get populated to the db into the table named app2_modelb. This is clear to me, because I excluded the App1 from migrating to the DB and therefore the table app1_modela is completely missing in the DB. My idea now was to clone ModelA, preserve … -
Return nested json reponse
My models.py: class CUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30) last_updated = models.DateTimeField(_('last updated'), default=timezone.now) class SL(models.Model): name = models.CharField(max_length=32) last_updated = models.DateTimeField(default=timezone.now) uuid = models.UUIDField(primary_key=True) class Key(models.Model): last_updated = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=32, default = 'Unnamed') sl_uuid = models.ForeignKey(SL) user = models.ForeignKey(CUser) urls.py: urlpatterns = [ url(r'^getstate/$', views.GetStateView.as_view(), name='getstate'), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] serializers.py: class GetStateSerializer(serializers.ModelSerializer): class Meta: model = User fields = tuple(User.REQUIRED_FIELDS) + ( User.USERNAME_FIELD, 'last_updated', ) read_only_fields = ( User.USERNAME_FIELD, ) views.py: class GetStateView(views.APIView): queryset = User.objects.all() serializer_class = serializers.GetStateSerializer permission_classes = ( permissions.IsAuthenticated, ) def get(self, request, format=None): last_updated = self.request.query_params.get('last_updated') if not last_updated: return response.Response( {"last_updated": ["Required field missing."]}, status=status.HTTP_400_BAD_REQUEST ) else: try: last_updated = models.DateTimeField().to_python(last_updated) if last_updated >= self.request.user.last_updated: return response.Response( {"success": ["Up-to-date content."]}, status=status.HTTP_200_OK ) else: return self.request.user except django.core.exceptions.ValidationError: return response.Response( {"last_updated": ["Invalid timestamp."]}, status=status.HTTP_400_BAD_REQUEST ) I want to get json response as: { "email":"abc.com", "first_name":"abc", "last_updated":"2016-11-02T02:12:36Z", "sls": [ { "name":"123", "last_updated":"2016-11-02T02:12:36Z", "uuid":"ac9d496d-62ba-45a1-a1ec-e1eca571b656" }, { "name":"23", "last_updated":"2016-11-02T02:12:36Z", "uuid":"ac9d496d-62ba-45a1-a1ec-e1eca571b656" } ] } In my above view, I am returning "return self.request.user" but I get AssertionError "Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view". It uses token authentication and will use the key … -
User Login in Django
I am quite new to Django and I have a question,I have a separate table for user which contain of username,password. I would like to make a login form with that table, Is is possible in Django? How? Please help. -
How to implement only Social login with django-allauth?
I'm trying to implement social auth with Django-allauth I want only social login in my project, should I have to override the default auth form for that? And do I need to secure my custom form with a csrf_token? -
Django: closest possible to the project name
I am creating a reusable app that needs to know the name of the project from which it is being used. Getting the AppConfig (or just the app name) of the app with the settings module in it would be already sufficient. Other approaches are welcome as well. Why would I ever want this: Different projects will have portions of their data shared in the same db schema. I still need to figure out to which project does some of it belong. Project names are considered to be unique at this point, default app names are the same as the corresponding project names (django-admin startproject behavior). Based on the previous experience, expecting the users of my app to specify something extra in their project settings is just not reliable enough. -
Devstack dashboard "cannot import name _compare_digest" error
Devstack use Apache and WSGI to deploy horizon. When the devstack completely depolyed and browse http://localhost/dashboard, I got "500 Internal Server Error". error log shows: /var/log/apache2/horizon_error.log: root@ubuntu:/var/log/apache2# more horizon_error.log 2016-10-31 10:59:00.588354 mod_wsgi (pid=27074): Target WSGI script '/opt/stack/horizon/openstack_dashboard/wsgi/django.wsgi' cannot be loaded as Python module. 2016-10-31 10:59:00.588498 mod_wsgi (pid=27074): Exception occurred processing WSGI script '/opt/stack/horizon/openstack_dashboard/wsgi/django.wsgi'. 2016-10-31 10:59:00.588535 Traceback (most recent call last): 2016-10-31 10:59:00.588565 File "/opt/stack/horizon/openstack_dashboard/wsgi/django.wsgi", line 4, in <module> 2016-10-31 10:59:00.588640 from django.core.wsgi import get_wsgi_application 2016-10-31 10:59:00.589583 File "/usr/local/lib/python2.7/site-packages/django/core/wsgi.py", line 2, in <module> 2016-10-31 10:59:00.589657 from django.core.handlers.wsgi import WSGIHandler 2016-10-31 10:59:00.589688 File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 11, in <module> 2016-10-31 10:59:00.589772 from django import http 2016-10-31 10:59:00.589812 File "/usr/local/lib/python2.7/site-packages/django/http/__init__.py", line 2, in <module> 2016-10-31 10:59:00.589876 from django.http.request import (HttpRequest, QueryDict, 2016-10-31 10:59:00.589914 File "/usr/local/lib/python2.7/site-packages/django/http/request.py", line 12, in <module> 2016-10-31 10:59:00.590055 from django.core import signing 2016-10-31 10:59:00.590079 File "/usr/local/lib/python2.7/site-packages/django/core/signing.py", line 46, in <module> 2016-10-31 10:59:00.590130 from django.utils.crypto import constant_time_compare, salted_hmac 2016-10-31 10:59:00.590138 File "/usr/local/lib/python2.7/site-packages/django/utils/crypto.py", line 8, in <module> 2016-10-31 10:59:00.590190 import hmac 2016-10-31 10:59:00.590211 File "/usr/local/lib/python2.7/hmac.py", line 8, in <module> 2016-10-31 10:59:00.590281 from operator import _compare_digest as compare_digest 2016-10-31 10:59:00.590310 ImportError: cannot import name _compare_digest My python version is Python 2.7.12, and I try import operator, it's nothing wrong. Python 2.7.12 (default, Nov 2 … -
Django management form missing or tampered with
I have a template with lots of forms on it, all wrapped in one form element. I have on MultiForm that is comprised of 4 regular forms, and two formsets. The formsets have been overridden to use custom formset classes. I render the management forms in the templates, and can see the relevant info in the post. For the formsets, I initialize the page with only one form visible. When I try to submit the combined form I get the following error: ManagementForm data is missing or has been tampered with I have searched everywhere for the answer, and read about 15 posts on stack overflow with the same error, but none of the solutions seem to help. The error page highlights the following line: {{ beneficiaries.management_form }} Template: <form class='pension_form' id='implementation_form' action="{% url "confirmation_form" %}" method="post"> {% csrf_token %} <ul> {{ the_form.user_info.as_ul }} </ul> <ul> {{ the_form.spouse_info.as_ul }} </ul> <div class='formset_container'> {{ children.management_form }} {% for form in children %} <div class='formset'><ul>{{ form.as_ul }} </ul><a class="glyphicon glyphicon-plus"></a></div> {% endfor %} </div> <ul> {{ the_form.employer_info.as_ul }} </ul> <ul> <li>{{ the_form.beneficiary_general.WHO_BENEFITS }}</li> </ul> <div id='beneficiary_info_container' style='display:none;'> <div class='formset_container'> {{ beneficiaries.management_form }} {% for form in beneficiaries %} <div class='formset' > <ul>{{ … -
Modifying User instances in Django already in database
Let's say I already have existing User instances in my database. Then, I just introduced a new model in my app: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') nickname = models.CharField(max_length=30, blank=True) I want to create a UserProfile instance for every user. I know that signals can handle this upon something like User().save(). However, what do I do with the users already in my database? Currently I handle it in views.py: try: user.profile.nickname = 'my_nickname' except: profile = UserProfile() profile.user = user profile.nickname = 'my_nickname' profile.save() But this makes the view quite long. Is there a better way to do it? -
How can I return an HttpResponse with Django Rest Framework?
I'm building an API function that allows the client to sent a GET request with URL parameters, the server receives and process a file based on the given info, and returns a custom file. The good news is I all of the steps working independently! I was able to get everything working inside the def get_query function except returning the HttpResponse. The function requires a Queryset response (makes sense I guess..). I figured I needed another function so I could return the HttpResponse, so I created def send_file. I'm not sure how to call this function and right now it just skips it. views.py. class SubFileViewSet(viewsets.ModelViewSet): queryset = subfiles.objects.all() serializer_class = SubFilesSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def send_file(self, request): req = self.request make = req.query_params.get('make') model = req.query_params.get('model') plastic = req.query_params.get('plastic') quality = req.query_params.get('qual') filenum = req.query_params.get('fileid') hotend = req.query_params.get('hotendtemp') bed = req.query_params.get('bedtemp') if make and model and plastic and quality and filenum: filepath = subfiles.objects.values('STL', 'FileTitle').get(fileid = filenum) path = filepath['STL'] title = filepath['FileTitle'] ''' #Live processing (very slow) gcode = TheMagic( make=make, model=model, plastic=plastic, qual=quality, path=path, title=title, hotendtemp=hotend, bedtemp=bed) ''' #Local data for faster testing gcode = "/home/bradman/Documents/Programming/DjangoWebProjects/3dprinceprod/fullprince/media/uploads" test_file = open(gcode, 'r') response = HttpResponse(test_file, content_type='text/plain') response['Content-Disposition'] = … -
Checking boxes for items passed through context in Django
I am using django-mptt with the following code to display a tree structure of categories, sub-categories (and so on) with checkboxes. The idea being that the user can choose which categories to use. {% load mptt_tags %} <ul > {% recursetree nodes %} <li> <input type="checkbox" id="{{ node.id }}" value="{{ node.id }}"name="category"/> {{ node }} {% if not node.is_leaf_node %} <ul> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> I have the checking of the boxes working as I want (similarly to this thread), but I'm having trouble figuring out how to check the previously checked boxes from the start when the user opens the page to edit the selection. How can I have the checkboxes checked for the node.ids I'm passing through in the context = {'selected_ids': selected_ids} when the page loads? -
How to change the foreign key constraint from id to another field (say uuid) on existing database using django migrations
I tried the following approach (django 1.9.2): Translate id to uuid and copy it in a new field Remove existing foreign key constraint based on id Add foreign key constraint on new field based on uuid I used the schema_editor.remove_field() and schema_editor.add_field() methods to achieve this This however was not working properly in sqlite database. Worked for mysql and postgres database. Has someone done this before using just the migrations on existing database with records. -
settings.py does not exist django
Running Python 2.7 Mac OSX. I did: django-admin.py startproject test123 cd test123 open settings.py Error: /users.../test123/settings.py does not exist. Why is this happening? -
Is it a correct pattern to mock methods within factoryboy?
I am currently using factory_boy to create fixtures for my django models. I have been trying to find factoryboy patterns for custom manager methods like the following: class DataCenterManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(category='datacenter') I am using also writing unit tests (using pytest), so the goal is to avoid any db whatsoever. Based on research so far I am drawing a few conclusions: Most ppl just do functional or integration tests when it comes to models. Mocking typically happens within the test itself. Any mocking within the factoryboy factory is typically done with faker and this is typically used for data contained withing vars. If people mock the orm manager methods, this is typically done as a test fixture outside of factoryboy. Question I have is, is it acceptable practice to mock out custom manager methods within factoryboy? I have yet to locate any code that demonstrates this. This tells me this is probably not common.