Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-simple-menu integration with bootstrap
I am trying to integrate django third-party app with a bootstrap template. This third party app provides dynamically generated menu for website. This app is called django-simple-menu. Following is a code to access the menu from Django template and it works well. base.html {% load menu %}{% generate_menu %} <!doctype html> <html> <head> <title>{% block title %}No title set{% endblock %}</title> {% block headextra %}{% endblock %} </head> <body> <h1>User Menu</h1> {% with menu=menus.user %}{% include "menu.html" %}{% endwith %} <h1>Main Menu</h1> {% with menu=menus.main %}{% include "menu.html" %}{% endwith %} <h1>Example Menu</h1> {% with menu=menus.ExampleMenu %}{% include "menu.html" %}{% endwith %} <hr> {% block content %} {% endblock %} </body> </html> menu.html <ul> {% for item in menu %} {% if item.separator %}<li>------------</li>{% endif %} <li><a href="{{ item.url }}">{{ item.title }}</a></li> {% for child in item.children %} <li><a href="{{ child.url }}">{{ child.title }}</a></li> {% endfor %} <br> <br> {% endfor %} </ul> I am trying to integrate it with following place in bootstrap where it provide a static navigation bar. I want it dynamically populated. Any help would be great.I am not familiar with CSS and very little experience with HTML and JS. <!-- Static navbar --> <nav class="navbar … -
Admin panel. Show rows of table where user pk is
I have an extended User with the model UserProfile. And I can see the UserProfile attributes in the admin panel just fine. And I have transaction model which has a foreign key User. So what I'd like, and which I don't know how to approach is. How can I in the admin panel with the UserProfile in User show a list of all the transaction objects which belong to that User? from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class investment_point(models.Model): name = models.CharField(primary_key=True, max_length=100, default='Calypso') class transaction(models.Model): amount = models.IntegerField() investment_point = models.ForeignKey(investment_point, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.IntegerField(default=0) ingameName = models.CharField(max_length=50, default='NotSet') def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) -
Postgresql Database Backup for Django Project
I am trying to use the following command in my django project to backup my database: sudo -u postgres -i pg_dump -c -Fc dbname > outdb_name.backup Here is my code: os.system('sudo -u postgres -i pg_dump -c -Fc dbname > outdb_name.backup') But if I run the project, it stops asking the sudo password. Well, I found the solution as below- os.system('echo mypass | sudo -S -u postgres -i pg_dump -c -Fc dbname > outdb_name.backup') In this case, If I run the project using python manage.py runserer it works fine. But If I use nginx then I am getting incorrect password attempt. How can I solve the problem. Actually I need the database backing up and I want if there is any other better solutions. -
Django: How to rollback (@transaction.atomic) without raising exception?
I'm using Django's command to perform some tasks involving database manipulation: class SomeCommand(BaseCommand): @transaction.atomic def handle(self, *args, **options): # Some stuff on the database If an exception is thrown during execution of my program, @transaction.atomic guarantees rollback. Can I force this behavior without throwing exception? Something like: # Doing some stuff, changing objects if some_condition: # ABANDON ALL CHANGES AND RETURN -
travic-ci build failing with django project
I am trying to setup travis-ci for the first time with a django project of mine and I am getting this trace in the travis output... 0.17s$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/python/2.7.9/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named py The command "python manage.py migrate" exited with 1. Now I can see that it is looking for a module named py instead of running the manage.py file but I don't see why that would happen, and I have found numerous resources online that have stated to run a command like that in the travi.yml file (heres one: https://gist.github.com/ndarville/3625246) here is my travis.yml file: script: - python manage.py migrate - python manage.py test Now before I go running off and trying to get it to run by installing another module like tox or nose I would like to know if it is possible to do it this why … -
Exception Handling in Django - Is this necessary?
Is this: @login_required def remove_photo(request): if request.is_ajax(): try: BirdPhoto.objects.get( pk = request.POST.get('image_id') ).delete() except Exception: raise Exception return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json') better than this: @login_required def remove_photo(request): if request.is_ajax(): BirdPhoto.objects.get( pk = request.POST.get('image_id') ).delete() return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json') ? I have to admit, I don't pay as much attention to error handling and testing as I should. So I just wrote this new function, and I was thinking I should make sure I am handling the errors. Once I kind of got to the basic level of handling errors, I looked at it and said to myself: well sh*t that isn't really even doing anything. It seems to me the 2 functions will act the same way. This is django, so in production environment the server should catch this and just return a general http response. Am I OK leaving it as the 4 line version and instead of the 6 line version? -
How to update load context variable after change in django template via AJAX call?
My Table Items in page customer_items.html: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> <th style="display: none">Item ID</th> <th>Name</th> <th>Supplier Code</th> <th>Location Code</th> <th>Part Number</th> <th>Part Group</th> <th>Unit Price</th> <th>Currency</th> <th style="display: none">Location ID</th> <th style="display: none">Currency ID</th> <th style="display: none;">Line ID</th> <th style="display: none;">UOM</th> <th style="display: none;">Supplier ID</th> <th></th> </tr> </thead> {% if items_list %} <tbody> {% for i in items_list %} <tr class="gradeX" id="{{ i.line_id }}"> <td style="text-align: right; display: none;">{{ i.item_id }}</td> <td style="text-align: left">{{ i.item_name }}</td> <td style="text-align: left">{{ i.supplier_code }}</td> <td style="text-align: left">{{ i.location_code }}</td> <td style="text-align: left">{{ i.part_no }}</td> <td style="text-align: right;">{{ i.part_gp }}</td> <td style="text-align: left">{{ i.sales_price }}</td> <td style="text-align: left;">{{ i.currency }}</td> <td style="text-align: right; display: none;">{{ i.location_id }}</td> <td style="text-align: right; display: none">{{ i.currency_id }}</td> <td style="text-align: right; display: none">{{ i.line_id }}</td> <td style="text-align: right; display: none">{{ i.uom }}</td> <td style="text-align: right; display: none">{{ i.supplier_id }}</td> <td><input type="checkbox" name="choices" id="{{ i.line_id }}" class="call-checkbox" value="{{ i.sales_price }}"></td> </tr> {% endfor %} </tbody> {% endif %} </table> In my main page, I include the customer items page inside it: <div class="adv-table" id="myTable"> {% include 'customer_items.html' %} </div> I used ajax to update items_list after change customer event run: function … -
NoReverseMatch on redirect django
I have a simple form where a user enters some text and on submission an operation is carried out and the results returned to the user. For example the user enters a bunch of text and on submission a page is displayed with the sentence count. views.py from django.core.urlresolvers import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.views.generic import ListView, CreateView, DetailView class CreateEntry(CreateView): model = Entryt fields = ['text'] def form_valid(self, form): return HttpResponseRedirect(reverse('app:result')) class ResultView(DetailView): model = Entryt context_object_name = 'fl' template_name = 'flesch/result.html' def get_queryset(self): return Entryt.objects.get(pk='entryt_id') project url contains this for the app url(r'^flesch/', include('flesch.urls', namespace='app')), app urls.py from django.conf.urls import url from .views import ResultView, CreateEntry urlpatterns = [ url(r'^$', CreateEntry.as_view(), name='create'), url(r'^(?P<pk>[0-9]+)/$', ResultView.as_view(), name='result'), ] error message when a form is submitted NoReverseMatch at /flesch/ Reverse for 'result' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['flesch/(?P<pk>[0-9]+)/$'] Are my on the right path on how to achieve this or how do I fix this? -
Django: is it possible to separate DB writing funcionality?
I want to update DB using Windows Scheduler on a weekly basis. I have the code which extracts the data to be saved as a separate module, so I need to add DB write code there. Is it possible to run it without the server? If not, how to better run a server, make this task only and exit. I write like this now: e = Employee() e.profile_link = ... ... e.save() models.py: from django.db import models class Employee(models.Model): profile_link = models.TextField(primary_key=True) ... -
List object has no attribute split
I am sending a list of sizes from html to the django function $("input[name='size']:checked").each(function() { size.push($(this).val()); }); formdata.append('size[]' , size) $.ajax({ type: "POST", data: formdata, url : "{% url 'data_entry' %}", cache: false, contentType: false, processData: false, success: function(data) { if(data == 'True'){ $('#flash').html("product uploaded successfully") $('#flash').delay(500).fadeIn('normal', function() { $(this).delay(2500).fadeOut(); }); location.reload(); } }, error: function(response, error) { } }); The list Sizes Contains like this 'list' object has no attribute 'split' [u'S,M,L'] Then i am using split it and loop over it like this if sizes: print sizes temp = sizes.split(',') print temp for size in temp: print size But it throws the above error. Why cant i use split on the list above and How can i resolve it? -
Convert Cakephp Query, conditions into Django Query
I am working on a site, It was developed by using Cakephp framework,But now I have to convert it in Django. I am facing problems with some default features of Cakephp and django. This is the code that has been used in cakephp function. if($this->request->is('ajax')){ $data=$this->request->data; switch ($_REQUEST['order'][0]['column']){ case '1' : $orderby= "title"; break ; case '2' : $orderby= "description"; break ; default : $orderby="title"; break; } $dir = $_REQUEST['order'][0]['dir']; if ($_REQUEST['length'] !=-1){ $limit=$_REQUEST['length']; } else{ $limit="all"; } $this->loadModel('CmsPage'); $conditions=array(); $query=$this->CmsPage->find('count',array( 'conditions'=>$conditions ) ); if(!empty($data['title'])) { $title=$this->request->data['title']; $conditions=array_merge($conditions,array('CmsPage.title LIKE'=>'%'.$title.'%')); } if(!empty($data['description'])) { $description=$this->request->data['description']; $conditions=array_merge($conditions,array('CmsPage.description LIKE'=>'%'.$description.'%')); } $iTotalRecords=sizeof($query); $iDisplayLength = intval($_REQUEST['length']); $iDisplayStart = intval($_REQUEST['start']); $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength; $iTotalRecords=$query; $querys = $this->CmsPage->find('all', array( 'conditions' => $conditions, 'order' => array($orderby=>$dir) ,'limit' => $iDisplayLength, 'offset' => $iDisplayStart )); $iTotalRecords = $this->CmsPage->find('count', array( 'conditions' => $conditions)); $sEcho = intval($_REQUEST['draw']); $records = array(); $records["data"] = array(); $end = $iDisplayStart + $iDisplayLength; $end = $end > $iTotalRecords ? $iTotalRecords : $end; $table_name="CmsPage"; $i=0; foreach($querys as $user) { $id= base64_encode(convert_uuencode($user['CmsPage']['id'])); $actionValues='<a title="Edit" class="btn btn-sm green margin-top-10" href="'.HTTP_ROOT.'admin/cms/edit_cms_page/'.$id.'"> <i class="fa fa-edit"></i> </a>'; $num = ++$i; $records["data"][] = array( '<input class="checkboxes" type="checkbox" value="'.$user['CmsPage']['id'].'">', $num, $user['CmsPage']['title'], $user['CmsPage']['description'] = substr($user['CmsPage']['description'],0,60), $actionValues ); } if (isset($_REQUEST["customActionType"]) && … -
Matching Outputted Image File from View to Template With Django
I am very new to Django and I am stuck with an issue to be able to match an outputted image from function in views.py to template so that the resulted image can be display on the browser as a file image, how is that can be done? My attempt is: in the views.py: return HttpResponse(fig, content_type ="image/png") fig is basically a constructing figure from matplotlib.pyplot which is being tested and run fine in the templates folder, inside of my home.html: <p> before </p> <img scr="{{image.image.url}}">{{ image.image.name }} <p> After</p> But nothing is displayed Thanks a lot in advance -
How do I get the final order total in django-oscar?
I am trying to create a plugin for payment gateway for django-oscar. In that i want to give a checkout button on the django-oscar which will directly take to the user to the payment gateway page. In my plugin how do I get the total order price and also how do I get the order id etc details from the given order or basket? -
Cannot override logout in Django
I'm trying to override the DJango logout doing the following: registration_urls.py urlpatterns = patterns( '', url(r'^activate/complete/$', TemplateView.as_view( template_name='registration/activation_complete.html'), name='registration_activation_complete'), # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to the view # that way it can return a sensible "invalid key" message instead of a # confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', ActivationView.as_view(), name='registration_activate'), url(r'^register/$', FHRegistrationView.as_view(form_class=RegistrationFormUserProfile), name='registration_register'), url(r'^register/complete/$', TemplateView.as_view( template_name='registration/registration_complete.html'), name='registration_complete'), (r'', include('registration.auth_urls')), #url(r'^login/$', views.login(template_name='registration/login.html'),{'APP_ROOT': settings.APP_ROOT}), url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'registration/login.html', 'authentication_form': AuthenticationForm }), url(r'^accounts/logout/$', 'formshare.apps.main.registration_views.LogoutView'), ) registration_views.py ... def LogoutView(request): logout(request) return render(request, "registration/logout.html",{'APP_ROOT': settings.APP_ROOT}) ... But it does not seem to work! The template does not get the variable APP_ROOT Any idea is much appreciated. -
Models, with foreignKey with user. But only when they're added?
How can I make a model which have a "list" field which can hold User objects. But only if I add User objects programmatically or by the admin site. Right now below model automatically adds all User objects to the list. But I want to add them myself. class investment_point(models.Model): name = models.CharField(primary_key=True, max_length=100) usernames = models.ForeignKey(User, on_delete=models.CASCADE) -
How to clone a running virtual machine in opennebula 5.x?
I am using XML-RPC to integrate opennebula 5.x. Which methods in xml-rpc doc to use to clone a vm? Clone a template using template id of running vm using template clone method Template clone and related image will be created. Using the created template id creates a new clone vm using template instantiate method. Is this the correct solution. what is cloning a running vm? -
Stop counting time in django
I've got a problem with take constant value from this function: def get_time_left(self) now = timezone.now() time_left = self.deadline - now return time_left self.deadline is value from model. For example I want to take time_left from 15.00 2.09.2016, save it and use this value in another function, but when I try to do this, the value is always changing... -
How to upload image file from django admin panel ?
I am making a personal website using django 1.10 I want to upload my website logo from admin for why I can edit this in future. So that I have wrote website app and the models of website is : from future import unicode_literals from django.db import models # Create your models here. class Website(models.Model): title = models.CharField(max_length=255) name = models.CharField(max_length=255) logo = models.ImageField(max_length=255, upload_to='images/') def __unicode__(self): return self.name def __str__(self): return self.name Admin panel: But image is not uploaded in media/images folder. Please help me about this issue. -
Django Queryset
I need to do something like this in order to match some objects. This is the best way to do it? Is possible to do it in a faster way? if User.objects.filter(first_name=name, age=age).exists(): user = User.objects.filter(first_name=name, age=age) function_x(user) elif User.objects.filter(full_name__icontains=name, age=age).exists(): user = User.objects.filter(full_name__icontains=name, age=age) function_x(user) -
Show html generated by using json2html at webpage [Django] [Python] ?
Following is my code in view: RESULTS= {} for k in RESULTS_LIST[0].iterkeys(): RESULTS[k] = list(results[k] for results in RESULTS_LIST) RESULTS.pop('_id',None) html_table = json2html.convert(json=RESULTS) return render(request,'homepage.html',{'html_table':html_table} here I am arranging a data fetched from Mongo Db in a JSON named as RESULTS and by using JSON2HTML package, it is successfully generated html table for data given in JSON. To embedd the html table code in a blank division at html page, I am doing: <div>{{html_table}}</div> But it failed to display the table on page. I have tried numerous ways to make it but didn't succeed. Please help me to resolve this issue. if any relevant example, you have done before , then please guide me in a right direction. -
python django: def parameters types are not clear
I have the following code: def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) the render function is defined as: def render(request, template_name, context=None, context_instance=_context_instance_undefined, content_type=None, status=None, current_app=_current_app_undefined, dirs=_dirs_undefined, dictionary=_dictionary_undefined, using=None): .... In the return render(request, 'blog/post_list.html', {'posts': posts}) we see only three parameters assuming rest are using the default values. We use {'posts': posts} for context parameter. So what does context represent as per Django. -
PUT Request fails on field rename
Serializer.py class CategorySerializer(serializers.ModelSerializer) : id = serializers.IntegerField(source='category_id') name = serializers.CharField(source='category_name') class Meta: model = Category fields = ['id', 'name'] Above works fine for the GET but when i run PUT request it goes to fail block views.py for PUT request.method == 'PUT': serializer = CategorySerializer(category, data=request.data) if serializer.is_valid(): serializer.save() response = { 'status': status.HTTP_200_OK, 'message' : "Category Updated", } return HttpResponse(json.dumps(response), content_type='application/json') else : response = { 'status': status.HTTP_400_BAD_REQUEST, 'message' : "Category not found", } return HttpResponse(json.dumps(response), content_type='application/json') And i'm running following curl curl -X PUT http://localhost:8000/api/add-category/4/ -d "category_name=xyz" Response: {"status": 400, "message": "Category not found"} Each time it goes in else part. Experts please help -
Django form queryset=model.objects.all() loads slowly
I have a simple model: class Sheker(models.Model): name = models.CharField(max_length=90) display_name = models.CharField(max_length=90, null=True) search_name = models.CharField(max_length=90, null=True) def __unicode__(self): return self.search_name class Sod(models.Model): name = models.CharField(null=False, blank=False, max_length=100) sheker = models.ManyToManyField(Sheker, blank=True, name='sheker') With a simple form: from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple from rosh.models import * class SodForm(forms.ModelForm): sheker = forms.ModelMultipleChoiceField( queryset=Sheker.objects.all(), widget=FilteredSelectMultiple("sheker", is_stacked=False), required=False ) The model Sheker have more then 12K rows in the db (postgres with geo extensions)- and the problem is that it makes the form to load super slow. Is the problem is queryset=Sheker.objects.all()? How can I make it load faster/cache it or something else to load the page fast (as normal web page). What is the best practice for such issue? -
NGINX 504 Gateway Time-out changing system date
I'm working in a django application with a nginx proxy. In my app, I need to be able to change system date, but nginx always throws a 504 Gateway Time-out because it does not restart the init session time. Anyone can say me how to disable nginx connection timeouts? This is my nginx config file: user www-data; worker_processes 4; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { #Added by Denis fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_connect_timeout 31536000; fastcgi_send_timeout 31536000; fastcgi_read_timeout 31536000; max_execution_time 31536000; proxy_connect_timeout 31536000; proxy_send_timeout 31536000; proxy_read_timeout 31536000; ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 31536000; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/java$ ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } -
Import error:No module named app1.models
In django, i am trying to populate my database from a csv file. with the help of this http://mitchfournier.com/2011/10/11/how-to-import-a-csv-or-tsv-file-into-a-django-model/ tutorial i wrote this code: load_data.py: # Full path and name to your csv file csv_filepathname="Home/Desktop/MyProject/practice/app1/data/link1.csv" # Full path to your django project directory your_djangoproject_home="Home/Desktop/MyProject/practice/" import sys,os sys.path.append('Home/Desktop/MyProject/practice/') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from app1.models import Link import csv dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in dataReader: abc = Link() abc.name = row[0] abc.roll = row[1] abc.save() now, when i run this, i get import error saying no module named app1.models. i cant figure it out. can someone please highlight the mistakes. I'm working on python 2.7 and django 1.6.