Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Checkout' object is not iterable
I'm having a problem and here's my code please help. I did this because what i want is when an existing user login the details of that user automatically appears on the page error 'Checkout' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/checkout1/1/ Django Version: 1.8.7 Exception Type: TypeError Exception Value: 'Checkout' object is not iterable Exception Location: /usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render, line 161 models class Checkout(models.Model): fname = models.CharField(max_length=120) address = models.CharField(max_length=250) email = models.EmailField(blank=True, null=True) number = models.IntegerField(blank=True, null=True) city = models.CharField(max_length=120) def __unicode__(self): return self.fname views def checkout1(request, id): i = Checkout.objects.get(id=id) return render(request, 'checkout1.html',{'k':i}) html <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for i in k %} {{i.fname}} {{i.address}} {{i.number}} {{i.city}} {{i.email}} {% endfor %} </body> </html> -
before submitting form data to database change some field data in view django
Hi my form is like this , And when I submit it goes to view I attached , I want to change for example add dashes between string in name field before it is submitted. So how I can do this in my view ? Form.html name = models.CharField(max_length=255, help_text='The name of this map.') subtitle = models.CharField(max_length=255, null=True, blank=True, help_text='If(unbolded)') And when I I submitt it goes to that view View.py def save_form_if_appropriate(self, attr): if self.request.method == 'POST': if self.site_acl >= self.acl.ADMIN or self.is_modifying_self(attr): if self.form.is_valid(): if attr == 'user': obj = self.form.save(commit=False) # this way we can keep record of the users creator. obj.parent_id = self.request.user if hasattr(obj, 'user_type') and obj.user_type != 'pro': obj.sub_users_allowed = 0 obj.save() else: self.form.save() messages.success(self.request, 'Thing saved.') return True else: messages.warning(self.request, self.form.errors) # messages.warning(self.request, 'Thing was invalid, and couldn\'t be saved.') else: messages.warning(self.request, 'You don\t have permission to save that thing.') return False -
How to connect multi master mysql in Django?
Our mysql cluster is a Multi-Master cluster. How to set db options of Django to use it? -
ListView with alternate background image [duplicate]
This question already has an answer here: Modulus % in Django template 3 answers This code doesn't work!! I want to show an img red and then blue. If I have 5 object the the list should be: Red Blue Red Blue Red I want to do this with 3 coulors. I thigh to something like this. Sorry for my English, I know is very bad! {% extends './base.html' %} {% block content %} {% for object in object_list %} {% if forloop.counter0 % 2 ==0 } <img src="img/red.jpg"> <p> {{object.title}} </p> {% else %} <img src="img/blue.jpg"> <p> {{object.title}} </p> {% endif %} {% endfor %} {% endblock content %} -
Using URLfield in django form, can't put without http/https prefix
I'm trying use URLfield in Django form, but when I put URL without http/https prefix in a browser (like www.ya.ru) it's don't send post query to my server. How to allow to use url without prefixes? -
exception error rising in installing virtualenv
I'm trying to install python virtualenv. So i ran the command pip install virtualenv and I met these errors. Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/virtualenv.py' -
unable to use PIL in django view function
i am trying to make a function that makes thumbnail of an image but i am unable to open the image file def create_thumbnail(request): slug = 'yftguhjkn' post = get_object_or_404(Post, slug=slug) if post: markdownify = import_string(MARKDOWNX_MARKDOWNIFY_FUNCTION) content = BeautifulSoup(markdownify(post.content), "html5lib") try: img_link = content.findAll('img')[0].get('src') print(img_link) filename = img_link.split('/')[-1] filename = filename.split('.')[0] file_path = settings.MEDIA_URL + settings.DRACEDITOR_UPLOAD_PATH + post.author.username + '/' + filename + '.jpg' print (file_path) #im = Image.open(img_link) im = Image.open(file_path) print (im.size) except: img_link = 'http://howtorecordpodcasts.com/wp-content/uploads/2012/10/YouTube-Background-Pop-4.jpg' return HttpResponse(img_link) but it is going to except statement can someone please tell me how to fix it -
django.db.utils.OperationalError: (1045, "Access denied for user 'someuser'@'localhost' (using password: NO)")
I am getting error when try to run python manage.py migrate django.db.utils.OperationalError: (1045, "Access denied for user 'someuser'@'localhost' (using password: NO)") This is my database setting inside setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': {'read_default_file': '/config/mysql.cnf', }, } } config/mysql.cnf [client] database = dbname user = root password = passwt host = localhost default-character-set = utf8 -
django Select2 multipleselect ajax
Below you may find the jquery code and select element in my template: <select class="tags-select" id="usergroup_setting" multiple="multiple" style="width: 300px;"> <option value="tag1" selected="selected">tag1</option> <option value="tag2" selected="selected">tag2</option> </select> $("#usergroup_setting").select2({ minimumInputLength: 3, ajax: { url: "users", dataType: 'json', quietMillis: 200, data: function (term) { return { q: term.term }; }, results: function (data) { return { results: data }; } } }); In the view of django, I manually combined the info to below String without consideration on any query param and return it: users=[{"id":"1","text":"test1@gmail.com"},{"id":"2", "text":"test2@gmail.com"}] return HttpResponse(json.dumps(users), content_type="application/json") then in the web, the select shows the default 2 options, when I type in the filter with "test", it shows the "No result found". Is there anybody know why? appreciate your help in advance! -
Anyone have an idea why tokens are not generated?
I wonder why tokens are not generated in my Django project. It seems to me that everything worked properly but now I get: django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner django_1 | response = get_response(request) django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response django_1 | response = self.process_exception_by_middleware(e, request) django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response django_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) django_1 | File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view django_1 | return view_func(*args, **kwargs) django_1 | File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view django_1 | return self.dispatch(request, *args, **kwargs) django_1 | File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch django_1 | response = self.handle_exception(exc) django_1 | File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception django_1 | self.raise_uncaught_exception(exc) django_1 | File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch django_1 | response = handler(request, *args, **kwargs) django_1 | File "/code/myProject/backend/myProject/companies/views.py", line 43, in post django_1 | return Response({'token': user.auth_token.key, 'id': user.id}, status=status.HTTP_200_OK) django_1 | File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 404, in __get__ django_1 | self.related.get_accessor_name() django_1 | django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: User has no auth_token. I checked my database and there is no token. Obviously I can add it through admin panel and then it works, but of course it should be generated β¦ -
User Object in Django Signals
I am using .post_save in some of my models to do some time consuming works. I want to track which user is actually sending the signals. Is there any way to do that? -
Fighting side effects of concurrent request handling and database transactions
Brief In one of my views I make external API Call to charge user's credit card. This view is not invoked by user himself - it's requested by staff user. I want to avoid race condition that allows two staff users to charge payment at the same time (or in very short period). Code Let's say my (much simplified) view's payment method looks like this in pseudocode: def make_payment(order): """ order - instance of Order model """ payment = Payment.objects.get_or_create(order=order) if not payment.paid: authorised = ExternalAPI.charge(payment) if authorised: payment.paid = True payment.save() Problem My ATOMIC_REQUESTS setting is set to True (it has to stay that way). That means, that payment.paid set to True won't be commited until client gets his response. In case when a payment instance already exists, but was not paid yet there is race condition that would allow two clients to simultanously call view and thus charge payment twice. One of them would be then probably returned OperationalError (database is locked), but still most of the code would be executed twice. I actually tried it by simply making two requests at once from console and it happened. How can I avoid it? What I've tried Since I'm β¦ -
Django : Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: [u'music/(?P<pk>[0-9]+)/$']
I am new to Django Environment (current version : 1.11.4) , I am trying to get an HTML Page to see the issue but getting an exception: NoReverseMatch at / music / Reverse for 'detail' with arguments '(' ',)' not found.1 pattern(s) tried: [u 'music/(?P<pk>[0-9]+)/$'] Some of the files I am taking in consideration are : index.html { % extends 'music/base.html' % } { % block body % } { % if all_albums % } <ul> {% for album in all_albums %} <li> <a href="{% url 'music:detail' album.id %}">{{album.album_title}}</a> </li> {% endfor %} </ul> { % else % } <h3>No Album Found </h3> { % endif % } { % endblock % } ** urls.py ** from django.conf.urls import url from.import views app_name = 'music' urlpatterns = [ url(r '^$', views.IndexView.as_view(), name = 'index'), url(r '^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name = 'detail'), ] views.py from django.views import generic from.models import Album from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' and my base.html file has nothing but a navigation bar with some functionalities to follow. I just did everything to make β¦ -
TypeError: __init__() got an unexpected keyword argument 'customer
class RequestProcess(dxmodels.WorkflowEnabled): def __init__(self): lang = self.customer.user.customerprofile.language @xworkflows.on_enter_state('documents') def on_documents(self, *args, **kwargs): self.update_timestamps() ctx = {'request': self} EmailFromTemplate('request-required-documents', extra_context=ctx, lang=lang)\ .send_to(self.customer.user) @xworkflows.on_enter_state('validation') def on_validation(self, *args, **kwargs): self.update_timestamps() validate_requirements_for_request(self) @xworkflows.on_enter_state('signature') def on_signature(self, *args, **kwargs): self.customer_product.lock() self.contract = create_contract(self) self.update_timestamps() ctx = {'request': self} EmailFromTemplate('product-request-accepted', extra_context=ctx, lang=lang)\ .send_to(self.customer.user) class Meta: abstract = True I have the following error TypeError: __init__() got an unexpected keyword argument 'customerd. I don't want to put lang = self.customer.user.customerprofile.language in each method. I just want to instantiate once a variable. What could I do to fix it? For instance, if I write a method and comment the other methods, it works fine. @xworkflows.on_enter_state('deposit') def on_deposit(self, *args, **kwargs): self.update_timestamps() self.customer_product.lock() create_loan_from_request(self) ctx = {'request': self, 'deposit_date': self.loan.product.deposit_date} EmailFromTemplate('deposit-notice', extra_context=ctx, lang=self.customer.user.customerprofile.language)\ .send_to(self.customer.user) Traceback Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/jeremie/Projects/Work_Projects/24-django/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/jeremie/Projects/Work_Projects/24-django/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jeremie/Projects/Work_Projects/24-django/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/jeremie/Projects/Work_Projects/24-django/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/jeremie/Projects/Work_Projects/24-django/loanwolf/core/management/commands/gen_fake_data.py", line 583, in handle options=options) File "/home/jeremie/Projects/Work_Projects/24-django/loanwolf/core/management/commands/gen_fake_data.py", line 244, in create_operation req = app.accept() File "/home/jeremie/Projects/Work_Projects/24-django/loanwolf/requests/models.py", line 625, in accept return create_request_from_external(self) File "/home/jeremie/Projects/Work_Projects/24-django/loanwolf/requests/utils.py", line 123, in create_request_from_external 'entered_documents_at': datetime.datetime.now(), β¦ -
can't display graphs with django-graphos as a MongoDBDatasource
from graphos.sources.simple import SimpleDataSource # from graphos.renderers.gchart import LineChart from graphos.sources.mongo import MongoDBDataSource from graphos.renderers.yui import LineChart @route("resource") def resource(request): client = MongoClient() db = client.collectd cur = db.aggregation.find_one() fields = [] from graphos.sources.base import BaseDataSource from graphos.sources.mongo import MongoDBDataSource doc_list = [] current_row = [] for doc in cur: for i in range(len(fields)): try: field = doc[fields[i]] except KeyError: field = "" current_row.append(field) doc_list.append(current_row) data_source = MongoDBDataSource(cur, fields, doc_list) chart = LineChart(data_source) # header = data_source.get_header() # # column = data_source.get_first_column() context = {'chart': chart} return render(request, 'resource.html', context) when trying to load my web page: I got an error as "list index out of range" caused by the line categoryKey:"{{ chart.get_category_key }}" in my file base.html -
Beanstalk Cronjobs using django-cron
Im trying to get cronjobs running on my elasticbeanstalk ec2 instance using django-cron. I created a cronjob.cron: */5 * * * * root /opt/python/run/venv/bin/python3 /opt/python/current/app/manage.py runcrons >> /var/log/cronjobs.log and added the file using commands: container_commands: 06_runcrons: command: "cat .ebextensions/cronjobs.cron > /etc/cron.d/djangocrons && chmod 644 /etc/cron.d/djangocrons" leader_only: true The cron seems to run but nothing gets printed into my /var/log/cronjobs.log (Which it should, every 5mins). I cannot test the script on the ec2 instance manually, because my environment variables I added using aws:elasticbeanstalk:application:environment: are neither present with the ec2-user or root. Where do those environment variables get written to? Are they only present during the deploy? The server itself works fine, so my db environment variables work. Do I need to use another user for my cronjobs? How can I solve this? -
Django REST Framework HyperlinkedRelatedField: Using related instances from cache
using djangorestframework==3.6.3, django 1.10 Drf has a HyperlinkedRelatedField. The question is how to get this field to use model instances from cache before issuing sql. For example models.py class WebPages(models.Model): # model fields.... @property def latest_pwc(self): return PageWordCount.from_cache_by_webpage(webpage = self) #..... class PageWordCount(models.Model): #....other model fields web_page = models.ForeignKey(WebPages, related_name= 'pwcs', on_delete=models.CASCADE) #...... serializers.py class PageWordCountSerializer(serializers.HyperlinkedModelSerializer): web_page = serializers.HyperlinkedRelatedField(view_name='api_webpage', read_only=True) class Meta: model = PageWordCount fields = [...., 'web_page'] class WebPagesSerializer(serializers.ModelSerializer): latest_pwc = CachedHyperlinkedRelatedField(many=False, view_name='api_pwc', read_only=True) class Meta: model = WebPages fields = [..., 'latest_pwc'] where CachedHyperLinkedRelatedField is class CachedHyperlinkedRelatedField(serializers.HyperlinkedRelatedField): def get_attribute(self, instance): return PageWordCount.from_cache_by_webpage(webpage = instance) Here the field handles only one instance of the model from the cache. However the same with many=True (for a cache entry that return more than 1 instance) get_attribute is not called on the subclass. DRF code comments Relationships with `many=True` transparently get coerced into instead being a ManyRelatedField with a child relationship. so when many=False get_attribute works as expected since it is not coerced. What would be a good way to get ManyRelatedField to work the same on many=True? -hsk -
django 1.8.6 - ModuleNotFoundError: No module named 'django_smtp_ssl'
I am a bit stuck here working through, Django by example. I keep getting the error that there is no module names 'django_smtp_ssl. Here are the mail settings from settings.py EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER = 'xxx@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT=465 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' command I am using in shell is: send_mail('Django Mail', 'This email was sent with Django', β123@msn.com', [β123@msn.com'], fail_silently=False) -
Django : How to create form (crispy form) and table (django-table2) in one single template
I am new to django and currently having a requirement of creating a form with table in one single template. I am using crispy form and django table 2 for this and in this I have to add a user in group and then show that added user in group table simultaneously. Can anyone help me out with the approach. Thanks in advance -
Form validation in Django: What to override or not?
I do not yet fully understand the validation process of Forms in Django. I've read the documentation about it already, but I've still questions. In the Mozilla Django Tutorial you can read this: Django provides numerous places where you can validate your data. The easiest way to validate a single field is to override the method clean_() for the field you want to check. So for example, we can validate that entered renewal_date values are between now and 4 weeks by implementing clean_renewal_date() as shown below. My question now: If I create methods like clean_field_name() what do I override? In the quote above it says that you'll override this method. However, I could not find what exactly I do override. In case I do override something, isn't it bad? Or are those methods only methods you can create by your own but do not exist by default? -
How to load css as static in Django
Hi I have the following structure in my project: myapp βββ app β βββ app | | βββ settings.py β β βββ [...] β βββ templates β β βββ base.html β β βββ my_test.html β βββ app2 β βββ [...] βββ statics β βββ bootstrap β β βββ css β β β βββ bootstrap.min.css β βββ static_root and I want to use the bootstrap.min.css in the base.html (which looks currently like this): {% load staticfiles %} <!DOCTYPE html> <html> <head> {% block head %} <link rel="stylesheet" type="text/css" href="../../statics/bootstrap/css/bootstrap.min.css"> {% endblock head %} </head> <body> {% block content %}{% endblock content %} </body> </html> and in my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'statics', 'static_root') STATICFILES_DIR = { os.path.join(BASE_DIR, 'statics', 'bootstrap'), } so how I have to chance it that it works because in this version it does not work (Page not found at /statics/bootstrap/css/bootstrap.min.css). -
ManifestStaticFilesStorage - still fetching old static file even when staticfiles.json shows the right mapping
After performing collectstatic and moving over the files to prod, I still see old css file (with old MD5 hash string) being fetched. settings.py: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' On prod, I can see staticfiles.json showing the correct (new) css file but still when I do 'view-source' from the web page, I can see old css being fetched. What could I have missed? -
How to load json into django (views or templates)
So I want to load json-data from a website (http://api.fixer.io/latest) and pick exactly the USD-value in the views. Nothing worked so far and I got nothing but errors. This is what I got so far: views from urllib import urlopen import json my_url = 'http://api.fixer.io/latest' data = json.loads(urlopen(my_url).read()) def home(request): return render(request, "index.html", {"data":data}) template {{ data }} -
Accessing Django models while Testing
I would like to know whether it is possible to access the current models stored in the db while doing testing in Django. Thanks! -
ModuleNotFoundError: No module named 'axes'
I installed django-axes using pip command $ pip install django-axes Then I've added axes to my Installed Apps as shown below INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'axes', 'frontend', 'userauth', 'methods', ] But when I run command python manage.py runserver I get error ModuleNotFoundError: No module named 'axes'