Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to install Psycopg2 for python3 on Ubuntu16.04
I have run sudo apt-get install python3-dev and the up-to-date pip. But when I ran pip install psycopg2, I got this error: Collecting psycopg2 Using cached psycopg2-2.7.1-cp27-cp27mu-manylinux1_x86_64.whl Installing collected packages: psycopg2 Exception: Traceback (most recent call last): File "/home/flint1025/.local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/flint1025/.local/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/flint1025/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/flint1025/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/flint1025/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/flint1025/.local/lib/python2.7/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/flint1025/.local/lib/python2.7/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/flint1025/.local/lib/python2.7/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/psycopg2-2.7.1.dist-info' Then after searching, some solution indicates I should change the ownership of the directory. So I tried chown -R flint1025:27 /usr/local/lib/python2.7/dist-packages/psycopg2-2.7.1.dist-info but got this error: chown: cannot access '/usr/local/lib/python2.7/dist-packages/psycopg2-2.7.1.dist-info': No such file or directory What should I do next? -
Pre install Django for learning
Is there any site which has tutorial for Django . Also wanted to run the Django code the way I can run Python code in www.tutorialspoint.com. Tutorialpoint has Django tutorial but I have to install Django. -
Django searching function issue
I tried implement searching function in my app , but I've got the error it's call typeError .I add the picture of this error views.py from django.shortcuts import render from .models import Games,Game_detail,Order from django.shortcuts import render,get_object_or_404,redirect from django.views.generic import ListView,DetailView,CreateView from django.db.models import Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger class IndexView(ListView): template_name ='games/list.html' context_object_name = 'all_games' model = Games def get_queryset(self,request): query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(name__icontains=query)| Q(platform__icontains=query)| Q(genre__icontains=query) | Q(language__icontains=query) ).distinct() return Games.objects.all() list.html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity=" sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title>Page Title</title> </head> <body> </body> </html> <form method='GET' action=''> <input type='text' name='q' placeholder='Wyszukaj' value='{{ request.GET.q }}'/> <input type='submit'class="btn btn-default" value='Szukaj' /> </form> <table class="table table-striped"> <thead> <tr> <th>Nazwa</th> </th></th> <th>Platforma</th> <th>Gatunek</th> <th>Język</th> </tr> </thead> <tbody> {% for obj in object_list%} <tr> <td><a href ='{%url "detail" pk=obj.pk%}'>{{obj.name}}</a></td> <td>{{obj.platform}}</td> <td>{{obj.genre}}</td> <td>{{obj.language}}</td> </tr> {% endfor %} </tbody> </table> Model.py from django.db import models class Games(models.Model): name = models.CharField(max_length=250) platform = models.CharField(max_length=500) genre = models.CharField(max_length=100) language = models.CharField(max_length=100) image = models.ImageField(upload_to='Images_game',default='' ) # def __str__ (self): # return self.Name class Game_detail(models.Model): game = models.ForeignKey(Games,on_delete=models.CASCADE) subcryption = models.TextField() publisher = models.CharField(max_length=250) date_of_publish = models.DateField() class Order(models.Model): person_name = models.CharField(max_length=24) person_surname = models.CharField(max_length=24) street = models.CharField(max_length=45) … -
Can we custom django admin to manage big data of m2m relationship in better way?
I have two model A and B and they have M2M relationship, but model B have huge number of records,I need pick some of them by filter,sort or search in some fields of model B for that I can add relationship between them and a certain model A, so I want to find a better way to manage M2M relationship in django admin, but I found existing way can not meet my expectations,whether model inline, raw_id_fields, or filter_horizontal ... Finally I found change list in django admin is a good module, can we merge this module into django admin change page for manage M2M relationship?By this,we can filter, sort or search them and bulk operation on M2M relationship. Please help me, thanks. -
Implementing text editing for comments
I am creating a website with Django and have some part where users can insert text that can be viewed by others. I now want to implement text formatting as an option for the user. For a number of reasons I want to try and create my own editor with its own tags, e.g. [strike] [/strike] and as such am looking for documentation regarding this topic. Does anyone know of any good resources regarding design patterns / techniques for these type of concepts. I have been frantically searching but my problem is I don't know the generic name for this topic. I keep running into wysiwyg editors and markdown, which so far only provide me with information on implementing existing solutions. -
how to perform database operations on single database using django and falcon
I am thinking of creating a project for which I chose 2 python frameworks, django and falcon. I will be using Falcon to build APIs and Django for other operations.I don't understand, how to manage database operations in both the frameworks which will be accessing single database(mysql database). My plan is to create tables using Django models into the database, but how about accessing the database values in falcon. I am not much aware about sqlalchemy. Thanks in advance. -
How to migrate from django_tables2 to js datatables?
There are many different html tables in our project. Those tables structure is quite difficult - they have own templates, templatecolumns, buttons inside, images etc. I'm looking for a most simple way how to make those tables act like datatables or migrate them to datatables so pagination, searching and other things doesn't require refresh. Do you have any ideas? This is an example of the table: class ProductsTable(tables.Table): batch_action = tables.columns.CheckBoxColumn(accessor='product.pk', orderable=False, verbose_name=_('')) category = tables.columns.TemplateColumn("""<div class="panel panel-default"> <div class="panel-heading" style='font-size: small'>{{ record.product.category }}</div> <div class="panel-body"><img src='{{ record.product.category.image.url }}' style='max-width: 80px; max-height: 80px'></div> </div>""", accessor='category') name = tables.columns.Column(accessor='product.name', verbose_name=_('Product name')) code = tables.columns.Column(accessor='product.code') brand = tables.columns.Column(accessor='product.brand') our_price = tables.columns.Column(accessor='product.our_original_price') last_min = tables.columns.Column(accessor='last_min_eur',verbose_name=_('MIN')) last_max = tables.columns.Column(accessor='last_max_eur',verbose_name=_('MAX')) last_avg = tables.columns.Column(accessor='last_avg_eur', verbose_name=_('AVG')) last_med = tables.columns.Column(accessor='last_med_eur',verbose_name=_('MED')) ... ... is_active = tables.columns.TemplateColumn( """<input type="checkbox" class="active_toggle" data-toggle="toggle" data-style="ios" data-offstyle="danger" data-onstyle="success" data-size="small" data-on="Active" data-off="Inactive" data-id= "{{ record.product.id }}" name="is_active" value="True" {% if record.product.active %} checked {% else %} {%endif%}>""", accessor='product.active', verbose_name=_('Scanning frequency')) action = tables.columns.TemplateColumn( template_name="productapp/includes/tables/products_table_action_template.html", ) class Meta: fields = ('batch_action', 'category', 'code', 'name', 'brand', 'our_price', 'last_scanning_datetime', 'last_min', 'last_max','last_avg', 'last_med', 'urls_count', 'is_active', 'frequency', 'action') attrs = {'class': 'table table-hover table-vcenter text-center'} empty_text = _("You haven\'t added any products yet") def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') … -
Django 1.9 broken redirect after custom 404 page
On Django 1.9 multilingual site domain.com/ used to redirect to domain.com/en/ automatically. Now, when I put a custom 404.html in top level templates dir, Django no longer redirects to the language: domain.com/ throws server error 500 instead of redirecting to domain.com/en/ How keep custom 404 error page and get no server error 500? -
Redirect after search Django
Hi i create autocomplete seacrh Javascript jQuery(function() { $("#id_input").on('keyup', function(){ var value = $(this).val(); $.ajax({ url: "{% url 'ajax_autocomplete' %}", data: { 'search': value }, dataType: 'json', success: function (data) { list = data.list; $("#id_input").autocomplete({ source: list, minLength: 3 }); } }); }); }); View: def autocomplete_search(request): if request.is_ajax(): game = None try: game = Game.objects.get(name=request.GET.get('search', None)) except: pass if game is not None: result = redirect('games') else: queryset = Game.objects.filter(name__startswith=request.GET.get('search', None)) list = [] for i in queryset: list.append(i.name) data = { 'list': list, } result = JsonResponse(data) return result But it didn't redirect when the game is not None it just response the page to ajax request. But i want to stop the request when the game != None and load the page i need. What is wrong? -
I am trying to deploy my first django app on heroku and getting error a pre-receive hook declined
I have unsettling the buildpacks but it didn't work and I do have requirements.txt and procfile as well as virtual env. (deploy) C:\Users\Samar\Desktop\deploy\blog>git push heroku master Counting objects: 127, done. Delta compression using up to 4 threads. Compressing objects: 100% (122/122), done. Writing objects: 100% (127/127), 45.25 KiB | 0 bytes/s, done. Total 127 (delta 47), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing Python 3.6.0 remote: -----> Installing pip remote: -----> Installing requirements with pip remote:/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/bin/steps/pip-install: line 5: /app/.heroku/python/bin/pip: No such file or directory remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to trueblog. remote:To https://git.heroku.com/trueblog.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/trueblog.git' -
from imagekit.models import ImageSpecField ImportError: No module named 'imagekit.models'
Django ==1.8.6. i Have installe pip install imagekit. imagekit==1.0.6. modells.py import PIL from django.db import models from PIL import Image from django.contrib.auth.models import User from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFit, Adjust,ResizeToFill the wrote model names. when i wanted to migrate the cmd showed me an error: from imagekit.models import ImageSpecField ImportError: No module named 'imagekit.models' -
Unable to use CreateView.as_view in django
I'm new to Django and trying to use CBV to generate a form for my 'Project' model. When I use the CreateView.as_view(...) in urls.py it gives the following error. Exception Type: ImproperlyConfigured Exception Value: Using ModelFormMixin (base class of CreateView) without the 'fields' attribute is prohibited. I'm listing the full code related to this view. urls.py url(r'^create-project/$', CreateView.as_view(model=Project, template_name='en/public/create_project.html', success_url='index'), name='create_project') create_project.py class Form_project_create(forms.Form): class Meta: model = Project fields = '__all__' I cannot figure our what's wrong in this code. Can anyone help? -
Sessions on Django
Could you please help to understand. I have enable the sessions on my site, like : if request.method == 'GET': if request.session.test_cookie_worked(): request.session.delete_test_cookie() sesion_count += 1 else: session_count request.session.set_test_cookie() It's wokring. But how i can do this to each page? For example I have some page id number and it will create this cookie due this number. Next page will have different cookie because new id and so on. But principe the same. Thanks, all for the help. -
How to get the line number where error occurred instead of line number from where error logged in Django
I am using logging in my django project to log errors. However whenever any error occurs at any line, the line number in logs is where the error was logged and not where the error occured. For example in below code if error occured at 3rd line (code to get data line 1) then in logs line number will be printed as 7 where logging happened. def get_gender(): try: # code to get data line 1 # code to get data line 2 # return data dictionary except Exception as e: logging.getLogger("error_logger").error(repr(e)) return {} Below is the code of formatted in logging settings file. formatters':{ 'large':{ 'format':'%(asctime)s %(levelname)s %(process)d %(pathname)s '+ '%(funcName)s %(lineno)d %(message)s ' }, Error message example: 2017-05-06 15:20:07,065 ERROR 7000 /home/USER/ASonline/common/services/category_services.py get_gender 7 IndexError('list index out of range',) How can I get the line number where error occurred instead of line number from where error logged. -
Why is my request.post object not mutable after calling .copy()?
I have an HTML view of a ModelForm where I'm trying to take a separate user input called scanner_input, run some code on it, and then replace request.post['product_id'] with the result from the code I just ran. Everywhere I look, it says the same thing, that request.post objects can be made mutable by using .copy() and yet I get the following error message: 'SerialInstanceForm' object does not support item assignment The error occurs in this line from my view: post.product_id = scanner_input_list[i] Here's my view: def SerialMulti(request): if request.method == "POST": form = SerialInstanceForm(request.POST) if form.is_valid(): scanner_input = request.POST['scanner_input'] scanner_input_list = scanner_input.splitlines() for i in range(0, len(scanner_input_list)): post = SerialInstanceForm(request.POST.copy()) post['product_id'] = scanner_input_list[i] post.save() return render(request, 'serial_multi.html', {'form': form}) else: form = SerialInstanceForm() return render(request, 'serial_multi.html', {'form': form}) My model: class ProductSerialInstance(models.Model): STATUS_CHOICES = ( ('in_inventory', 'In Stock'), ('given_out', 'Given Out'), ('repair', 'Repair') ) name = models.ForeignKey(ProductSerial) employee = models.ForeignKey(Employee, blank=True, null=True) it_dep = models.ForeignKey(ItDep) product_id = models.CharField(max_length=50) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __unicode__(self): return self.name And my form: class SerialInstanceForm(forms.ModelForm): # duplications = forms.IntegerField() class Meta: model = ProductSerialInstance fields = ['name','employee','it_dep','status'] -
Django form shows No File Chosen
My question is, why does the form show No File Chosen against the file fields even when a file is loaded (and how do I correct this)? I have the following form (the relevant bits being the FileInput widgets): class StudentForm(forms.ModelForm): class Meta: model = Student exclude = ['id',] widgets = { 'user' : forms.HiddenInput(), 'first_name' : forms.TextInput(attrs={'class' : 'form-control'}), 'last_name' : forms.TextInput(attrs={'class' : 'form-control'}), 'email' : forms.EmailInput(attrs={'class' : 'form-control'}), 'majors' : forms.TextInput(attrs={'class' : 'form-control'}), 'university' : forms.TextInput(attrs={'class' : 'form-control'}), 'grad_year' : forms.TextInput(attrs={'class' : 'form-control', 'type' : 'number'}), 'resume' : forms.FileInput(attrs={'class' : 'form-control'}), 'transcript' : forms.FileInput(attrs={'class' : 'form-control'}), 'git_link' : forms.URLInput(attrs={'class' : 'form-control'}), 'linkedin_link' : forms.URLInput(attrs={'class' : 'form-control'}), } My view to save/display for is : student = Student.objects.get(user=request.user) form = StudentForm(instance=student) if request.method == 'POST': form = StudentForm(request.POST, request.FILES, instance=student) if form.is_valid(): form.save() messages.success(request, 'Profile successfully updated.') variables['form'] = form return render (request, 'app/profile.html', variables) And I am rendering it through HTML like this: <form method='post' action="{% url 'add-profile' %}" enctype="multipart/form-data" data-confirm="Please confirm you want to save the current data. This will overright all previous data."> {% csrf_token %} <table class="table"> {{form.as_table}} </table> <button type="submit" class="btn btn-primary" >Update Profile</button> </form> My question is, why does the form show No … -
Access Django variabel on a page from separate JavaScript file.
I have searched SO regarding this topic without much success and I hope this is not a duplicate after you go through the entire problem description. Let me say I have a variable countryList, a JSON text, returned from Django view context to the template and I inserted it directly into the body: <body> {% if countryList %} [Blocks for other codes] {% endif %} </body> What I found is that if I want to access the content/value of countryList from a JavaScript(JS), I have to place this JS code inside the [Blocks for other codes]. In this way, I can directly access the content via, for example var cList = '{{ countryList }}'; inside a jQuery(document).ready() function. However, I attempt to access the same variable from an external JavaScript file (country.js) loaded to this HTML in the following way <script type="text/javascript" src="{% static 'country.js' %}"></script> <body> {% if countryList %} [Blocks for other codes] {% endif %} </body> then using var cList = '{{ countryList }}'; inside this file only gives me a string variable {{ countryList }}. There is no issue with Django settings and the country.js can be loaded properly. This makes me wondering if it has … -
setUp function being called multiple times in django TestCase
I am using django unit tests for the first time. Following is a sized down version of my code. My assumption was that setUp function would be called once for each TestCase class. But when I run the python manage.py test command, setUp function is called once for each of the test function. Am I doing something wrong or is there something wrong in my assumption? class SampleTest(TestCase): """ This class assumes an archiver setup with add available at localhost:9101 query available at localhost:9105 """ def __init__(self, *args, **kwargs): self.init_var = False super(SampleTest, self).__init__(*args, **kwargs) def setUp(self): """""" print "setup called" self.init_var = True def test_1(self): print "Test 1", self.init_var def test_2(self): print "Test 2", self.init_var -
Object has no attribute 'distance' - GeoDjango
I am referring the answer in the question listed below as I am trying to run a query that gets the closest object to a given point. How to return a record with the lowest distance from a point using geodjango? In my view I am passing in a Zipcode and using GeoPy to get the location and lat/long. from django.contrib.gis.geos import * from django.contrib.gis.measure import D from geopy.geocoders import Nominatim geolocator = Nominatim() zipcode = self.request.query_params.get('zipcode', None) distance_m = 20000 if zipcode is not None: location = geolocator.geocode(zipcode, timeout=None) origin = Point((location.latitude, location.longitude)) queryset = Chapter.objects.filter(location__distance_lte=(origin, D(m=distance_m))).distance(origin).order_by('distance')[:1][0] return queryset I get the following error: AttributeError: 'QuerySet' object has no attribute 'distance' -
How to run Django and node.js app on same dyno in Heroku?
I have an Django app deployed on Heroku, but due to some requirement I had to create a basic nodejs file and I wish to run it on the same dyno. I googled for solutions but couldnt come up with much apart from the blogs, which all are same https://blog.heroku.com/heroku-django-node So, I did install buildpack mentioned, and my profiles are: Procfile: web: bin/runsvdir-dyno Profile.web django: gunicorn exampledjangoapp.wsgi:application --bind 127.0.0.1:$DJANGO_PORT node: node node_app/app.js I have created NODE_ENV and DJANGO_PORT configs in Heroku too. Here is what I see in logs: Error: listen EADDRINUSE :::56842 2017-05-05T21:02:15.241005+00:00 app[web.1]: at Object.exports._errnoException (util.js:1022:11) 2017-05-05T21:02:15.241006+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:1045:20) 2017-05-05T21:02:15.241007+00:00 app[web.1]: at Server._listen2 (net.js:1259:14) 2017-05-05T21:02:15.241007+00:00 app[web.1]: at listen (net.js:1295:10) 2017-05-05T21:02:15.241008+00:00 app[web.1]: at Server.listen (net.js:1391:5) 2017-05-05T21:02:15.241009+00:00 app[web.1]: at Object.<anonymous> (/app/node_app/app.js:15:4) 2017-05-05T21:02:15.241009+00:00 app[web.1]: at Module._compile (module.js:570:32) 2017-05-05T21:02:15.241010+00:00 app[web.1]: at Object.Module._extensions..js (module.js:579:10) 2017-05-05T21:02:15.241011+00:00 app[web.1]: at Module.load (module.js:487:32) 2017-05-05T21:02:15.241011+00:00 app[web.1]: at tryModuleLoad (module.js:446:12) 2017-05-05T21:02:15.285970+00:00 app[web.1]: buildpack=runit ps=node at=exit status=1 waitpid_lsb=0 2017-05-05T21:02:15.305915+00:00 app[web.1]: buildpack=runit ps=node at=start 2017-05-05T21:02:16.126572+00:00 app[web.1]: events.js:160 2017-05-05T21:02:16.126582+00:00 app[web.1]: throw er; // Unhandled 'error' event 2017-05-05T21:02:16.126583+00:00 app[web.1]: ^ 2017-05-05T21:02:16.126584+00:00 app[web.1]: 2017-05-05T21:02:16.126584+00:00 app[web.1]: Error: listen EADDRINUSE :::56842 2017-05-05T21:02:16.126585+00:00 app[web.1]: at Object.exports._errnoException (util.js:1022:11) 2017-05-05T21:02:16.126586+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:1045:20) 2017-05-05T21:02:16.126587+00:00 app[web.1]: at Server._listen2 (net.js:1259:14) 2017-05-05T21:02:16.126587+00:00 app[web.1]: at listen (net.js:1295:10) 2017-05-05T21:02:16.126588+00:00 app[web.1]: at … -
Django - Page not scrolling down when importing jquery
Basically, if I import jquery as it follows: <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> I happen to observe two different scenarios: If I use my Django Template, I can no longer scroll down the page in the mousepad, but only with the scrollbar. If I delete the line in which I import jquery, I can scroll down again! If I decide to view the source code generated from the template, copy and paste it entirely into a new html file, if I open it in my browser, now I can scroll down with my mousepad/arrows. What on Earth can be such reason for that? What am I missing out? -
Write custom code or use many libraries in Django
I am creating a web site in Django and there is a library for almost any problem I have. My question is: Is better to use many libraries or write custom code and use less libraries as possible? -
table does not created properly within a function
I have a table like this below, <table> <div id="boards"></div> </table> And I have a function like this, function drawBoard(item, index) { boards = document.getElementById("boards"); boards.innerHTML = boards.innerHTML + "<tr><td><div id=\x22Board" + index + "\x22></div></td></tr>"; } Also, with {{winners}} as an array with 3 entries var winners = {{winners}}; winners.forEach(drawBoard); However, the table thus generated have got only 1 row instead of 3. Looks like the td and tr are ignored somehow. Any idea? -
Django Many-To-Many relationships symmetric different types
In django I have two models Post and Tag. I have a ManyToManyField on each of them refering to the other. However, when I add a new Post and supply some tags, only the post -> tag relationship is recorded in the database. I have to manully add the tag -> post relationship. Is there a way to get django to do this automatically? -
Ajax function , or ) expected
So I'm following a tutorial trying to implement an Ajax search form on my site, my Ajax.js looks as follows: $(funcrion () { $('#search').keyup(function () { $.ajax({ type: "POST", url: "/cooks/search/", data: { 'search_text': $('#search').val(), 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); From what I understood the first bit is to make sure the search function doesn't run before the page loads. I'm getting a ", or ) expected " error although the syntax seems to match the tutorials. mind that I have an on load function on my base.html (don't know if that's related) $( window ).on( "load", function() { console.log( "window loaded" ); }); What am I missing here? ps. I don't want massive lines of code on my HTML for the ajax so I rather have a separate js file for that