Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a Second URL Pattern in Django Causes Attribute Error
This is related to Django: 'module' object has no attribute 'index'. I have very similar files to that poster, and have been following the same first django tutorial. Here's my project/urls.py. A slight modification causes it to fail. from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), #url(r'^redis/', include('redis.urls')), url(r'^admin/', admin.site.urls), ] Uncommenting that line causes this error: Exception Type: AttributeError Exception Value: 'module' object has no attribute 'index' If I leave this file as is, going to /polls/ in my webbrowser works fine, so do I just need to do something different with namespaces? -
Django:Cannot update instance, make new instance
I'd like to update existed instance by using form, however my code made new instance. I referred this question views.py def update(request, id): user = request.user invoice = Invoice.objects.get(id=id) form = InvoiceForm(request.POST or None, instance=invoice) products = user.products.all() if form.is_valid(): form.save() return redirect('/invoice') return render(request, 'invoice/create.html', {'form': form, 'products':products}) create.html ~~~ <div> <select> {% for product in products %} <option value="{{ product.id }}">{{ product.name}}</option> <div class="error">{{ form.product.id.errors }}</div> {% endfor %} </select> </div> <div> <label for="invoice_no">INOVICE NO:</label> {{ form.invoice_no }} <div class="error">{{ form.invoice_no.errors }}</div> </div> ~~~ urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name="invoice"), url(r'^show/(?P<id>\w+)/', views.show, name='invoice_show'), url(r'^create/', views.create, name="invoice_create"), url(r'^update/(?P<id>\w+)/', views.update, name="invoice_update"), url(r'^destroy/(?P<id>\w+)/', views.destroy, name="invoice_destroy"), url(r'^pdf/(?P<id>\w+)/$', views.create_pdf, name='invoice_output_pdf'), ] -
django not serving angular js files
i am trying to use django with angular js but it throws error while trying to include the angular js files {% load staticfiles %} <html ng-app> <head> <script type="text/javascript" src="{% static 'js/libs/angular.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/modules/app.module.js' %}"></script> <script type="text/javascript" src="{% static 'js/modules/app.config.js' %}"></script> <script type="text/javascript" src="{% static 'js/modules/blog-list.module.js' %}"></script> <script type="text/javascript" src="{% static 'js/controllers/blog-list.js' %}"></script> </head> <body> <input type="text" ng-model="name"> <p>hi , {{name}}</p> <div ng-controller="BlogListController"> <h1>{{title}}</h1> <button ng-click="someTest()">click</button> </div> </body> </html> How can i server angular js files .Thanks in advance -
Django: can't store variable in self.xxx in Generic View?
views.py class MyView(View): def get(self, request, *args, **kwargs): self.foo = "hi" def post(self, request, *args, **kwargs): print(self.foo) GET request works but POST request doesn't work. It occurs errors, AttributeError: 'MyView' object has no attribute 'foo' Can't I save variable in self.xxx in views.py? -
Downloaded videos with urllib and bs4 does not play
I have a folder online where I have video files so I need to download videos from there to my local system so in order to do that I am using Bs4 , urllib modules , The downloaded files are not playable Please have a look at my code . from bs4 import BeautifulSoup import urllib2 import random import urllib from urllib2 import urlopen def download(url): response = urllib.urlopen("http://ssdolutions/addadsfasdfulsdfaatadfae") doc = response.read() soup = BeautifulSoup(doc) for link in soup.find_all('a'): x = (link.get('href')) name = random.randrange(1,10) full_name = str(name) + ".mp4" urllib.urlretrieve(url, full_name) download("http://ssdolutions/addadsfasdfulsdfaatadfae") -
Which type of field in django is better to use for saving token code?
I am writing an app, that will work with Instagram. They use an OAuth 2.0 protocol. The question is: How to save access token for each user in secure way? What type of field to use? Or maybe there is a module for those purposes, because I saw only for old versions of Django. Many thanks -
Should I use 1st Generation or 2nd generation database for flexible environment?
In the tutorial https://cloud.google.com/python/django/flexible-environment they ask me to create a 1st generation database. In the README.md, they ask me to create a 2nd generation database. Neither seems to work. I get a: Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [13] Timed out when starting VMs. It's possible that the application code is unhealthy (0/2 ready, 2 still deploying). Browsing to the site gives me: OperationalError at / (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 38") Any suggestions? -
How to use a custom method in form to send request and accept response from another server in Django?
I have the following code in my forms.py file. class RegisterForm(forms.Form): employee_id = forms.CharField(label='Employee ID', max_length=30) password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Retype Password', widget=forms.PasswordInput) first_name = forms.CharField(label='First Name', max_length=100) last_name = forms.CharField(label='Last Name', max_length=100) designation = forms.CharField(max_length=100) department = forms.ChoiceField(choices=[(x, x) for x in departments]) mobile = forms.CharField(max_length=50) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2: if password1 != password2: raise forms.ValidationError(("The two password fields didn't match.")) elif password1 == '' or password2 == '': raise forms.ValidationError(("The password cannot be blank")) return password2 I have two queries. I understand how the code in the clean_password2 method works but I don't understand why that method is called clean_password2 and why does it not work if I remove the 2 from the name? I have a script in another server where I want to send a request with employee_id and get a response back whether that ID is available or it already exists. How do I create a method that would not let me submit the form in the ID is not available? Also, it would be highly helpful if someone provides me with reading material to get a solid grasp on Django Forms. -
How to change Django updateview date display format?
I using Django generic updateview when I edit a object I get and input with this format 2016-10-26 00:00:00 but I want to get 26/10/2016 -
Django TypeError: 'formas_pago' is an invalid keyword argument for this function
I'm trying to keep all the information in one json. If I delete the relationship "establecimientos" function does not throw any errors, but if I include "establecimientos" there throwing error. Models Class class Negocio(models.Model): nombre = models.CharField(max_length=255) slug = models.CharField(max_length=255) logo = models.FileField(upload_to=upload_logo_to) fecha_creado = models.DateTimeField(auto_now=True) propietario = models.ForeignKey(User) tipos_negocio = models.ManyToManyField('TipoNegocio') formas_pago = models.ManyToManyField('FormaPago') def __str__(self): return self.nombre def get_establecimiento(self): establecimientos = Establecimiento.objects.filter(negocio=self) return establecimientos class TipoNegocio(models.Model): tipo = models.CharField(max_length=255) def __str__(self): return self.tipo class Establecimiento(models.Model): nombre = models.CharField(max_length=255) direccion = models.TextField() telefono = models.CharField(max_length=255) negocio = models.ForeignKey('Negocio', related_name='establecimientos') def __str__(self): return u'{0} - {1}'.format(self.negocio, self.nombre) def get_horarios(self): horarios = Horario.objects.filter(establecimiento=self) return horarios class FormaPago(models.Model): forma_pago = models.CharField(max_length=255) def __str__(self): return self.forma_pago Serializer Class This is the serializadora class work correctly until this line (establecimientos_data = validated_data.pop('establecimientos')) class NegocioSerializer(ModelSerializer): establecimientos = EstablecimientoSerializer(many=True) class Meta: model = Negocio fields = ('id','nombre', 'slug', 'fecha_creado', 'tipos_negocio','formas_pago', 'propietario', 'establecimientos') read_only_fields = ('propietario',) def create(self, validated_data): establecimientos_data = validated_data.pop('establecimientos') negocio = Negocio.objects.create(**validated_data) for establecimiento_data in establecimientos_data: Establecimiento.objects.create(negocio=negocio, **establecimiento_data) return negocio JSON { "nombre": "nuevo", "slug": "nuev", "tipos_negocio": [ 2, 3 ], "formas_pago": [ 1 ], "establecimientos": [{ "nombre": "Matriz", "direccion": "asasasas", "telefono": "0997739485", "horarios": [] }, { "nombre": "bbb", "direccion": "sassdd", "telefono": "445588", "horarios": … -
Django: select a instance of a parent model at ModelForm
I'd like to select a instance of a parent model, product, at the create.html , then send the data to views.py . However, I cannot figure out how to do that. I've achieved to select product instance at create.html as following, but I am not sure how to send the data to views.py and save it. {% for product in products %} <option value="{{ product.id }}">{{ product.name}}</option> <div class="error">{{ form.product.id.errors }}</div> {% endfor %} create.html ~~~ <div> <select> {% for product in products %} <option value="{{ product.id }}">{{ product.name}}</option> <div class="error">{{ form.product.id.errors }}</div> {% endfor %} </select> </div> <div> <label for="invoice_no">INOVICE NO:</label> {{ form.invoice_no }} <div class="error">{{ form.invoice_no.errors }}</div> </div> ~~~ views.py from django.shortcuts import redirect, render from django.http import HttpResponse from .models import Invoice from account.models import User from .forms import InvoiceForm def index(request): d = { 'invoices' : Invoice.objects.all(), } return render(request, 'invoice/index.html', d) def create(request): user = request.user if request.method == 'POST': form = InvoiceForm(request.POST) if form.is_valid(): invoice = form.save(commit=False) invoice.user = user invoice.save() return redirect('/invoice') else: return redirect('/') else: products = user.products.all() form = InvoiceForm() return render(request, 'invoice/create.html', {'form': form, 'products':products}) models.py from django.db import models from account.models import User from product.models import Product class Invoice(models.Model): … -
Autofill a django form field based on input of another field with ajax
I don't have much experience with AJAX or jQuery. I want to collect a user's address when they register (address, city, state and zip). I have a Django Form that has fields for all four of these. The address field autopopualtes with valid US addresses via the Google Maps API and django-address (https://github.com/furious-luke/django-address). If I want to take this address and live fill say, the city field, how would I go about doing this? I've tried a million different solutions with no luck. models.py class user_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = AddressField() city = models.CharField(max_length=200) state = models.CharField(max_length=200) zip = models.CharField(max_length=200) forms.py from address.forms import AddressField from localflavor.us.us_states import US_STATES from localflavor.us.forms import USStateField from localflavor.us.forms import USStateSelect ... class ProfileForm(forms.ModelForm): address = AddressField() city = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'City'})) state = USStateField(widget=forms.Select(choices=US_STATES)) state = forms.CharField(widget=USStateSelect()) zip = forms.CharField(widget=forms.TextInput(attrs={'placeholder': ZIP code'})) class Meta: model = user_profile fields = ['address', 'city', 'state', 'zip'] template {% for field in profileform %} {{ profileform.media }} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <div class="col-sm-10">{{ field }}</div> </div> {% endfor %} {% csrf_token %} address.js $(function(){ $('input.address').each(function(){ var self = $(this); var cmps = $('#' + self.attr('name') + '_components'); var fmtd = … -
Django- using URL namespace to differentiate apps- "NoReverseMatch"
I'm doing my first Django project where, in a template from my 1st app, I wanna put up a link to a URL that is from a 2nd app I've added, which is: https://github.com/stephenmcd/django-forms-builder I had a problem with namespacing. I read Django's topic for this and several questions here, and followed a tip about adding a namespace. I did so now, my project root urls.py file is: //urls.py ... urlpatterns = [ url(r'^polls/', include('polls.urls', namespace='polls')), url(r'^admin/', admin.site.urls), url(r'^forms/', include(forms_builder.forms.urls, namespace='forms_builder')),] I'm trying, from a template belonging to my 1st app, "polls", to have a link with a URL that belongs to the other app, "forms", like this: <li><a href = "{%url 'forms_builder:form_detail' slug=form.slug %}">{{ form }}</a></li> Checking the page this generates in a specific situation, this matches the correct URL that i want to go to, and there are no namespace problems in this page that references the other! My real problem now is that when trying to open the other page, the one I reference, from the "forms_builder" app, I get the following error (where "my example" is a form I've created for testing purposes): NoReverseMatch at /forms/my-example/ Reverse for 'form_detail' with arguments '()' and keyword arguments '{u'slug': … -
Put model's id in hidden input in template
I would like to put a hidden input in my template containing my model's id. This is what I have: models.py: class MyModel(models.Model): name = models.CharField(max_length=10) class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['name'] widgets = { 'name': TextInput(), } index.html: {{ form.name.label_tag }} {{ form.name }} This works fine and displays a simple form with a text input. What I want to do is add a hidden input that contains the model's id. I tried: models.py: class MyModel(models.Model): name = models.CharField(max_length=10) class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['name', 'id'] widgets = { 'name': TextInput(), 'id': HiddenInput(), } index.html: {{ form.name.label_tag }} {{ form.name }} {{ form.id }} But it doesn't work. If possible I wanted to avoid manually doing this: index.html: {{ form.name.label_tag }} {{ form.name }} <input type="hidden" name="id" value="{{ form.instance.id }}"> Thanks! -
How do I make an html div element follow vertical scrolling (in html/django)?
I'm extremely inexperienced with html and although I know python, I had never used django before this. I'm trying to set up a simple website where the user can view some code on the left side of the screen and enter some text about it on the right side of the screen. The code can be pretty long sometimes so the webpage scrolls, but I want the textbox to always be present even if you scroll up or down. As my code is now, the textbox is on the right side of the screen, but it always stays at the bottom. Here's a screenshot of what it looks like: Here's the .html file I'm using in my templates directory in django: <div style="display: inline-block"> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <pre>{{ source_code }}<pre> </div> <div style ="display: inline-block" > <form method="post" action="/labeling/{{ document_id }}/send/"> {% csrf_token %} <input type="text" name="textfield"> <input type="submit" value="Finish" name="finish_btn" /> </form> </div> Sorry for my complete lack of html knowledge. How would I fix this either in django or in the html file directly so that the textbox and button move up and down with the scrolling, instead of being permanently attached to … -
how to curl datetimefield to django
How can I make a cURL-type request to my django app where the POST data includes a DateTimeField? models.py: from django.db import models from datetime import datetime class usageHistory(models.Model): fk_employee_number = models.BigIntegerField() fk_version = models.BigIntegerField() fk_instrument = models.BigIntegerField() timestamp = models.DateTimeField(auto_now=False, auto_now_add=False) forms.py: from django import forms from django.forms import ModelForm from .models import * class usageHistoryForm(ModelForm): class Meta: model = usageHistory fields = '__all__' def __init__(self, *args, **kwargs): super(usageHistory, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) I don't know what it wants in the field. perhaps YYYY-MM-DD HH:MM:SS? I really have no idea. I can find lots of helps online for serializing the DateTimeField, but not on how to feed info into it. I know the POST data is a string, so what's django expecting to receive? -
Receiving Errno 10053 (An established connection was aborted by the software in your host machine) on Ajax calls in Django
There's been pretty much of discussion on this topic, and still the peculiarity of my question is that I am using beforeSend, and I blame the error on my possibly incorrect usage of this operator. So I have this JS code: DATA_LIST_REQUEST = $.ajax( { type:'GET', url:"/ajax_refresh_order_suggestions/", beforeSend : function() { if(DATA_LIST_REQUEST != null) DATA_LIST_REQUEST.abort(); }, data:data, success: function(response) { refresh_zeon_data_table(response, $table); } }); And the respective Django view which has nothing special in its code, so I don't post it to keep the question concise (will provide it on request). The above code is called every time the user changes combobox. And sometimes - NOT ALWAYS - I get this unpleasant error: [Errno 10053] An established connection was aborted by the software in your host machine error which most interestingly does not lead to fatal error behaviour, I still receive an answer, but it takes me 8 or 9 seconds instead of otherwise instant response. Am I doing something wrong in the above-mentioned JS code ? Here's the full traceback Exception happened during processing of request from ('127.0.0.1', 61839) Traceback (most recent call last): File "C:\Python27\lib\SocketServer.py", line 599, in process_request_thread self.finish_request(request, client_address) File "C:\Python27\lib\SocketServer.py", line 334, in finish_request self.RequestHandlerClass(request, … -
trouble with nginx and django gunicorn socks setup
So I followed this tutorial (http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/) and everything went smoothly till the end when I erase the default config for mine in sites-available and sites-enabled the restart nginx. When I navigate to my site I get a "site cant be reached" error. I created the link for new config to sites-enabled from sites-available. supervisorctl says its running my gunicorn start script when I check the status. What I notice though is that at no point is gunicorn.sock created in the run directory. Am I supposed to create that? I tried that but to no avail. Can someone help -
Django: undefined template variable renders as context dump
Django 1.10.1 Template is using a mandatory 'title' context variable and an optional 'note' template variable. Rendering {{ title }} works fine, but rendering {{ note }} causes a full template context to be rendered (kind of debug view?) if note is not defined in the context. I would expect that is 'note' is not defined in the context it would render an empty string, and if defined renders the content of the variable. This is the settings.py context related to templates: DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth')], 'APP_DIRS': True, 'OPTIONS': { 'string_if_invalid': '', 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] These python modules are in the virtual environment: Babel==2.3.4 BulkSMS==0.3 cGraph==0.1 diff-match-patch==20121119 Django==1.10.1 django-allauth==0.27.0 django-bootstrap-ui==0.2.0 django-bootstrap3==7.0.1 django-crispy-forms==1.6.0 django-debug-toolbar==1.5 django-extensions==1.7.4 django-import-export==0.5.1 django-jinja==2.2.1 django-mailjet==0.2.0 django-phonenumber-field==1.1.0 django-tag-parser==2.1 django-utils==0.0.2 dominate==2.1.17 funcsigs==1.0.2 graphviz==0.5.1 Jinja2==2.8 mailjet-rest==1.2.2 MarkupSafe==0.23 mock==2.0.0 nose==1.3.7 oauthlib==2.0.0 pbr==1.10.0 phonenumberslite==7.7.2 pydot2==1.0.33 pygraphviz==1.3.1 pyparsing==2.1.10 python-clickatell==0.1.3 python-openid==2.2.5 pytz==2016.7 requests==2.11.1 requests-oauthlib==0.6.2 six==1.10.0 sqlparse==0.2.1 tablib==0.11.2 -
How to fetch data from LDAP to html textbox in Python - Django?
I am pretty new to Python and Django. Recently, I am doing a project which requires me to make a function to do two things. 1. fetch data from LDAP to display in html text-boxes by input proper user ID. 2. store all the information to local database(half from ldap and half by user input). Is there anyone can provide me a sample code to accomplish these functions? -
Python how to "borrow" docstring from another class?
Background I am using django-rest-swagger to display the API documentation, the official way for swagger is to use the docstring from the view. Purpose A lot of documentation as docstring are done in the Model class, so I would like to "borrow" the docstring from the Model class into the APIModelView class, without physically copying the docstring. Eg. class Model(models.Model): """ Very comprehensive docstring... """ field_1 = ... field_2 = ... class APIModelView(ModelView): """ <borrow from the model class> """ model = Model -
Django model methods don't autocomplete
I'm using PyCharm 2016.2.3 I'm new to Django and when typing this for example: list_of_people = Person.objects.order_by('name') It works fine but the autocomplete stops after 'Person'. I tried creating a Manager instance manually: class Person(models.Model): # ... people = models.Manager() list_of_people = Person.people.order_by('name') So it autocompletes 'people' but it still doesn't know anything after that. Any idea why that happens? -
How to pass Extra Context Into Django Rest Serializer from View
I'm using Django REST Framework to overide the get_serializer_context() method in my view class, below (view.py) so I can pass an extra context variable to my serializer below (serializer.py), but I'm receiving a null value when a view my API results in the browser. My results are below (result). Any help would be greatly appreciated. view.py class TaskListMixin(object): s1 = Schedule.objects.get(pk=1) r1 = Room.objects.get(pk=2) sp1 = r1.spacetype.pk s = Space.objects.get(pk = sp1) queryset = s.task.all() serializer_class = SimpleSerializer3 permission_classes = (permissions.IsAuthenticated,) class TaskListViewSet(TaskListMixin, generics.BulkModelViewSet): def get_serializer_context(self): context = super(TaskListViewSet, self).get_serializer_context() return {'request' : 'test'} serializer.py class SimpleSerializer3(BulkSerializerMixin, ModelSerializer): is_my_object = serializers.SerializerMethodField() def get_is_my_object(self, obj): test_me = self.context.get('request') class Meta(object): model = Task list_serializer_class = BulkListSerializer fields = ('pk','task_name', 'is_my_object') results [ { "pk": 1, "task_name": "Remove large debris from floor", "is_my_object": null }, { "pk": 2, "task_name": "Clean walls and horizontal surfaces", "is_my_object": null }, { "pk": 3, "task_name": "Clean touch points", "is_my_object": null }, { "pk": 4, "task_name": "Empty trash container", "is_my_object": null }, { "pk": 6, "task_name": "Spot clean desks/furniture", "is_my_object": null }, { "pk": 7, "task_name": "High/Low dust", "is_my_object": null } ] -
Django 1.10.2 manage.py runserver Not Found: /"/static/index.css"
I may be making a simple mistake but after several days of troubleshooting and iterating I cannot locate the source of my problem. Despite my best efforts Django refuses to load my static css file and spits out exactly the same error each time. The error is Not Found: /"/static/index.css" Here is my current code: APP_NAME/APP_NAME/index.html {% load staticfiles %} <link rel="stylesheet" type="text/css" href=“{% static 'index.css' %}”> APP_NAME/urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^APP_NAME/', include("APP_NAME.urls")), url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) APP_NAME/APP_NAME/urls.py from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r"^$", views.index, name = "index"), ] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) APP_NAME/APP_NAME/settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'APP_NAME.urls' STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "APP_NAME/static/") STATICFILES_DIR = [ os.path.join(BASE_DIR, "APP_NAME/static/") ] -
Django add management command without installing as app
I've created a package for use with django, the main feature of which is accessible through a management command. However, in order to make management commands accessible, django seems to insist on the package being listed as an app in INSTALLED_APPS in settings.py. This application is merely used as part of our build process while doing intergration testing. It does not even need to be installed on developer machines, let alone end up in our production environment. However, since it needs to be in settings.py's installed apps, it also spreads to requirements.txt, as it suddenly breaks builds wherever it is not installed. Is there a way to inject a management command without the package being installed as a full-blown app?