Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Wkhtmltopdf error on IIS
i have same problem: How generate a pdf file with django-wkhtmltopdf on IIS 7.5 - 8 but i am on python 3.4. check_out method on subprocess.py like: def check_output(*popenargs, timeout=None, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') if 'input' in kwargs: if 'stdin' in kwargs: raise ValueError('stdin and input arguments may not both be used.') inputdata = kwargs['input'] del kwargs['input'] kwargs['stdin'] = PIPE else: inputdata = None with Popen(*popenargs, stdout=PIPE, **kwargs) as process: #with Popen(stdout=PIPE, stderr=PIPE, stdin=PIPE, *popenargs, **kwargs) as process: try: output, unused_err = process.communicate(inputdata, timeout=timeout) except TimeoutExpired: process.kill() output, unused_err = process.communicate() raise TimeoutExpired(process.args, timeout, output=output) except: process.kill() process.wait() raise retcode = process.poll() if retcode: raise CalledProcessError(retcode, process.args, output=output) return output -
Django-filer: set secure downloads based on group membership for non-staff/admin users?
New to django-cms, django-filer, have secure downloads working, but would like to allow users with minimal permissions (that is, just logged in, not django staff or admin access) to view files, how or where should I look to edit these permissions levels? I've looked through the filer package templates, but nothing there jumped out at me, assume I'm missing something basic, thanks for any help! -
let users download files from my aws bucket using django
I am working on a document sharing site for students that lets them upload and download files directly to/from from the site. Right now I have the site set up to where they can upload the files (which sends those files to an AWS bucket), however I cannot get it to where they can download the files. One of the paths that I am given is ^mysite.s3.amazonaws.com/media/(?P.*)$. I am trying to use this path to let users download the files however I just get sent to an error 404 page. Is there an IAM policy or special path that lets users download files from my bucket? I am assuming there is something, I just haven't found anything useful on the web. Thank you in advance for any light you can shine on my question! My Current IAM Policy is this: { "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetBucketLocation", "s3:ListBucketMultipartUploads", "s3:ListBucketVersions" ], "Resource": "arn:aws:s3:::<your_bucket_name>" }, { "Effect": "Allow", "Action": [ "s3:*Object*", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::<your_bucket_name>/*" } ] } My Current AWS Settings are this: AWS_ACCESS_KEY_ID = "key_ID" AWS_SECRET_ACCESS_KEY = "key" AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'mysite.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'mysite.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'mysite' … -
django-OperationalError at /register/ no such table: auth_user
I have tried many way to solve this, but none of them work. My question is when I tried to register a user, it shows an error no such table: auth_user . (py2.7 django 1.10) I am using a custom user (because I want to add locations(one user can have multiple locations) to my users) in my models.py: from __future__ import unicode_literals from django.conf import settings from django.db import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model # Create your models here. from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Locations(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) lat = models.FloatField(default=0.0) lng = models.FloatField(default=0.0) class UserForm(UserCreationForm): class Meta: model = User fields = ("username",) In my setting.py: AUTH_USER_MODEL = 'weather.User' # Application definition INSTALLED_APPS = [ 'weather', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] in my views.py: from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from django.views.generic.edit import CreateView from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template.context_processors import csrf def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('register/complete') else: form = UserCreationForm() token = {} token.update(csrf(request)) token['form'] = form return render_to_response('registration/register.html', token) … -
String processing issues with special characters ('ascii' codec can't decode byte)
I run a Django forum (with postgresql backend) where users post regarding various topics. I employ the excellent fuzzywuzzy python library to check every user's post against the same user's previous post. If the post is a fuzzy match (e.g. 85% similar), I encourage the user to differentiate his/her newest post further. To ensure this works, I've been storing each user's previous posts in the profiles on the postgresql DB. To validate whether the latest user comment, I thus do: score = fuzz.ratio(latest_comment,submitter.userprofile.previous_comment) if score > 85: #show the user a friendly prompt Lately, I started saving all previous comments in redis, instead of making expensive DB calls. The code simply became: score = fuzz.ratio(latest_comment, get_prev_comment(user_id)) if score > 85: #show the user a friendly prompt Where get_prev_comment() is a redis function that extracts the user's previous comment. My problem is that this fails when strings contain special characters such as this:۞. Exact error being: 'ascii' codec can't decode byte 0xdb in position 0: ordinal not in range(128). It worked perfectly with Django's postgresql backend (where I was using Django's CharField() attribute to save it in the model). Can anyone point out what's changed and how I can fix this? … -
Either redirect or show a message (Django)
Writing a reusable Django component: Calling certain function of my component should either redirect to PayPal site (if the trial period is zero) or show the message to the user that he has registered and entered into a trial period. The problem is that because the component is reusable, I don't know in advance how the message should be shown: It may be redirect to a page which shows the message or it may be a JavaScript based popup window, etc. How to make a reusable Django method which can be customized in these ways? -
How do a for loop to this function in Django?
I have this def in my forms to customize the attrs def __init__(self, *args, **kwargs): super(ejemploForm, self).__init__(*args, **kwargs) self.fields['image'].widget = forms.ClearableFileInput(attrs={ 'id': 'Logo', 'class': 'file', 'data-show-upload':'false', 'data-show-preview':'false', 'name': 'logito', 'placeholder': 'myCustomPlaceholder'}) I want to do that for each widget in my template, for example: This is my HTML file <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="form-group"> {{form.image}} </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="form-group"> {{ form.image }} </div> </div> </div> So for example for the first {{form.image}} I want this: 'id': 'Logo', 'class': 'file', 'data-show-upload':'false', 'data-show- preview':'false', 'name': 'logito', 'placeholder': 'myCustomPlaceholder'}) For the second {{form.image}} I want this : 'id': 'imagen1', 'class': 'file', 'data-show-upload':'false', 'data-show-preview':'false', 'name': 'imagen1', 'placeholder': 'myCustomPlaceholder'}) How can I do that with the previous def function? -
Allow only the user to edit the profile
views.py class ProfileView(DetailView): model = User queryset = User.objects.all() template_name ="profile/profile_view.html" class ProfileEdit(UserPassesTestMixin, UpdateView): login_url = '/login/' model = User form_class = ProfileForm template_name="profile/profile_new.html" def test_func(self): #do something I want the profile to be edited only by the user who created it. What logic should i use in the test_func to restrict a user from editing other user's profile. is it possible to get the user_id from the detail view and use it globally? Note- I'm a beginner. -
How to put all the other pages in a base template without using a web framework
By django, one can use a base template for a common navbar and a footer adding {% block content %} {% endblock %} in the base template. Is there a method to do this using php but without a web framework? -
user with that username already exists in Django
I wrote two views as the class in Django in order to do the Registration and Login for my website. But the problem is that the user objects get created successfully. But when I try to authenticate later getting the warning message showing that user with that username already exists in Django The two views are given below class RegistrationView(View): form_class=RegistrationForm template_name='eapp/user_registration_form.html' def get(self,request): form=self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self,request): form=self.form_class(request.POST) if form.is_valid(): user=form.save(commit=False) #cleaned (normalized) data username =form.cleaned_data['username'] password =form.cleaned_data['password'] email=form.cleaned_data['email'] user.set_password(password) user.save() return render(request,self.template_name,{'form':form,}) class LoginView(View): form_class=LoginForm template_name='eapp/user_login_form.html' def get(self,request): form=self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self,request): form=self.form_class(request.POST) if form.is_valid(): #cleaned (normalized) data username =form.cleaned_data['username'] password =form.cleaned_data['password'] #authenticatin user=authenticate(username=username,password=password) if user is not None: if user.is_active: login(request,user) return render(request,'eapp/index.html',{}) return render(request,self.template_name,{'form':form,}) How can I solve this? ThankYou -
Python Django for loop not working properly
I have written a simple script, but when I have the loop in the script the products and allbrands variable comes out empty except when I remove the loop. Here is part of the script. products = amazon.search(Brand="Microsoft", SearchIndex="Software", ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations") allbrands = Brand.objects.all(); for i, product in enumerate(products): print ("Product"); context = { 'products': products, 'allbrands': allbrands } return render(request, 'storefront/index.html', context) -
What's the best way to load stored procedures into the Django unit test database?
I've got some Postgres stored procedures that my selenium tests will depend on. In development, I load them with a line in a script: cat stored_procedures.sql | python manage.py dbshell This doesn't work when unit testing, since a fresh database is created from scratch. How can I load stored procedures saved in a file into the test database before unit tests are run? -
google.maps.Marker icon url uses wrong relative path in django
I have a django web app with Google map. The web site url is like: www.mysite.com and settings for static url is defined: SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = ( (os.path.join(SITE_ROOT, 'static/')), ) The javascript as following show marker correctly: var iconuri = 'static/img/hello.png'; marker = new google.maps.Marker({ position: pos1, icon: iconuri, title: 'hello', map: mymap}); because it load hello.png correctly www.mysite.com/static/img/hello.png I added new url for the app, and the site can be accessed as: www.mysite.com/hello/1/ Then, above javascript can show marker, as it is looking: www.mysite.com/hello/1/static/img/hello.png What I should do to make new url work when enter www.mysite.com/hello/1/ in browser? Thank you. -
Django AutoCompleteLight Javascript Create function override
How to override django autocompltelight Create new item option in javascritpt. I want to change the default funtion to a popup modal.Somebody please help me. $(document).on("click", ".select2-results__option--highlighted", function(){ $(document).ajaxSend(function(e, jqXHR, options){ jqXHR.abort(); }); }); i tried to abort ajax request and try to create popup here, i know its not the correct solution. -
Is using SQLalchemy for a core python package and Django ORM for users a good idea?
I have a core python package used for data analysis. I also have a web-framework which provides a UI to this package as well as an API for accessing data. Currently, I'm using the django ORM for creating users etc. and I am executing manual SQL to return data from my core python package database. I'm looking to use an ORM for the core python package as well, and I am split between using Django ORM (which seems to be less flexible overall and gave me some problems when trying to use outside of django) and SQL alchemy (which would require having two ORMs, one for the core package to handle core data and one for the django site to manage users etc.) Before diving in to either too deeply, I'm not sure which path makes more sense. -
Patch Django Site Package From a Pull Request Using Pip
I need to apply pull request 51 to a locally installed Site Package in my Django project but am not sure how it should be done without applying directly to the local library directly. Is there a way to add reference to the pull request in requirements.txt or git config? Thank you. -
How to read and update data from database with Django python?
I learn django ecommerce from this book . In cart app forms.py use for select quantity of product. The code is PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] It show 1-20 product. It not relate with stock. If I have 5 product in stock this code will can but 20 products. How to edit code by get quantity from database? def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() And in order app when user checkout it should update stock by reduce quantity in view.py but I don't know how to modify this code . -
NoReverseMatch at Error Django/Python
I've tried to explore other questions here about this but having trouble diagnosing my error--hoping someone here can help me out. Here is the full error: NoReverseMatch at / Reverse for 'projects' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Error during template rendering In template /home/django/chrisblog/posts/templates/posts/home.html, error at line 0 The error happened when i tried to create a few additional pages on the website--just essentially copying the template of another page. These pages are using an extends tag with a 'base.html' template. My URL file looks like this from django.conf.urls import url from django.contrib import admin import posts.views import sitepages.views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', posts.views.home, name="home"), url(r'^resources/', sitepages.views.resources, name="resources"), url(r'^projects/', sitepages.views.projects, name="projects"), url(r'^about/', sitepages.views.about, name="about"), url(r'^posts/(?P<post_id>[0-9]+)/$', posts.views.post_details, name="post_detail"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my Views file from django.shortcuts import render from . import models def about(request): return render(request,'sitepages/about.html') def resources(request): return render(request,'sitepages/resources.html') def projects(request): return render(request,'sitepages/projects.html') Let me know if this is enough to go on. Thanks for the help. -
Django Apps aren't loaded yet error
I'm still new to Django, but when I run python manage.py runserver, I get this error: Unhandled exception in thread started by <function wrapper at 0x10363f2a8> Traceback (most recent call last): File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Applications/Canopy.app/appdata/canopy-1.4.0.1938.macosx-x86_64/Canopy.app/Contents/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/ashih/Desktop/ProjectX/website/mysite/toa/models.py", line 13, in <module> class Absolutedollarvalue(models.Model): File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "/Users/ashih/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Does this mean that the problem is with INSTALLED_APPS? toa is the name of the app, and toa.models.absolutedollarvalue is the name of one of the tables in models.py. Can anyone tell me what my issue is? This is my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings … -
django.contrib.gis.db + Images
I'm working on my first GeoDjango project. And I'm using django-leaflet + GeoJSON together with leaflet-ajax to display markers on the map. I would like to have an image attached to each "properties" to be displayed in the popup. But does django.contrib.gis.db play nice with ImageField. Because if I just go ahead and add a model.ImageField field to the model, I get an Type Error when saving from the Admin. That it has to be a string. I just wanna ask if it is possible to do this? I'm hoping that is and that I've just made mistake, that I need to find. Or should take another approach? P.S. I'm using Postgres -
Heroku django can't open file 'manage.py': [Errno 2] No such file or directory
I am trying to deploy my django project to Heroku. At local machine everything works fine. But when Iam trying to run heroku run python manage.py migrate I am recieving an error python: can't open file 'manage.py': [Errno 2] No such file or directory I tried heroku run bash, then pwd I am recieving /app but this folder is empty. -
Django redirect is not working
def CompleteMini(request,mini_id): mini_instance = get_object_or_404(url_all,mini_address = mini_id) return redirect(mini_instance.full_address) I have this code but it does not redirects explicitly to the URL provided as parameter rather it just appends the current url with this one -
Unable to run Nosetests on classes or functions
I am using pycharm and are trying to run individual tests. My "run all tests works (used py.test), but I want to run specific tests. When I try to run the Nosetest i get this error: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My wsgi.py looks like this: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "v3.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Django Rest Framework unittest ValueError: Cannot assign "u'johnz'": "Message.author" must be a "User" instance
tests.py from django.contrib.auth.models import User from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase, APIClient, RequestsClient, APIRequestFactory from rest_framework.authtoken.models import Token from views import MessageListView class CreateMessageTest(APITestCase): def setUp(self): self.client = APIRequestFactory() self.user = User.objects.create_user(username='johnz', first_name='John', last_name='Doe', email='john@doe.com', password='johnny', id=3) self.user.save() self.token = Token.objects.create(user=self.user) self.data = {"body": "I am sad", "author": self.user} def test_loggedin_user_can_create_message(self): header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token)} user_obj = User.objects.get(pk=self.user.pk) request = self.client.post(reverse('message-list'), data=self.data, **header) request.user = self.user response = MessageListView.as_view()(request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_anonymous_cant_create_message(self): request = self.client.post(reverse('message-list'), data=self.data) response = MessageListView.as_view()(request) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) Traceback Traceback (most recent call last): File "/home/bkovacev/PycharmProjects/silver_logic_project/posts/tests.py", line 28, in test_loggedin_user_can_create_message response = MessageListView.as_view()(request) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/generics.py", line 243, in post return self.create(request, *args, **kwargs) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 21, in create self.perform_create(serializer) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 26, in perform_create serializer.save() File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 214, in save self.instance = self.create(validated_data) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 902, in create instance = ModelClass.objects.create(**validated_data) File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), … -
How can I update multiple FileField with the same FK ID in Django?
I have this form in my template I can add the images at the same time but when I want to update I can't, this is for that each image have the same FK , So I don't know how can I update the five images at the same time. This is part of my code in the HTML file : <div class="form-group"> <label class="col-md-12 control-label">Logo </label> <div class="col-md-12"> {{form2.imagen}} </div> </div> <div class="form-group"> <label class="col-md-12 control-label">Carousel 1</label> <div class="col-md-12"> {{form2.imagen}} </div> </div> <div class="form-group"> <label class="col-md-12 control-label">Carousel 2</label> <div class="col-md-12"> {{form2.imagen}} </div> </div> <div class="form-group"> <label class="col-md-12 control-label">Carousel 3</label> <div class="col-md-12"> {{form2.imagen}} </div> </div> <div class="form-group"> <label class="col-md-12 control-label">Carousel 4</label> <div class="col-md-12"> {{form2.imagen}} </div> </div> This is my Archivos model: class Archivos(models.Model): id_archivo = models.AutoField(primary_key=True) id_unidad = models.ForeignKey(Unidad, on_delete=models.CASCADE) nombre_archivo = models.CharField(max_length=255, blank=True) imagen = models.FileField(null=True, blank=True) This is my views as you can see I update two forms that have a relationship class uniUpdate(UpdateView): model = Unidad second_model = Archivos template_name = 'back/Modulo_unidades/partial_unidad_form.html' form_class = UnidadForm second_form_class = imgForm success_url = reverse_lazy('BackEnd:unidades') def get_context_data(self, **kwargs): context = super(uniUpdate, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) solicitud = self.model.objects.get(id_unidad=pk) persona = self.second_model.objects.get(id_unidad=solicitud.id_unidad) if 'form' not in context: context['form'] = self.form_class() if …