Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
BASE_DIR returning settings path and not project django 1.10
I am currently setting up my settings files for Django 1.10 as per Two Scoops For Django 1.8 preferred settings files set up. my base.py settings file is: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) the BASE_DIR is returning the following path: /Devs/projects/captain_log/src/cap_log my file tree: |--Virtual Env Folder |--src(django project)/ |--cap_log(django config)/ |--init.py |--urls.py |--wsgi.py |--settings/ |-- init.py |-- base.py (all settings located here) |-- development.py |-- production.py |-- etc. I am under the assumption that the BASE_DIR is supposed to return: /Devs/projects/captain_log/src/ I am asking because my STATIC_DIRS is also returning: /Devs/projects/captain_log/src/cap_log/static instead of: /Devs/projects/captain_log/src/static Can someone please advise to a solution or correction to what I am doing. It is also effecting template paths, collectstatic, Media Path, etc. -
Multiple instances of celerybeat for autoscaled django app on elasticbeanstalk
I am trying to figure out the best way to schedule tasks regularly, e.g. every day, in an autoscaling AWS ElasticBeanstalk environment. So far I have been using Celery + Celerybeat to schedule daily tasks, however, now that I want to have multiple Django servers running at the same time the current situation would lead to having multiple celerybeat instances running at the same time, causing the tasks to be duplicated. I have read about multiple solutions, but all of them seem to have issues that have not been solved: Using django cache + locking: not a good solution if you have a lot of scheduled tasks. Lots of unnecessary cache accesses and extra code for every task to avoid duplication. Using leader_only option with ebextensions: works initially, but failing or replacing of instance would lead to no celerybeat instance running and scheduled jobs not to be initiated. How to I use celery + celerybeat in a distributed ElasticBeanstalk environment without task duplication? How can I make sure that only one instance is running on one of the servers, but still make sure that in case the celerybeat instance fails a new celerybeat instance will be started? -
Python runs the commented-out code
I have a problem that sometimes docker-py returns an error Permission denied. Trying to fix it, I commented out the piece of code, and received the following picture. File "/opt/dst/src/utils/runner.py", line 48, in run_code #if len(cli.containers(filters={'status': ['running', 'created']})) >= settings.DOCKER_CONTAINER_COUNT: Traceback (most recent call last): File "/opt/dst/env/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/opt/dst/src/core/tasks.py", line 12, in run return 'Solution not found' File "/opt/dst/src/utils/runner.py", line 48, in run_code #if len(cli.containers(filters={'status': ['running', 'created']})) >= settings.DOCKER_CONTAINER_COUNT: File "/opt/dst/env/lib/python2.7/site-packages/docker/api/container.py", line 85, in containers res = self._result(self._get(u, params=params), True) File "/opt/dst/env/lib/python2.7/site-packages/docker/utils/decorators.py", line 47, in inner return f(self, *args, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/docker/client.py", line 132, in _get return self.get(url, **self._set_request_timeout(kwargs)) File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 487, in get return self.request('GET', url, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 585, in send r = adapter.send(request, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/requests/adapters.py", line 453, in send raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', error(13, 'Permission denied')) The runner.pyc file is updated. What could be the problem? Thank you for your help and sorry for my bad english -
How to format django generated sitemap lastmod date?
As django docs says, lastmod returns datetime. It renders sitemap.xml lastmod to 'yyyy-mm-dd' format. But how could I change lastmod format to ISO8601 (I need exactly this: 2008-01-02T10:30:00.000123+02:00). I've played around making custom 'formats' path as said here (Django format localization) but did not found which setting should I change to get appropriate date format. -
Django model formset factory and forms
I'm trying to user Django model formset factory to render a template where a user can add images and change the images they have uploaded(very similar to what can be done in the admin). I currently can render the template and its correct fields to the template. What I cannot do is have the user preselected(want currently logged in) and when I refresh the page the image will be posted again(not sure if this is preventable). Below is my code. Thanks! Model: class Image(models.Model): user = models.ForeignKey(User) image = models.ImageField(upload_to=content_file_name, null=True, blank=True) link = models.CharField(max_length=256, blank=True) Form: class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Image fields = ('image', 'link', ) View: @login_required def register(request): user_data = User.objects.get(id=request.user.id) ImageFormSet = modelformset_factory(Image, fields=('user', 'image', 'link'), extra=3) if request.method == 'POST': print '1' formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.all()) if formset.is_valid(): formset.user = request.user formset.save() return render(request, 'portal/register.html', {'formset': formset, 'user_data': user_data}) else: print '2' formset = ImageFormSet(queryset=Image.objects.all()) return render(request, 'portal/register.html', {'formset': formset, 'user_data': user_data}) Template: <form id="" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} <input type="submit" name="submit" value="Submit" /> -
save() prohibited to prevent data loss after setting foreign key to null
I've searched for this error but all the questions I've seen discuss creation of a new object. My problem is that I need to make two updates to the same object. One is to call delete() on the Override foreign key, with the on_delete=models.SET_NULL, and then immediately after to update the fee value and call save(). I've tried this in a transaction.atomic block, tried nested transactions, and tried removing the transaction entirely. No matter what I get this same error. My models: class FeeCalculationMixin(models.Model): fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.0) override = models.ForeignKey('Override', null=True, on_delete=models.SET_NULL) class Override(models.Model): fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.0) forgive_interest = models.BooleanField(default=False) overridden_by = models.ForeignKey(User, related_name='User_that_created_override', related_query_name='override_created_by_user)') override_fee = models.BooleanField(default=False) date_overriden = models.DateField(auto_now_add=True) repeat = models.BooleanField(default=False) reason = models.CharField(max_length=250) def __str__(self): return 'Override - ' + self.date_overriden.strftime('%b %d, %Y') class LicenseAreaFeeYear(InterestCalculationMixin, FeeCalculationMixin): license_area = models.ForeignKey('LicenseArea', related_name='licensearea_for_licenseareafeeyear', related_query_name='licenseareafeeyears_for_licensearea', null=False) license_year = models.ForeignKey('LicenseYear', related_name='licenseyear_for_licenseareafeeyear', related_query_name='licenseareafeeyears_for_licenseyear', null=False) value_per_sq_ft = models.DecimalField(max_digits=10, decimal_places=4, null=True) The view, for each LicenseAreaFeeYear: l.override.delete() l.calculate_fee() in which calculate_fee() calls l.save() after calculating the fee. The database shows that the foreign key value is null and the Override object/row has been deleted from the database, but I cannot save the LicenseAreaFeeYear object. Any help will be appreciated! -
django contact page send_email
I am trying to create a contact page which will take 17 inputs from a visitor and then email that information to me. I found many basic tutorials but none specific to what I am trying to achieve. So far this is what I have: I created a new Django project "contactform" then a new app "send_email" this is my forms.py file located- send_email/forms.py from django import forms class ContactForm(forms.Form): title = forms.CharField(max_length=3, required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) identity_type = forms.CharField(required=True) identity_number = forms.IntegerField(required=True) current_job = forms.CharField(required=True) career_prospects = forms.CharField(required=True) age = forms.IntegerField(required=True) nationality = forms.CharField(required=True) address = forms.CharField(required=True) city = forms.CharField(required=True) province = forms.CharField(required=True) postal_code = forms.IntegerField(required=True) contact_number = forms.IntegerField(required=True) daytime_contact_number = forms.IntegerField(required=True) evening_contact_number = forms.IntegerField(required=True) email_address = forms.EmailField(required=True) My views.py file located- send_email/views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] identity_type = form.cleaned_data['identity_type'] identity_number = form.cleaned_data['identity_number'] current_job = form.cleaned_data['current_job'] career_prospects = form.cleaned_data['career_prospects'] age = form.cleaned_data['age'] nationality = form.cleaned_data['nationality'] address = form.cleaned_data['address'] city = form.cleaned_data['city'] province = form.cleaned_data['province'] postal_code = form.cleaned_data['postal_code'] … -
Django AWS Elastic-Beanstalk WSGI.py configuration
I am currently setting up a django application with python3 on AWS Elastic-Beanstalk, but I am having issues with configuring the wsgi.py file for the application. Why am I having the error: ERROR: Your WSGIPath refers to a file that does not exist.? When running eb config I set the wsgi path to WSGIPath: pronet/pronet/src/pronet/wsgi.py Is the issue with my wsgi.py script, eb config wsgi settings, or not having the django module installed? WSGI.py Script """ WSGI config for pronet project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pronet.settings.production") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Wrap werkzeug debugger if DEBUG is on from django.conf import settings if settings.DEBUG: try: import django.views.debug import six from werkzeug.debug import DebuggedApplication def null_technical_500_response(request, exc_type, exc_value, tb): six.reraise(exc_type, exc_value, tb) django.views.debug.technical_500_response = null_technical_500_response application = DebuggedApplication(application, evalex=True, # Turning off pin security as DEBUG is True pin_security=False) except ImportError: pass ElasticbeanStalk eb logs output file [Tue Oct 18 18:59:52.882790 2016] [:error] [pid 25763] [remote 172.31.5.99:148] mod_wsgi (pid=25763): Exception occurred processing WSGI script '/opt/python/current/app/pronet/src/pronet/wsgi.py'. [Tue Oct 18 20:01:21.096064 2016] [:error] [pid 25763] [remote 172.31.46.245:148] ImportError: No module named … -
OS shows that TemporaryUploadedFile does not exist anymore but somehow this uploaded file can be read
I have the following situation here. My OS shows that TemporaryUploadedFile which I got via the POST request does not exist anymore but somehow this uploaded file can be read. Here is the code text_file = request.FILES['text_file'] print(text_file.temporary_file_path()) os.system('ls -l ' + text_file.temporary_file_path()) fs = FileSystemStorage() file_new =fs.save(text_file.name, text_file) print(text_file.temporary_file_path()) os.system('ls -l ' + text_file.temporary_file_path()) fs.delete(file_new) for chunk in text_file.chunks(): text += chunk.decode(encoding) print('Got text OK.') This gives the following output: /tmp/tmp0tngal9t.upload foo.txt -rw------- 1 mine machine 3072889 oct 18 19:29 /tmp/tmp0tngal9t.upload /tmp/tmp0tngal9t.upload foo.txt ls: cannot access '/tmp/tmp0tngal9t.upload': No such file or directory Got text OK. So TemporaryUploadedFile is disappeared after it was saved to file_new which later is also deleted. Anyway text_file is successfully read by chunks and I get all the text from uploaded foo.txt file. How it is possible? From where text_file.chunks() gets the data if text_file does not exist anymore? -
Crispy Layout: Submit button loops back to same page
I started using crispy layouts so I could add a checkbox so it can hide/show password field. The issue that I am having is that every time the form is submitted, it takes me back to the same page instead to accounts. It used to work fine before implementing crispy layout but now I doesn't. This is what I have in its form.py: from crispy_forms.bootstrap import StrictButton, FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, HTML, Field from django import forms from producer.models import LibsynConfig class LibsynAccountForm(forms.ModelForm): # user can not change podcast name here, is just provided as reference podcast_name = forms.CharField(label='Podcast Name', required=False, max_length=100, disabled=True) podcast_id = forms.IntegerField(widget=forms.Field.hidden_widget) # Libsyn Config data libsyn_config_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False) show_slug = forms.CharField(label='Show Slug in Libsyn', max_length=100, required=True) server_directory = forms.ChoiceField(choices=LibsynConfig.SERVER_DIRECTORY_TYPES) # credetials data user_name = forms.CharField(label='Username', required=True) password = forms.CharField(label='Password', required=True) check_box = forms.BooleanField(label='Show/Hide Password') def __init__(self, *args, **kwargs): super(LibsynAccountForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Div( Div( Div( Div( HTML('<h2>Libsyn</h2><p><h3>Choose an Account</h3><hr>'), 'podcast_name', 'show_slug', 'server_directory', 'user_name', Field('password', id='pw', type='password'), Field('check_box', id='box', onclick ='reveal()'), HTML('<hr>'), FormActions( StrictButton('<i class="fa fa-check pull-right" aria-hidden="true"></i> Finish', name="save", value="save", type='submit', css_class="btn btn-primary box-shadow--6dp"), ), css_class='col-sm-12' ), css_class='row' ), css_class='panel-body' ), css_class='panel panel-default … -
Barcode Input with Django Application
Any resources out there with code examples that explain how to configure and use a Django 1.9 web application to accept barcode input? -
How can I create a download handler to process api GET requests?
I'm writing a website in Django with python 3.4, with Django-restframework for an API. My API works great and I can download a stored file using the GET request. I need to shift my processing from end computer to server now and I'm not sure how to do it. So basically When I send my api a GET requeset, I would like to have the file processed based on information passed in. For example, I would like to pass two variables (Printer, Plastic) and based on that process with specific files on my server and output a more specific file. Am I correct in thinking I can call some sort of custom GET functions (like an upload handler) if I pass in variables, or is there a better way to solve this? -
rq error on heroku rq.exceptions.UnpickleError: ('Could not unpickle', AppRegistryNotReady("Models aren't loaded yet.",))
I'm trying to pass a function to the worker on heroku, but got an error message below. Can anyone help me resolve this error? Thanks in advance! I'm using django 1.10.2 and python 3.5.2 rq.exceptions.UnpickleError: ('Could not unpickle', AppRegistryNotReady("Models aren't loaded yet.",)) My worker.py is in the same folder as manage.py. import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") import redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() Here is the main.py function related to the worker: from myapp.models import Mymodel ...... myobject = Mymodel() queue = Queue(connection = conn) # heroku worker result = queue.enqueue(myfunction, myobject) ...... Myfunction is defined in utility.py: from myapp.models import Mymodel def myfunction(myobject): ...... The model_object is the model object. -
Django -- Form Field on change
I'm using Django forms to display data. There is a HTML select field - which has 2 options a) teachers and b) Students. Django forms:- self.fields['account_type'].choices = [('student','Student'),('teacher', 'Teacher')] self.helper.layout = Layout( HTML('''<h5>Sign Up Information</h5>'''), Div( Field('account_type', placeholder="Account Type", css_class='form-control'), css_class = 'form-group' ), Based on whether you select "Student" or "Teacher" you need auto populate another field - topics. How can I fire the 'onchange' event in Django forms. -
Django "module 'portal.views' has no attribute 'MyAccount'"
I just made another class based view in Django and it apparently isn't being imported in urls.py, which is confusing. I even simplified it by making the view just a def. views.py: from django.shortcuts import render from django.views import generic from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.contrib.auth.models import User from .models import RxgAsset # Create your views here. def index(request): return render(request, 'index.html') @method_decorator(login_required, name='dispatch') class GregAssets(generic.ListView): template_name = 'greg_assets.html' context_object_name = 'greg_assets' def get_queryset(self): if self.request.user.is_superuser: return GregAsset.objects.order_by('id') else: return GregAsset.objects \ .filter(organization=self.request.user.employee.organization) \ .order_by('id') class GregShowAsset(generic.DetailView): model = GregAsset template_name = 'greg_show_asset.html' context_object_name = 'greg_asset' def get_object(self, queryset=None): asset = GregAsset.objects.get(id=self.kwargs['pk']) if self.request.user.is_superuser: return asset else: if self.request.user.employee.organization == asset.organization: return asset else: return None def MyProfile(request): return render(request, 'index.html') urls.py: from django.conf.urls import url from portal import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^rxg_assets/$', views.RxgAssets.as_view(), name='rxg_assets'), url(r'^rxg_assets/(?P<pk>[0-9]+)/$', views.RxgShowAsset.as_view(), name='rxg_show_asset'), url(r'^my_account/$', views.MyAccount.as_view(), name='my_account'), ] Output: AttributeError at /portal/my_account/ module 'portal.views' has no attribute 'MyAccount' Request Method: GET Request URL: https://www.website.com/portal/my_account/ Django Version: 1.10.2 Exception Type: AttributeError Exception Value: module 'portal.views' has no attribute 'MyAccount' Exception Location: /server/apache/partner/portal/urls.py in <module>, line 8 Python Executable: Python Version: 3.5.2 Python Path: ['/server/apache/partner', '/server/apache/partner-env/lib/python3.5/site-packages', '/usr/local/lib/python35.zip', '/usr/local/lib/python3.5', '/usr/local/lib/python3.5/plat-freebsd11', '/usr/local/lib/python3.5/lib-dynload', … -
Django Amazon aws readonly database error
I have developed a Django project on a local server using PyCharm with Apache server. Now I deployed project on the Amazon AWS Elastic Beanstalk, but when I am trying to register a User (using standard django User model) I get exception: attempt to write a readonly database Can anyone give a hint how can I fix this? -
New relics with django channels on heroku
Can someone explain to me how to add new relic to django-channels example project running on Heroku ? -
How to block specific django app's url
I'm using the AllAuth plugin. Is there a proper way to block only a part of it's urls? -
How to known the level of current page Django
my page.html has this {% extends "base.html" %} {% load cms_tags menu_tags %} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} {% placeholder "content" %} {% show_menu 2 0 0 100 %} {% endblock content %} But depend of the level of the current page I have to show different element on the page, something like this {% if node.menu_level == 2 %} {% show_menu 2 0 0 100 %} {% else %} #do something different {% endif %} How to do that? How to know the level of the current page? -
I am making a movie inventory using python in Django.
I am passing parameters in URL, that parameter will be added in the database. In the parameter there is Name of movies and movie count. Using this list I need to perform rent and return functions. So if I rent that movie, the movie count will de duducted from the original list and if i return the movie count will increment. what should I add in rent and return functions and html files. -
Concisely adding variables to Django context dictionary
The Django documentation suggests adding variables to the context dictionary in class based views as follows: def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context I often have a lot of variables in my gather context function, so my code ends up looking like this: def get_context_data(self, **kwargs): context = super(PublisherDetail, self).get_context_data(**kwargs) a = 2 b = 'hello' c = 75 # temp variable, not wanted in context dict d = a * c context['a'] = a context['b'] = b context['d'] = d return context To avoid adding each variable to the context dictionary on its own line, I've begun doing the following: def get_context_data(self, **kwargs): context = super(PublisherDetail, self).get_context_data(**kwargs) a = 2 b = 'hello' c = 75 # temp variable, not wanted in context dict d = a * c del c # delete any variables you don't want to add context.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'context'}) return context It seems to be working, but I'm not very familiar with locals(). Is there any reason why I shouldn't be … -
Kendo UI Styling with Many Django Forms
We have a Django project that has many (100s) of forms across it. We would like to apply Kendo UI styling (http://demos.telerik.com/kendo-ui/styling/index) to all of our forms. This pretty much entails adding classes to the appropriate elements in order to get the styling. What's the best technique to achieve this result? I've found two main approaches, each with their drawbacks: 1 - Create a "Kendo Form" Django template. This template would have tons of logic in it for each type of possible field. However, this would probably be the easier of the two options for application authors to use (just include the template on their pages). Would we also lose functionality like .as_p() and .as_table()? {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} {% if field|is_choice %} <stuff class="niftyKendoClass"></stuff> {% elif field|is_radio %} <stuff class="niftyKendoClass"></stuff> ...... {% endif %} {% endfor %} 2 - Create custom "Kendo Widgets" by subclassing Django's widgets (https://docs.djangoproject.com/en/1.9/ref/forms/widgets). From what I can tell, implementation of this technique would be easier than the template since I just need CSS classes and can reuse Django's markup in most cases, but it becomes harder on the caller as … -
How to retain data type in django form submitted through AJAX
I am trying submit a large django form using AJAX. (I am using post method in AJAX. if this information is relevant here) If I do serializeArray() like below then I get a Json String. formData = JSON.stringify($('#add_member_Form').serializeArray()); Something like this - [{"name":"csrfmiddlewaretoken","value":"tZYajDy9XlzpQSyNwCXHY58S0fdI7BQS"},{"name":"first_name","value":"dajk"},{"name":"last_name","value":"khjk"},{"name":"gender","value":"2"}] And then on server side I am using json.loads() to convert it into a list. But in this process I am losing the type of data. For example in the data above, gender was an integer but it is converted to string. Is there any way to send this form data using AJAX and retain the data type (numbers remain integers when received in django view) for each field? -
Django all-auth module how to override user creation
I have a mobile app and website, which backend is Django. Mobile app's backend is the same django app. In mobile and in browser version users can login using Facebook. In mobile app I login into facebook using FB SDK and then manually create user in django and then authenticate new user in system. In desktop version thanks to all-auth user is created automatically, but I dont have control over it. Is there a way, in which I can alter user creation process on desktop from social credentials ? I need to perform some logic in case not to have same user registered twice from mobile and from desktop -
How can I store a file path in Mysql database using django?
I need to store a file path in db using django via ajax form submission . Here is my view: def new_scheduler(request): if request.method =='POST': f_name = request.POST.get('file') dateAndTime = request.POST.get('dateAndTime') Scheduled_data = schedulesdb.objects.create( f_name = file, dateAndTime = dateAndTime, ) Scheduled_data.save() return HttpResponse ('done') It save in database like <type 'file'> . Here is my model.py: class schedulesdb(models.Model): f_name = models.CharField(max_length=100) dateAndTime = models.DateTimeField(['%Y-%m-%d %H:%M:%S'],null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=2) def __unicode__(self): # on Python 2 return self.f_name Thanks in advance :)