Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Working with AWS- Django and MongoDB
I have developed my application using mongoDB as the database and Django framework and I intend to use AWS services. I visited the AWS site and there were many products that confused me, so with the above stack what would be the most viable solution to work with AWS -
Is it possible to make a custom ADD form in Django-Admin?
I checked out How to add button next to Add User button in Django Admin Site for the extra button. Is it a "preferred" way of creating a custom ADD function that is a copy of the normal ADD function with some modifications, i don't want to replace the default ADD function. This is to make some "devices" have a few default fields that is always the same when adding them. Some really nice images to explain my question. https://s12.postimg.org/a9hqfub6l/add_default.png https://s14.postimg.org/z93ujbqbl/cloned_add.png -- Regards Falk -
Django migration relation does not exist
So I'm trying to run the initial migrations on a django app and when I try to run the migrate command (python manage.py migrate or makemigrations) I get the following error: psycopg2.ProgrammingError: relation "dotworks_server_internship" does not exist LINE 1: ...s", "dotworks_server_internship"."questions" FROM "dotworks_... ^ I'm on a Windows environment using Django 1.9.6 and my database is postgres. Plus, I'm using PGAdmin to manage my database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dotworks', 'USER': 'postgres', 'PASSWORD': 'mypasswordgoeshere', 'HOST': 'localhost', 'PORT': '5432', } } -
Edit tag from Django RadioSelect widget
I've created a custom ModelChoiceField: class ImageModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): image = conditional_escape(obj.widget_image.url) label = """<img src="%s" />""" % (image) return mark_safe(label) and i use the forms.RadioSelect() widget , so i could have icons instead of labels for my "radio options". So the HTML rendered is: So my question is how can I edit the <img src tag ? Is that possible from the view? -
Convert Query result to strings from Unicode
I'm running a script every half hour or so comparing states of jobs in the Job table if i query the database i get back results in this format: (u'production_assignment', u'22', datetime.datetime(2016, 11, 17, 12, 13, 44, 839672, tzinfo=<UTC>)) Is there anyway to convert this back to the same data style that is recorded in the table? -
In Heroku, how I connect PostgreSQL from another server?
I created one App Python:Django in Heroku, in my settings I have a set up a database from Amazon WS, so when Deploy is finished, another configurations appear. My settings.DATABASES DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myAppDb', 'USER': 'UserAppDb', 'PASSWORD': 'some_password', 'HOST': 'myAppDb.cohkbwwvlbxi.us-west-2.rds.amazonaws.com', 'PORT': '7878', } } In console heroku I have this: heroku run bash python from myapp import settings setting.DATABASES {'default': {'NAME': 'd7kqa751lkhqo6', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'ec2-74-75-228-85.eu-west-1.compute.amazonaws.com', 'USER': 'hzhpegboxtikxk', 'PORT': 5432, 'PASSWORD': 'XfiPl1tJZB9Znk22b5UQmeYD2u', 'CONN_MAX_AGE': 500}} In this case: NAME, HOST, USER, PORTΒ΄,PASSWORD` are tottaly diferent then I setup. What I did wrong or didn't? -
python loop breaks on special chars in django template
So I am working with django and an external List of names and values. With a custom template tag I am trying to display some values in my html template. Here is a example of what the list could look like: names.txt hello 4343.5 bye 43233.4 HΓ«llo 554.3 whatever 4343.8 My template tag looks like this (simplified names of variables): # -*- coding: utf-8 -*- from django import template register = template.Library() @register.filter(name='operation_name') def operation_name(member): with open('/pathtofile/member.txt','r') as f: for line in f: if member.member_name in line: number = float(line.split()[1]) if number is not member.member_number: member.member_number = number member.save() return member.member_number return 'Not in List' It works fine for entries without specials char. But it stops when a name in member.member_names has special chars. So if member.member_names would be HΓ«llo the entire script just stops. I can't return anything. This is driving me crazy. Even the names without special chars won't be displayed after any name with special chars occurred. I appreciate any help, thanks in advance. -
PyCharm console - no module named
I've recently renamed project and its apps. When I run development server through Windows command line it works correctly. The problem is that when I run server through PyCharm (I've set virtualenv), it says (I've recently installed django-allauth): Unhandled exception in thread started by <function wrapper at 0x03767B30> Traceback (most recent call last): File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\core\management\commands\runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\utils\autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Milano\Desktop\Projekty\venvs\sflvenv\lib\site-packages\django\apps\config.py", line 86, in create module = import_module(entry) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named allauth What I've done: Replaced all apps with new names, project too. Removed .idea folder to make PyCharm create fresh new. Set virtualenv What should I do to make it work? -
How do I pass and render an object to an extended child template?
So what I'm trying to do is create a view for a child template, so that I can pass in model objects and parameters, and render it accordingly. But is this possible..because two views can't be called once? And two urls (one for child and one for parent template) can't be called at once either. I don't understand how it works or maybe I'm just not looking at it right. Does anyone have any idea? urls.py BV = BoxesView.as_view() urlpatterns = [ url(r'^(?P<question_id>[0-9]+)/$', poll, name='poll'), #child template url(r'^$', BV, name='news'), #parent template ] view.py class BoxesView(ListView): template_name = 'polls.html' def get_queryset(self): queryset_list = Post.objects.all().filter(category=1).order_by('-date') return queryset_list def poll(request, question_id): question = get_object_or_404(Question, id=1) return render(request, 'polls.html', {'question': question}) child.html {% extends 'parent.html' %} {% block polls %} <p>question goes here</p> #this shows up {{ question.question_text }} #this doesn't show up {% endblock %} parent.html {% extends 'base.html' %} {% block content %} {% for post in post_list %} {% block polls %} {% endblock %} {% endfor %} {% endblock %} models.py class Post(models.Model): title = models.TextField(max_length=70) class Question(models.Model): question_text = models.CharField(max_length=70) -
Django modify field before save_as_new
I have a post like model consisting of a field is_published. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=255, blank=True) body = models.TextField() is_published = models.BooleanField(default=False, db_index=True) date = models.DateField(blank=True, null=True) In the admin page I set save_as=True and everything works fine. However it also publishes the new object when saved as new. class BlogAdmin(admin.ModelAdmin): inlines = [ PostInline, AuthorInline, ] save_as = True What I'd like to do in this step is to set is_published field to false when clicked on save as new button. I've tried some codes that override model_save unfortunately couldn't succeed. -
Django admin showing duplicate results
I'm building an application for handling reservations. I'm using Django 1.10. The problem is that django admin is showing duplicated results, but my database and fronted show the correct amount. Database App Admin admin.py from django.contrib import admin from .models import Reservation admin.site.register(Reservation) I'm not sure what's happening here.. -
Django view is not redirecting properly
I'm facing some difficulties to render pages with Django shortcuts. My workflow is quite simple: Users go a page where they can view some project data (detail_project) If they want to update the project data, they should click a button that will send a POST request and loads update_project page. This page is loaded with current project data. Users update and submit new data. After submission, they are returned to detail_project page. My view is like this: def update_project(request): if request.method == 'POST': if 'update_project_submit' in request.POST: # updates project with form data and returns to detail project page return redirect('detail_project', project_name=project_name) else: # loads project original data into the form return render(request, 'project/update_project.html', context) def detail_project(request, project_name): if request.method == 'POST': if 'update_project' in request.POST: return update_project(request) else: # does another stuff else: # shows project details return render(request, 'project/detail_project.html', context) urls.py: url(r'^project/update/$', views.update_project, name='update_project'), url(r'^project/details/(?P<project_name>[a-zA-Z][a-zA-Z0-9-_]+)/$', views.detail_project, name='detail_project'), And update_project.html: <form class="form-horizontal" role="form" action="" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> <div class="col-sm-3"> <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label> </div> <div class="col-sm-9"> {{field}} </div> <div class="col-sm-12"> {{ field.help_text }} </div> </div> {{field.non_field_errors }} {{field.errors}} {% endfor %} <button type="submit" name="update_project_submit" class="btn btn-primary">Submit</button> </form> β¦ -
'WSGIRequest' object has no attribute 'cart' in django-cartridge
I am working on Django 1.10, Mezzanine 4.4.2 with Cartridge installed manually after installing Mezzanine. Now I am able to add the products and price through cartridge. But when I click on the BUY button it is giving me the following error:- AttributeError at /shop/product/nike-blue/ 'WSGIRequest' object has no attribute 'cart' Request Method: POST Request URL: http://localhost:8000/shop/product/nike-blue/ Django Version: 1.10.3 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'cart' Exception Location: G:\Py_Envs\Racknole\Mezzanine_Trial\lib\site-packages\cartridge\shop\views.py in product, line 69 Python Executable: G:\Py_Envs\Racknole\Mezzanine_Trial\Scripts\python.exe Python Version: 2.7.11 Python Path: ['G:\\Django_Projects\\RackNole\\Mezzanine_Trial\\project_name', 'C:\\Windows\\SYSTEM32\\python27.zip', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial\\DLLs', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial\\lib', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial\\lib\\plat-win', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial\\lib\\lib-tk', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial\\Scripts', 'c:\\python27\\Lib', 'c:\\python27\\DLLs', 'c:\\python27\\Lib\\lib-tk', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial', 'G:\\Py_Envs\\Racknole\\Mezzanine_Trial\\lib\\site-packages'] Server time: Fri, 11 Nov 2016 11:11:07 +0000 Also if I click on checkout option it shows me an empty cart and then again when I click on continue shopping it redirects me to the http://localhost:8000/shop/which I want to change. Thanks in advance. -
Some Celery tasks work, others are NotRegistered
I follow the Celery Django tutorial and the tasks I see in the example (add, mul) work for me perfectly. I get a correct response when I do res = add.delay(1,2); res.get(). But I get *** NotRegistered: u'pipeline.tasks.sayhello' when I try to execute another my task res = sayhello.delay('trex'). How to add tasks correctly? The error full message: [2016-11-11 10:56:09,870: ERROR/MainProcess] Received unregistered task of type u'pipeline.tasks.sayhello'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[["tiger"], {}, {"chord": null, "callbacks": null, "errbacks": null, "chain": null}]' (84b) Traceback (most recent call last): File "/home/trex/Development/Sirius/new/rocket/rocket-venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 549, in on_task_received strategy = strategies[type_] KeyError: u'pipeline.tasks.sayhello' Django version 1.9.7 Celery version: celery==4.0.0 django-celery==3.1.17 Django project dir tree: rocket βββ etl β βββ etl β β βββ celery.py β β βββ __init__.py β β βββ settings β β β βββ base.py β β β βββ dev.py β β β βββ __init__.py β β β βββ production.py β β β βββ test.py β β βββ urls.py β β βββ wsgi.py β βββ manage.py β βββ pipeline β β¦ -
Django migrations. How to check if table exists in migrations?
I'm currently working on app built on Django 1.8 and Postgres. This app is installed in several environments, in some of them there old tables in DB from which i need to delete records. I wrote migration with following SQL query: IF EXISTS ( SELECT relname FROM pg_class WHERE relname=tablename ) THEN DELETE FROM tablename END IF; But Django throws error at this query: django.db.utils.ProgrammingError: syntax error at or near "IF" Can i somehow check, in migration, that table exists, and only then execute query, like DROP FROM tablename ? -
Django vs Ruby on rails vs php framework
Hello i want to start with web development but don't know which one is better .I also don't have any prior knowledge except basic python and HTML also i slightly prefer python as it is simple and used in data analysis -
Django: How can I use a variable inside an if statement in the template?
My views.py hands over a variable called "preSelect" that contains a Integer value. Inside the template I want to use that Integer in an If statement to check if the current for loop counter is less equal or greater than than my value. {% if forloop.counter <= {{ preSelect }} %} <td><input type="checkbox" name="checks" id="1" value={{ row.0 }} checked/></td> {% else %} <td><input type="checkbox" name="checks" id="1" value={{ row.0 }} /></td> {% endif %} This however returns me the following error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 1.10.2 Python Version: 2.7.11 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testsetcreation'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template D:\Django\testsetcreation\templates\testsetcreation\testsetView.html, error at line 61 Could not parse the remainder: '{{' from '{{' 51 : Comment 52 : SW Version 53 : HW Version 54 : ABP 55 : Project 56 : 57 : 58 : 59 : {% for row in rows %} 60 : 61 : {% if forloop.counter <= {{ preSelect }} %} 62 : 63 : {% else %} 64 : 65 : {% endif %} 66 : {{ row.1 }} 67 : {{ row.2 }} 68 : 69 : 70 β¦ -
Refering to related object in ListView
I am trying to create some kind of 'panel control'. I need to manage my objects directly from ListView. I'll show you transparent (I believe) schema what I'm trying to solve. Models class Category(models.Model): cat_name = models.CharField(max_length=120) class Product(models.Model): category = models.ForeignKey(Category) prod_name = models.CharField(max_length=120) Views class CategoryListView(ListView): model = Category def get_context_data(self, *args, **kwargs): context = super(CategoryListView, self).get_context_data(*args, **kwargs) # two class based forms created for models context['form_category'] = CategoryForm() context['form_product'] = ProductForm() return context def post(self, request, *args, **kwargs): form_category = CategoryForm(request.POST or None) if form_category.is_valid(): new_category = form_category.save(commit=False) new_category.save() return redirect('category_list') return Http404 templates I use two modal window to open my forms which I added to my context views <button>Modal btton opens product form</button> {% for category in object_list %} <div class="panel"> <div class="panel-heading"> <h3>{{ category.cat_name}}</h3> <button>Modal btn opens product form</button> </div> <div class="panel-body"> <ul> {% for product in category.product_set.all %} <li> <p>{{ product.prod_name }}<p> <span><a href="" class="btn btn-default">Delete</a></span> {% endfor %} </ul> </div> </div> {% endfor %} <form action="." method="POST">{%csrf_token%} {{ form_category.as_p }} <input type="submit" value="add category"> </form> <form action="." method="POST">{%csrf_token%} {{ form_product.as_p }} <input type="submit" value="add product"> </form> For first form (CategoryForm) it's working fine because whole page refers to that (model = Category). β¦ -
What to do in settings.py file to use @cache_control?
I am using @cache_control(no_cache=True, must_revalidate=True) but i don't know what to do in settings.py so that it goes into running mode. -
Displaying all table data relating to the filter
I am using Management commands to display a result from a table i have got it to work to display the PK and the name of the customer relating to that job. How would i go about showing all the data in that table row. Example, right now i get returning $ [<Job: 36172 - Customer Name Example>] there are other columns in the table that can be returned but how do i do this? class Command(BaseCommand): # Show this when the user types help help = "My test command" # A command must define handle() def handle(self, *args, **options): Job_set = Job.objects.all().filter(serial_no = 66666) self.stdout.write(Job_set, ending='') def __str__(self): return self.SLA -
python parse prints only first line from a list
I have a list accommodation_dict it return to only the first line i don't know what's the problem accommodation_list = groupby(obj.accomodations.all(), lambda x: x.get_accommodation_level_display()) if accommodation_list: accommodation_dict = OrderedDict() for level, accomodations in accommodation_list: accommodation_dict[level] = OrderedDict() accommodation_dict[level]['name'] = level accommodation_dict[level]['ceiling'] = dict(Counter([a.get_ceiling_display() for a in list(accomodations)])) accommodation_dict[level]['floor'] = dict(Counter([a.get_floor_covering_display() for a in (accomodations)])) accommodation_dict[level]['data'] = dict(Counter([a.get_accommodation_display() for a in list(accomodations)])) accommodation_dict[level]['walls'] = dict(Counter([a.get_bathroom_walls_display() for a in list(accomodations)])) pprint (accommodation_dict) this is the console: OrderedDict([(u'Ground Level', OrderedDict([(u'name', u'Ground Level'), (u'ceiling', {'': 1, u'Plastered Ceiling, Suspended Ceiling Panel, Decorative Cornices': 1, u'Coffered Ceiling': 1}), (u'floor', {}), (u'data', {}), (u'walls', {})]))]) -
Jquery Datetimepicker to Python Datetime
I have bellow Jquery Datetimepicker html: <input type="text" name="datetime" id="datetime"> js: $( "#datetime" ).datetimepicker({ controlType: 'select', oneLine: true, timeFormat: 'hh:mm tt' }); im sending the date as AJAX POST request to django: const starts = $('#datetime').val(); $.ajax({ type: 'POST', url: '/booking/new/', data: { starts: starts, }, }; in django i get the value: if request.method == 'POST': starts = request.POST.get('starts') object.starts = datetime.strptime(starts, '%x %I:%M %p') I get the following error: ValueError: time data '11/12/2016 12:00 am' does not match format '%x %I:%M %p' I tried different formats but i can't find the correct one. Can i produce the format from the string value some how? -
How to display user's fb profile pic in another project using django
Working on django project in which i have to implement facebook login functionality, i have implemented fb login successfully, but now what i need to do is to upload user's fb image in my proejct, i got user's fb image url using this:- url = 'http://graph.facebook.com/{0}/picture'.format(request.POST['id']) and got this url finally http://graph.facebook.com/1209634319115496/picture When i run above url in browser if displays user's fb profile pic, I want to know that should i upload this pic in my project's directory or should i save this url in database and run directly this url in <img src="this url" > so that every time if user changes its profile pic in fb, it will also reflect on my project. Or if i should upload this pic in my project's directory, then how to upload image in django directory using url. -
Django how to achieve SaveAs option in CBV(Update View)
I'm a newbie with Django. I observed save_as option on Dajango modelAdmin. I would like to implement similar solution on one of my view. I am currently using Django CBV(UpdateView) to edit an entry, i want to give an option to SaveAs as well, is there a easy way to achieve this? Please note, i did look for the solution around web and i did not get solution, infact i am not sure what should be the approach to achieve this. I found this thread on SO, but this was more on editing the actual admin view. I do not want to play with admin view. Below is the existing updateView i have, I would like to change it to have Save_as option as well. The view is lengthy because of it has formset. class RunConfigUpdateView(LoginRequiredMixin, UpdateView): model = RunConfig form_class = RunConfigForm template_name_suffix = '_update_form' #success_url = 'success/' def get_success_url(self): return reverse('runconfig-detail', kwargs={'pk':self.object.pk}) def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) DSJobs_form = DSJobsFormSet(instance = self.object) return self.render_to_response( self.get_context_data(form=form, DSJobs_form=DSJobs_form, )) def post(self, request, *args, **kwargs): """ β¦ -
Cant run application using mod_wsgi
We been using Django 1.6 & recently upgraded to Django 1.8. We are running application behide apache using mod_wsgi. Getting following exception : [Fri Nov 11 09:21:55.551697 2016] [:info] [pid 18966] [client 10.133.213.15:49285] mod_wsgi (pid=18966, process='', application='localhost|/ui'): Loading WSGI script '/usr/myapp/lib/python2.7/site-packages/myapp/ui/wsgi.py'. [Fri Nov 11 09:21:55.993652 2016] [:error] [pid 18966] [client 10.133.213.15:49285] mod_wsgi (pid=18966): Exception occurred processing WSGI script '/usr/myapp/lib/python2.7/site-packages/myapp/ui/wsgi.py'. [Fri Nov 11 09:21:55.993798 2016] [:error] [pid 18966] [client 10.133.213.15:49285] Traceback (most recent call last): [Fri Nov 11 09:21:55.993882 2016] [:error] [pid 18966] [client 10.133.213.15:49285] File "/usr/myapp/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ [Fri Nov 11 09:21:55.994275 2016] [:error] [pid 18966] [client 10.133.213.15:49285] self.load_middleware() [Fri Nov 11 09:21:55.994328 2016] [:error] [pid 18966] [client 10.133.213.15:49285] File "/usr/myapp/lib/python2.7/site-packages/django/core/handlers/base.py", line 52, in load_middleware [Fri Nov 11 09:21:55.994610 2016] [:error] [pid 18966] [client 10.133.213.15:49285] mw_instance = mw_class() [Fri Nov 11 09:21:55.994659 2016] [:error] [pid 18966] [client 10.133.213.15:49285] File "/usr/myapp/lib/python2.7/site-packages/django/middleware/locale.py", line 24, in __init__ [Fri Nov 11 09:21:55.994845 2016] [:error] [pid 18966] [client 10.133.213.15:49285] for url_pattern in get_resolver(None).url_patterns: [Fri Nov 11 09:21:55.994908 2016] [:error] [pid 18966] [client 10.133.213.15:49285] File "/usr/myapp/lib/python2.7/site-packages/django/core/urlresolvers.py", line 402, in url_patterns [Fri Nov 11 09:21:55.995220 2016] [:error] [pid 18966] [client 10.133.213.15:49285] patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) [Fri Nov 11 09:21:55.995284 2016] [:error] [pid 18966] [client β¦