Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is equivalent in django of symfony services
In symfony, it is possible to write services. I do not talk about web services, i am talking about services (what you configure in services.yml, with dependency injection). If 2 controllers actions need to do the same work (sending an email for example), i create a service in order to factor common code. Is there the same thing in python django ? Thanks -
django how to add a MinLengthValidator validator in a form
I have a search form and I want to validate that the input 'seach_word' has at least 4 letters. I'm getting this error when I'm trying to validate my forms The response content must be rendered before it can be iterated over. #views.py class SearchFormView(FormView): form_class = PostSearchForm template_name = 'lineup/post_search.html' def form_valid(self, form): schWord = form.cleaned_data['search_word'] search_type = form.cleaned_data['search_type'] context = {} if search_type == 'store': post_list = Store.objects.filter( Q(cie_name__icontains=schWord)).distinct() context['object_type'] = 'store' context['object_list'] = post_list if search_type == 'city': post_list = Address.objects.filter( Q(city__icontains=schWord)).distinct() context['object_type'] = 'city' context['object_list'] = post_list context['form'] = form context['search_term'] = schWord return render(self.request, self.template_name, context) def form_invalid(self, form): schWord = form.cleaned_data['search_word'] messages.add_message( self.request, messages.WARNING, _('Please correct this...')) context = super(SearchFormView, self).form_invalid(form) return render(self.request, self.template_name, context) content of forms.py #forms.py class PostSearchForm(forms.Form): SEARCH_TYPE_CHOICES = ( ('city', 'city'), ('store', 'store'), ('product', 'product'), ) search_type = forms.ChoiceField(choices=SEARCH_TYPE_CHOICES, required=True) search_word = forms.CharField(label='Search Word', validators=[MinLengthValidator(4)], required=True) ''' def clean_search_word(self): cd = self.cleaned_data if len(cd['search_word']) < 4: raise forms.ValidationError('too short.') return cd['search_word'] ''' def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Fieldset( '', Field('search_type', css_class='span6'), Field('search_word', css_class='span6'), ), FormActions( Submit('submit', 'Go', css_class='btn btn-primary') ) ) super(PostSearchForm, self).__init__(*args, **kwargs) -
How to run Django app with Gunicorn/WSGI webserver?
I have my existing Django application running locally on my MacBook. It's directory structure looks something like this: myproject/ mySite/ __init__.py settings.py urls.py wsgi.py myApp1/ __init__.py models.py views.py manage.py requirements.txt Up until now, I have been using the Django toy webserver to run my app: ./manage.py runserver 0.0.0.0:8000. But now I want to use gunicorn instead. So I'm following the instructions here. I do source myVirtualenv/bin/activate && cd myproject && gunicorn KingkajouSite.wsgi. I get the following error: File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "myproject/MyApp2/models.py", line 11, in <module> from caching.base import CachingManager, CachingMixin ImportError: No module named caching.base When I run ./manage.py runserver 0.0.0.0:8000 from the same location it works perfectly fine. Why? Am I doing something wrong? Does Django-Cache-Machine not work with Gunicorn/WSGI? How to work around this issue? -
How form class attributes work in django
how Form class attributes work in django ? class Test(forms.Form): x = forms.CharField(max_length=20) def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) print hasattr(self, 'x') # return False ... what type of mechanism work here ? -
Python-DjangoREST-uWSGi-nginx
This is my first time posting and its a pretty long question. I'm a beginner and I've decided to learn and use Python and DjangoREST to build my first web application. Unfortunately, I have a lot of issues that I'm not sure how to get answers to. Querying Google one at a time for each component is giving me answers that sometimes conflicts with another component. First things first, the following is my project setup:- OS->Ubuntu 16.04.1 Backend->Python3 and DjangoREST Webserver->uWSGI and nginx Database->PostgreSQL Client Side software->AngularJS(which requires the setup of Node.js and NPM) Now I installed pip and went through the process of creating a virtualenv and ran a test Django app. I was able to get that done. When I went through the documentation of uWSGI and Nginx over here http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html, I came across the following line the web client <-> the web server <-> the socket <-> uwsgi <-> Django This has me slightly confused. Is there a specific order in which I need to install the software I need? And if yes, could you all tell me the correct order? Thanks in advance! -
AttributeError: "QuerySet" doesn't have attribute 'model'
I'm trying to create a basic django-rest-framework backend with mongoengine as a database. I have successfully made a basic list of entries which supports POST and behaves as needed with required fields. However I encounter this bug with QuerySet not having attribute 'model'. Of what I've seen in the web - people get this kind of bug when putting a filtered collection in object. However in my case it is different(I believe). The error appears when I'm accessing /box/1 endpoint. The source codes as below: models.py: from __future__ import unicode_literals import datetime from mongoengine import Document, connect, EmbeddedDocument, fields, DynamicDocument from django.db import models # Create your models here. from mongoengine import signals connect('yourdb', alias='default') class GPS(EmbeddedDocument): lat = fields.FloatField(null=False, required=True) lon = fields.FloatField(null=False, required=True) class PPM(EmbeddedDocument): time = fields.DateTimeField(default=datetime.datetime.now()) value = fields.IntField(null=False, required=True) @classmethod def pre_save(cls, sender, document, **kwargs): document.time = datetime.datetime.now() signals.pre_save.connect(PPM.pre_save, sender=PPM) class BuyHistory(EmbeddedDocument): time = fields.DateTimeField(default=datetime.datetime.now()) boxid = fields.StringField(max_length=128, null=False, required=True) username = fields.StringField(max_length=128, null=False, required=True) product = fields.StringField(max_length=128, null=False, required=True) amount = fields.IntField() @classmethod def pre_save(cls, sender, document, **kwargs): document.time = datetime.datetime.now() signals.pre_save.connect(BuyHistory.pre_save, sender=BuyHistory) class RecycleHistory(EmbeddedDocument): time = fields.DateTimeField(default=datetime.datetime.now()) boxid = fields.StringField(max_length=128, null=False, required=True) username = fields.StringField(max_length=128, null=False, required=True) amount = fields.IntField() @classmethod def pre_save(cls, … -
Django Forms - Is there any way to save data to a separate model from a form?
If I'm working with the form.clean() method for a simple formset, and I'm using input values to pull data from its associated models, how do I save that data to a separate model class, that's not defined by the formset? Code: #forms.py class SlotInlineFormSet(BaseInlineFormSet): def clean(self): super(SlotInlineFormSet, self).clean() y = self.cleaned_data print(y) # Access each form one at a time for idx, form in enumerate(self.forms): form_data = form.cleaned_data print('idx: ' + str(idx+1)) #Pull Necessary Port Variables port_type = (form_data['installed_card'].default_port_type) max_ports = (form_data['installed_card'].max_port_num) port_start_num = (form_data['installed_card'].port_start_num) port_naming = (form_data['installed_card'].port_naming) #Save Ports to Port model #??? #views.py def manage_slots(request, node_id): node = Node.objects.get(pk=node_id) max_slots = node.chassis.num_slots SlotFormSet = inlineformset_factory(Node, Slot, max_num=max_slots, extra = max_slots-node.slot_set.count(), can_order = False, fields=('installed_card', ), can_delete=False, formset = SlotInlineFormSet) if request.method == "POST": formset = SlotFormSet(request.POST, request.FILES, instance=node) if formset.is_valid(): forms = formset.save(commit=False) ### Save form slot number as an enumeration ### formset.save() messages.success(request, "Slot details saved!") return redirect("appDB:apphome") else: formset = SlotFormSet(instance=node) return render(request, 'forms/manage_slots.html', {'formset': formset}) #models.py - Port class to save to class Port(models.Model): slot = models.ForeignKey(Slot) port_num = models.PositiveSmallIntegerField() port_type = models.ForeignKey(PortDef) class Meta: unique_together = ("slot", "port_num") def __str__(self): if self.slot.sub_slot_num is None: return u'%s - Port: %s%s/%s' % (self.slot.node, self.slot.installed_card.port_naming, self.slot.slot_num, self.port_num) … -
How do I get click event of modal form button?
On my django web app, I have a webpage and when a button is clicked a modal form is opened. On this form there are a few fields and a save button. When the save button is pressed, I want to do something, like printing an alert. Here is what I tried: Modal form code: <div class="container-content"> <div class="infor-experience col-lg-2 more_info"> {% if request.user|isEmployer %} <div class="add-to-list">{% include "layout/addtolistmodal.html" %}</div> <div class="connect-now bottom">{% include "layout/bidmodal.html" %}</div> {% endif %} <!-- more code below here --> Javascript block in same HTML file as modal above: <script type="text/javascript"> // Add to short list handler $('.add-to-list').on('click', '.submit', function(e) { alert("TEST"); }) </script> Basically, what I want to do is when the user clicks save on the add-to-list modal, print the alert "TEST". From my understanding the reason its not working is because it cannot find '.add-to-list' but what I should use instead? Thanks! -
How to customize django auth decorator with urls.py?
I have several urls defined: url(r'^board/$', TemplateView.as_view(template_name='recruit/board.html'), name='recruit_board'), url(r'^job/$', login_required(TemplateView.as_view(template_name='recruit/job_detail.html')), name='job_detail'), url(r'^company/$', login_required(TemplateView.as_view(template_name='recruit/company_detail.html')), name='company_detail'), ... and users I designed have two account types: A or B. The "job" url can only be accessed by users with an A account type, and the "company" url can only be viewed by B account type users. If users try to access a wrong url, it will be redirected to the "board" url. I have used the login_required decorator, and I know about user_passes_test, but I don't know how to go on from here. Can I write a new decorator that works just like login_required and get what I want? -
modifying `builtins` while splitting a django settings file
I'm starting a django project and would like to split the settings file. I was unsatisfied with any existing solutions. I do not want to be able to override string settings from one file in another. Each string setting should be set in only one place. This makes it easy to keep track of where things are defined. I do not want to have to manually extend tuple/list settings, e.g. INSTALLED_APPS += (test_app). This seems to be messy and requires me to keep track of whether a list or tuple was used in the other file. I do not want to have to import os and define BASE_DIR in multiple files. DRY. My solution, having looked at many others, is to replace settings.py with a directory containing local_settings.py, common_settings.py and __init__.py. In __init__.py, I have import os and calculate BASE_DIR. I then import builtins builtins.BASE_DIR = BASE_DIR builtins.os = os from .common_settings import * from . import local_settings # At this point both modules have run and we no longer need to be messing # with the builtins namespace. del builtins.BASE_DIR del builtins.os del builtins I then loop over dir(local_settings) and mess with globals() to achieve the first two requirements … -
Why gunicorn service file is named sshd.services at digitalocean?
I am following this tutorial and migrating my django app from sqllite and my local dev serever under windows to cloud hosting with postgres and gunicorn on ubuntu. I am using digitalocean droplet https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I was able to migrate the database and to run the gunicorn but I am confused at this step We'll then map out the working directory and specify the command to use to start the service. In this case, we'll have to specify the full path to the Gunicorn executable, which is installed within our virtual environment. We will bind it to a Unix socket within the project directory since Nginx is installed on the same computer. This is safer and faster than using a network port. We can also specify any optional Gunicorn tweaks here. For example, we specified 3 worker processes in this case:/etc/systemd/system/gunicorn.service But my file located under this path is named sshd.services and under the Services part it already has content [Service] EnvironmentFile=-/etc/default/ssh ExecStart=/usr/sbin/sshd -D $SSHD_OPTS ExecReload=/bin/kill -HUP $MAINPID KillMode=process Restart=on-failure so I am a bit puzzled how should I proceed in this case? -
Blank URL pattern in Django
I've inherited a Django app and have noticed urlpatterns += patterns('') and equivalent throughout urls.py. e.g. urlpatterns = patterns( '', url(r'^index.html', render_index), ) #... urlpatterns += patterns( '', url(r'^page.html', another_controller), ) What is this doing? Anything? -
Django: how to get the latest rows for each item?
My issue is similar to this question: How to select only the latest rows for each user? But I am implementing this with Django. In the following example (which I borrowed from the question above), I need to extract only the last row for each user. Additionally, in my case, I only want to get rows for a particular list of user_ids. id | user_id | period_id | completed_on ---------------------------------------- 1 | 1 | 1 | 2010-01-01 2 | 2 | 1 | 2010-01-10 3 | 3 | 1 | 2010-01-13 4 | 1 | 2 | 2011-01-01 5 | 2 | 2 | 2011-01-03 6 | 2 | 3 | 2012-01-13 ... | ... | ... | ... If the user_list is [1, 2], I'd like to get a result like this: id | user_id | period_id | completed_on ---------------------------------------- 4 | 1 | 2 | 2011-01-01 6 | 2 | 3 | 2012-01-13 I was writing it using filter, but couldn't figure out the right way. PeriodTable.objects.filter(user__in=user_list, period_id=max(....?)).values(...) -
Django HTTP 404 error when PUT or GET
I am simply trying to GET or PUT to my Django api. It all compiles fine but everytime I try to PUT or GET through the web interface i get the following messsage: HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } I very new to Django and I am not sure where I went wrong, here is my views.py file: from django.shortcuts import render from rest_framework import viewsets from rest_framework import permissions from SecMeRe.models import Patient from SecMeRe.serializers import PatientSerializer # Create your views here. class PatientViewSet(viewsets.ModelViewSet): queryset = Patient.objects.all() serializer_class = PatientSerializer My modesl.py from __future__ import unicode_literals from django.db import models import uuid class Patient(models.Model): firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) dob = models.DateField() firstRecorded = models.DateField() uniqueHash = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) and my serializers.py from SecMeRe.models import Patient from rest_framework import serializers class PatientSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Patient fields = ('firstName', 'lastName', 'dob', 'firstRecorded', 'uniqueHash') -
Display last page of paginated results instead of 404 using ListView
The Django docs show how to return the last page of a paginated queryset using a function-based view by catching the EmptyPage exception. What's the easiest way to achieve the same thing using generic class-based views, for example ListView? I first thought that the allow_empty setting for MultipleObjectMixin would do what I need, but examining the code shows that it only prevents a 404 error if there are zero objects in the queryset, rather than zero objects on the page requested. Two options seem to be: subclass ListView and override paginate_queryset (inherited from MultipleObjectMixin), or subclass Paginator and override validate_number, and set paginator_class to the subclass in the view. Is there a better way to achieve this? -
Get list index on form submission in Django
I have a form where a user can submit an arbitrary number of inputs, which I have setup using jquery. <form method="post" action="{% url 'review:submit_review' %}"> <ol id="bibliography"> <li><input type="url" name="references"></li> </ol> <button name="add-reference">+</button> <button name="remove-reference">-</button> <button type="submit">Submit</button> </form> $("button[name='add-reference']").click( function (e) { e.preventDefault(); $("#bibliography").append('<li><input type="url" name="references">'); }) $("button[name='remove-reference']").click( function (e) { e.preventDefault(); $("#bibliography input[name='references']").last().parent().remove() }) I would like to have it, so that when the form is submitted, I know the index number of the input field. i.e. For a given reference what was its list number. Is there a way to do this? -
How to execute multiple Selenium functions on the same webpage with Django?
I started a Django project that uses Selenium, but I'm stuck since few days on a little problem (By the way, I'm a novice in Python, Django and Selenium...). I'm creating a website (with Django) that asks a user to fill in a form and then, automatically fill in a similar forms and navigating between pages on other websites (using Selenium). So far, I succeed to code in my view a function using Selenium to automatically open Firefox, get on an external website page, and fill in a form. But my problem is: When I execute a second function in my view, it automatically open a new Firefox application with a white page. But I want that function to be executed from the opened page (where the first function stopped). Anyone can help me please? Here is my code (the names are simplified): VIEW : @login_required def login(request): browser = webdriver.Firefox() browser.get('https://otherwebsite.com') ID_otherwebsite = ID_mywebsite.objects.get(user__username=request.user.username) field_username = browser.find_element_by_id("dialogTemplate-dialogForm-login-name1") field_username.send_keys(ID_otherwebsite.username) field_password = browser.find_element_by_id("dialogTemplate-dialogForm-login-password") field_password.send_keys(ID_otherwebsite.password) browser.find_element_by_id("dialogTemplate-dialogForm-login-defaultCmd").click() return render(request, 'main/logged_in.html') @login_required def get_main_page(request): browser = webdriver.Firefox() browser.find_element_by_id("main-page-button").click() return render(request, 'main/main_page_reached.html') MODEL: class ID_mywebsite(models.Model): user = models.OneToOneField(User) username = models.CharField(max_length=100) password = models.CharField(max_length=100) def __str__(self): return "ID_mywebsite of {0}".format(self.user.username) To be precise, I use: … -
Django Model and View Output
I'm kinda stuck in a situation. I have 1 model class and I kinda want it's out put to be both photo and story combined. Like the page should be photo-story-photo-story. But I can only make it give one(photo or story) How am I supposed to combine them two? I use django & bootstrap.And also the photo only stores urls' how can i turn them into images on the web page? class Blog(models.Model): photo = models.CharField(max_length=200, unique=True) story = models.TextField(unique=True) pub_date = models.DateTimeField('date published', default=datetime.datetime.now) and my View is: def index(request): posts = Blog.objects.order_by('-pub_date').reverse() return HttpResponse(posts) -
How to properly set a "go to the next-post" and "go to the previous-post" in a blog like app?
I have been looking around for an answer to the question that gives the name to this post, and I gotta say I found several, but they gave me only a fraction of the answer each. I am fairly new to the Django world, so I find myself at the point where linking all the pieces together is extremely difficult. So far I understood that if I have written a model that includes a date-time field, I can use the "get_next_by_FOO" method, where FOO is the date-time field I have been using in the Model. I also understood that I might need to change my views.py accordingly, and the urls as a consequence. So good so far, but how do I do all of this? I am using "DetailView" to render every single page of the "blog-like" APP. I understood I might have to write a child class of DetailView in views.py.. but how? and what should I add? My Blog-like app is called NEWS. Here is my code(I am posting only the parts where I think I need help). A huge thanks you to everybody willing to help me grow on the subject. models.py from django.db import models class … -
Django 1.10 - how-to: Many-to-Many horizontal interface
As in this old post, I would like to get in my own template the same horizontal interface as you get in the admin pages with class MyModelAdmin(admin.ModelAdmin): filter_horizontal = ('MyM2M',) I understand that I have to use the FilteredSelectMultiple widget. However the given example there seems to be outdated. What are the necessary js/css for django 1.10, jquery 2.2.4? Is there a better way? -
Django name patterns is not defined in ulrs.py
I am trying to set up a Django app, but everytime I try to run it i get the following error message: NameError: name 'patterns' is not defined I do not understand what is wrong with my urls.py file, here is a copy of it: from django.contrib import admin from rest_framework import routers from SecMeRe import views router = routers.DefaultRouter() #makes sure that the API endpoints work router.register(r'api/SecMeRe', views.PatientViewSet) admin.autodiscover() urlpatterns = patterns( url(r'^admin/', include(admin.site.urls)), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ) -
django save data to session without increasing its expiry
Basically I want to do something like: request.session['last_date'] = datetime.datetime.now() without django modify (increase) session expire_date (i.e, it should stay as it is) I have SESSION_SAVE_EVERY_REQUEST = True -
How to iteratively get all field names for a given django model and all its ForeignKey fields
I am using Django 1.10 I have the following django models. class Primer(models.Model): name = models.CharField(max_length=256) synonym = models.CharField(max_length=256) locus = models.ForeignKey(Locus,null=True,blank=True) class Locus(models.Model): locusname = models.CharField(max_length=256,blank=True) organism = models.CharField(max_length=16,default="human") genomic_coordinate_start = models.IntegerField() genomic_coordinate_stop = models.IntegerField() genome_build=models.CharField(max_length=60,default="hg38") common_name = models.CharField(max_length=256,null=True,blank=True) I know I can get the "Primer" model attributes and the foreign key relationships in the "Primer" model using code below from django.db.models import ForeignKey primer_attributes_non_foreign = [str(x) for x in Primer._meta.fields if not isinstance(x,ForeignKey) ] primer_relationships_foreign = [x for x in Primer._meta.fields if isinstance(x,ForeignKey) ] To get all ForeignKey Models and their fields I am using the related model statement. import itertools foreign_key_fields = [str(z) for z in itertools.chain.from_iterable(\ [fk_model._meta.fields for fk_model in [rel_to_primer.related_model for rel_to_primer in Primer._meta.fields if isinstance(rel_to_primer,ForeignKey)]])] Is there a better way to dynamically burrow down and get all fields for a given django model ? Eventually , I want to create a csv upload form that will accept an arbitrarily formatted csv input table and then allow the user to associate columns with all model attributes and their foreign-key attributes to "register" the "Primer" objects which are in rows. -
Does Django-cache-machine prevent/break usage of WSGI/Gunicorn?
I have my existing Django application running locally on my MacBook. It's directory structure looks something like this: myproject/ mySite/ __init__.py settings.py urls.py wsgi.py myApp1/ __init__.py models.py views.py manage.py requirements.txt Up until now, I have been using the Django toy webserver to run my app: ./manage.py runserver 0.0.0.0:80. But now I want to use gunicorn instead. So I'm following the instructions here. I do source myVirtualenv/bin/activate && cd myproject && gunicorn KingkajouSite.wsgi. I get the following error: File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "myproject/MyApp2/models.py", line 11, in <module> from caching.base import CachingManager, CachingMixin ImportError: No module named caching.base Why? Am I doing something wrong? Does Django-Cache-Machine not work with Gunicorn/WSGI? How to work around this issue? -
Display Local Images in Django App
Is it possible to display images that are stored locally on a django app? I am currently building a workflow that integrates with a web service, and I have dynamically analyzed data that the user uploads which is then processed locally and saved locally (ie, not in the static directories). I am currently just trying to build something minimally viable before making it "formally correct" (I know I'm supposed to store the images I want displayed in the static directory, but as they aren't static, this doesn't make much sense to me since users can upload and delete their processed data so it's not always necessarily going to be there; the workflow is presently external the web service so integrating them is something I'm hoping to get to after having a product working since the integration itself will probably take several months and I need something minimally working before that for a demo). I have the images I want to display stored locally, and when generating templated HTML's the paths I expect are actually showing up (ie, when browsing and viewing the HTML, the path that is shown is the path the images are locally on my computer) however, Django …