Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extracting a song information from a downloaded file
When I download a song in my android phone, the song gets included in my music player along with song name, singer name, movie name and also a song logo. I want to extract the same information for a song downloaded on my laptop. I am making a music web app with django and I need a song's information to be displayed. -
Django - cannot deploy with mod_wsgi in virtualenv with python 3.4
i've been trying for two days and still can't deploy my django proj to apache + mod_wsgi in virtualenv with python3.4. I'm getting Internal Server Error on the web browser. please help~~~ note: i am running mod_wsgi with operating system Apache 2.4.10 in terminal, i ran mod_wsgi-express with the following command: (env3.4)root@X110:/var/www/html/example.com/mysite# mod_wsgi-express start-server --host 192.168.1.110 --port 8000 --working-directory mysite --application-type module mysite.wsgi --user developer --group developer Server URL : http://192.168.1.110:8000/ Server Root : /tmp/mod_wsgi-192.168.1.110:8000:0 Server Conf : /tmp/mod_wsgi-192.168.1.110:8000:0/httpd.conf Error Log File : /tmp/mod_wsgi-192.168.1.110:8000:0/error_log (warn) Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : C.UTF-8 error log: [Thu Nov 10 01:05:11.682936 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] mod_wsgi (pid=4692): Target WSGI script '/tmp/mod_wsgi-192.168.1.110:8000:0/handler.wsgi' cannot be loaded as Python module. [Thu Nov 10 01:05:11.683051 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] mod_wsgi (pid=4692): Exception occurred processing WSGI script '/tmp/mod_wsgi-192.168.1.110:8000:0/handler.wsgi'. [Thu Nov 10 01:05:11.683109 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] Traceback (most recent call last): [Thu Nov 10 01:05:11.683194 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote … -
Django - Migrate ManyToMany to through
I have a model that looks like this: class Assignment(models.Model): """An assignment covers a range of years, has multiple coders and one specific task""" title = models.CharField(blank=True, max_length=100) start_date = models.DateField(default=date.today) end_date = models.DateField(default=date.today) coders = models.ManyToManyField(User, related_name='assignments') I want to change this model (which has data already in production) so that it looks like this: class Assignment(models.Model): """An assignment covers a range of years, has multiple coders and one specific task""" title = models.CharField(blank=True, max_length=100) start_date = models.DateField(default=date.today) end_date = models.DateField(default=date.today) coders = models.ManyToManyField(User, through = 'AssignmentProgress') class AssignmentProgress(models.Model): """The progress a particular coder has made with an assignment""" assignment = models.ForeignKey(Assignment, related_name="assignment_progress") coder = models.ForeignKey(User, related_name="assignment_progress") articles_coded = models.IntegerField(default=0, null=False) progress = models.FloatField(default=0, null=False) From what I have read so far, the solution would be to add a field assignment_coders = models.ManyToManyField(User, through = 'AssignmentProgress') to Assignment and then use a datamigration to copy the info over. I tried that with the following data migration: # -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-11-09 16:31 from __future__ import unicode_literals from django.db import migrations def move_coders(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration … -
Redirect OAuth screen to a new window
I am building a django application which uses OAuth to get Google drive access. However when I run the flow to get the credentials, the OAuth screen opens in another tab which diverts the user to another window. How do I make the OAuth appear in a popup window and close when authentication is done ? flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) I believe the tools.run_flow is the method that calls the OAuth screen in another tab. Thanks ! -
Django- how to add another field to a table displayed in a web page
I am debugging a Django project, and want to display another field from the database in a table on the webpage. The Django HTML for the table as it's currently displayed in the webpage is: <table class="multisection pipeline left"> <tr class="sub-summary"> <th colspan="4"><a href="?detailed_status={{detailed_status}}"><h3 class="p-l-sm">{{detailed_status_str}}</h3></a></th> {% if total_i %}<th>Initial exc VAT: {{total_i|money:"£"}}</th>{% endif %} {% if total_u %}<th>Latest exc VAT: {{total_u|money:"£"}}</th>{% else %} <th></th> {% endif %} </tr> </table> <table class="multisection pipeline left m-b-xl"> <tr class="summary"> <th style="width: 3em;"></th> {% for field in fields %} <th class="text-sm p-l-sm p-t-sm p-b-sm" style="width:{{widths|getval:forloop.counter0}}"> {% if field.1 %} {% if sort == field.0 and not reverse %} <a href="?sort=-{{field.0}}&detailed_status={{detailed_status}}">{{field.0}}</a> {% else %} <a href="?sort={{field.0}}&detailed_status={{detailed_status}}">{{field.0}}</a> {% endif %} {% else %} {{field.0}} {% endif %} </th> {# Make all have the same number of columns (8) #} {% if forloop.last %} {% for i in ',,,,,,,,' %} {% if forloop.counter|add:forloop.parentloop.counter0 < 11 %} <th>&nbsp;</th> {% endif %} {% endfor %} {% if detailed_status == "ds4"|ds %} <th></th> {% endif %} {% endif %} {% endfor %} </tr> {% with user.employee.full_name|is:'Nick Ross' as summary_link %} {% for project in projects %} <tr data-project-id="{{project.id}}" class="{% cycle 'odd' 'even' %}{% if project.office == 2 %} col{% endif … -
Error occured while reading WSGI Handler
I am running a django project using IIS. I am using this tutorial https://www.youtube.com/watch?v=kXbfHtAvubc I followed all the steps. I was able to run the project from shell and now I am using IIS Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\www\syllabi\search_syllabi\wfastcgi.py", line 711, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\www\syllabi\search_syllabi\wfastcgi.py", line 568, in read_wsgi_handler return env, get_wsgi_handler(handler_name) File "C:\www\syllabi\search_syllabi\wfastcgi.py", line 539, in get_wsgi_handler handler = getattr(handler, name) AttributeError: 'module' object has no attribute 'wsgi' StdOut: StdErr: Can some one help me to fix the issue. I tried using django which was installed using pip and from tar file. -
Can not create superuser for Django site - PostgreSQL database- fatal error: password authentication
I am an extreme newbie to Django and using shell. Hence please be gentle. I am working on a site where the owner has lost the relationship with the developer and hence passwords to the admin accounts (front-end and back-end). I am trying to create superusers for both but am having problems with the database. The site uses a PostgreSQL database. In the shell I activate the virtual environment and run my command: python3 manage.py createsuperuser The email address is requested and enter but receive the error after several lines of script. django.db.utils.OperationalError: FATAL: password authentication failed for the user "xxx". Do I need to somehow activate or enable the connection to the database before running the command?? Again really new and not trying to be the developer on the site- just trying to gain access and create users. Many thanks. -
How to pass a django model to a javascript function
I have a javascript function that needs some variables (about 10) from my view. I don't need to call again the variables once the page is loaded. I could give them using a context dict, like below, but maybe is possible to do better. My models.py: class Mymodel(models.Model): my_field1 = # my_field2 = # ... my_field10 = # My views.py: def myview(request): context_dict={} context_dict['myfield1'] = Mymodel.objects.get(id=1).myfield1 context_dict['myfield2'] = Mymodel.objects.get(id=1).myfield2 context_dict['myfield10'] = Mymodel.objects.get(id=1).myfield10 My template.html: ... <script> <!-- window.onpageshow = function() { my_function( '{{ myfield1 }}', '{{ myfield2 }}', ..., '{{ myfield10 }}' ); }; --> </script> ... My javascript.js: function my_function(myfield1, myfield2, ..., myfield10) { //code } These variables are the fields of a model, so i just need to pass the model istance. How can I do that? It's some time I work on it and I think I should use serialize but I don't understand how... My template.html: ... <script> <!-- window.onpageshow = function() { my_function( serializers.serialize("json", {{ mymodelistance }})); }; --> </script> ... Thanks in advance -
Using Windows to run a virtual environment Created on Ubuntu
so i have been developing a website with a backend database. The following is my current setup and it is working great: Currently using Ubuntu 16.04 I created a virtualenv and downloaded Django and postgreSQL within the virtual environment. I also downloaded and am using Python 3.5.2 within the virtual environment. My entire folder structure is on GitHub so that I can edit the code on the go (Again, everything working fine on Ubuntu). The problem comes when I want to start doing some editing on Windows 10 using Powershell. I am unsure of how to run the 'activate.sh', 'activate.csh', or 'activate.fish' file in order to run the virtual environment and initialize my server using 'python manage.py runserver' so I can start editing my website. Has anyone run into the problem and found out how to fix this? Any help on how to get started working on Windows would be great. If you need any more details id be glad to provide them. Thanks! -
check if file is present while updating form in django
I have a form to update in some fields. In the update form i have some fields. I want to check if i select a file then the file gets uploaded and if i don't select a file the existing file stays. Any way of doing that? i tried to check it by this user = User.objects.get(pk=pk) upd_form = UpdateForm(request.POST, request.FILES or None) if upd_form.is_valid(): user.first_name = upd_form['first_name'].value() user.last_name = upd_form['last_name'].value() user.email = upd_form['email'].value() user.phone = upd_form['phone'].value() user.address = upd_form['address'].value() if upd_form['photo'].value() == '': user.photo = user.photo else: user.photo = upd_form['photo'].value() user.save() return redirect('user_management:list_user') -
Vertical Scroll bar django-tables2
Can anyone tell me how to add a vertical scroll bar to django-tables2 instead of having Page 1 of 2 Next 25 of 49 vehicles at the bottom of the table. tables.py ''' Created on 28 Oct 2016 @author: JXA8341 ''' import django_tables2 as tables from .models import Vehicle class CheckBoxColumnWithName(tables.CheckBoxColumn): @property def header(self): return self.verbose_name class VehicleTable(tables.Table): update = tables.CheckBoxColumn(accessor="pk", attrs = { "th__input":{"onclick": "toggle(this)"}}, orderable=False) class Meta: model = Vehicle fields = ('update', 'vehid') # Add class="paleblue" to <table> tag attrs = {'class':'paleblue'} screen.css table.paleblue + ul.pagination { font: normal 11px/14px 'Lucida Grande', Verdana, Helvetica, Arial, sans- serif; overflow: scroll; margin: 0; padding: 10px; border: 1px solid #DDD; list-style: none; } div.table-container { display: inline-block; position:relative; overflow:auto; } table.html <div class='vehlist'> <script language="JavaScript"> function toggle(source) { checkboxes = document.getElementsByName('update'); for(var i in checkboxes) checkboxes[i].checked = source.checked; } </script> <form action="/loadlocndb/" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% render_table veh_list %} <h4> Location database .csv file</h4> {{ form.locndb }} <input type="submit" value="Submit" /> </form> </div> I've looked all over but I can't seem to get a straight answer, or is there a better table module I can use to display the array and checkboxes? -
Django - Access and save files to remote server
I am currently developping an application using Django. What I'm trying to achieve is to have a remote server that will host configuration files. Those files are going to be numerous but quite small. The configuration of my server is the following : on the adress 172.x.x.51 I have my Django app running with uwsgi and on 172.x.x.52 I have my nginx service connected to my uwsgi instance. What I would like is to host the files on the nginx server. Inside the application, I will need to access to the files and to save them (they are calculated from data from the database, so there's no need for a fileupload). I looked on the documentation and found that I can use a Custom Storage System. The thing is, I don't think that's what I need because I want to store them the way it's done by default. I would just like to define the place where the files should be updated from Django. Would it be better if I stored them in the media folder on my nginx instance ? How would I say to Django to go look on nginx's instance for the files ? On the server … -
python - Django display uploaded multiple images
I'm working on app, but I can not understand how to display images to the post. I have a model "Image" of the foreign key (Post), but how to display an image to the post of its id my model: class Post(models.Model): title = models.CharField(max_length=20000) date = models.DateTimeField(editable=True, null=True) text = models.TextField(max_length=50000) is_super = models.IntegerField(default=0) class Image(models.Model): foreing = models.ForeignKey(Post) image = models.ImageField(null=True, blank=True, upload_to='my-images') views: def post_new(request): ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3) if request.method == "POST": form = PostForm(request.POST, request.FILES or None) formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none()) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.date = timezone.now() post.save() for form in formset.cleaned_data: image = form['image'] photo = Image(foreing_id=post.id, image=image) photo.save() return render(request, 'home/page.html') else: form = PostForm() return render(request, 'home/edit_post.html', {'form': form, 'error_message': 'something error message'}) else: form = PostForm() formset = ImageFormSet(queryset=Image.objects.none()) return render(request, 'home/edit_post.html', {'form': form, 'formset': formset}) and index view: class IndexView(generic.ListView): paginate_by = 4 template_name = 'home/index.html' context_object_name = 'all_posts' def get_queryset(self): query = self.request.GET.get('q') if query: posts = Post.objects.filter( Q(text__icontains=query.capitalize()) | Q(title__icontains=query.capitalize()) | Q(text__icontains=query.lower()) | Q(title__icontains=query.lower()) ).distinct() return posts else: return Post.objects.filter(date__lte=timezone.now()).order_by('-date') template index.html: Here is a image displayed <div class="profile-img-container" style="text-align: center"> <img class="img" src="images"> <a target="_blank" title="****." href="URL to the uploaded image"><span … -
Serialize HTML form with Array and JSON fields to post to Django Rest
I'm using Django Rest Framework to supply data to a web app. We are in the process of converting the front end to React, so we are having to port a few things here and there to plain javascript to ease the transition. I have a form that accepts JSON and Array fields and this works ok when I use Django Forms, but is more difficult with just javascript. The goal here is to grab the form data with javascript and post it to the Django Rest API in a valid way. Imagine the form has these four fields with an id of #my-form: field1:[{"a": "b"},{"a": 1}] field2: [123,456] field3: 123 field4: "foo" When I try to get the form data like so: $("#my-form").serializeArray(); it returns a list of objects: [ {name: "field1", value: "[{"a": "b"},{"a": 1}]"}, {name: "field2", value: "[123,456]"}, {name: "field3", value: "123"}, {name: "field4", value: "foo"}, ] this is mostly ok because I can easily iterate over this and create one object: { field1: "[{"a": "b"},{"a": 1}]", field1: "[123,456]", field1: "123", field1: "foo", } My issue is that field1 and field2 are nested Array[Int] or Array[Object] but they are being treated as strings which is not a … -
Breaking template on {% load rango_template_tags %}
So I am half way through a tutorial useing the book Tango With Django trying desperately hard to take on as much information as i can about Django. Now i am trying to set up a template that lists all the category's but i get an error invalid syntax (rango_template_tags.py, line 8) I have no idea why i am getting this line, absolutely none i have checked it with the book 5 + times but i cant find anything that looks out of place of wrong. Can anyone please tell me why i am getting this error. Base.html {% load rango_template_tags %} <div> {% block sidebar_block %} {% get_category_list %} {% endblock %} </div> # This file has more within it these are the new pieces of code that break the template system. If these are in it wont work. rango_template_tags from django import template from rango.models import Category register = template.Library() @register.inclusion_tag('rango/cats.html') def get_category_list(): return {'cats' Category.objects.all()} cats.html <ul> {% if cats %} {% for c in cats %} <li><a href="{% url 'show_category' c.slug %}">{{ c.name }}</a></li> {% endfor %} {% else %} <li><strong> There ar eno categories presen. </strong></li> {% endif %} </ul> -
How do you filter on many-to-many relationships using classes (Python/Django)
Im trying to filter posts belonging to a certain theme. I have a many-to-many relationship as you can see in my models. The problem is that I don't know how to filter. Normally I would do that by ID, but that didnt work. Models: class Theme(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(_('slug'), max_length=255, null=True, blank=True) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) image = FilerImageField() def publish(self): self.save() def __unicode__(self): return self.title class Post(models.Model): writer = models.ForeignKey(Author, blank=True, null=True) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) themes = models.ManyToManyField(Theme) def publish(self): self.published_date = timezone.now() self.save() def __unicode__(self): return self.title Views: from .models import Theme, Post from django.views.generic import ListView, DetailView class ThemesOverview(ListView): """ Overview of all themes """ model = Theme template_name = 'content/theme_list.html' def get_queryset(self): queryset = Theme.objects.all() return queryset class ThemePostsOverview(ListView): """ Overview of all posts within a theme """ model = Post template_name = 'content/theme_posts_list.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(ThemePostsOverview, self).get_context_data(**kwargs) slug = self.kwargs['theme'] theme = Theme.objects.get(title=slug) context['theme'] = theme return context def get_queryset(self): queryset = Post.objects.all() return queryset As you can see I'm currently showing all posts … -
patch function with same name as module python django mock
|-- dir | |-- __init__.py | |-- function.py `-- test.py in function.py: import other_function def function(): doStuff() other_function() return in __init__.py from .function import function in my test.py from django.test import TestCase from mock import patch from dir import function class Test(TestCase) @patch(dir.function.other_function) def function_test(self, mock_other_function): function() When I run this I got a AttributeError: <@task: dir.function.function of project:0x7fed6b4fc198> does not have the attribute 'other_function' Which means that I am trying to patch the function "function" instead of the module "function". I don't know how to make it understand that I want to patch the function. I would also like to avoid renaming my module or function. Any ideas? -
How to get missing data using Django model query?
In Django, there is the filter() method to filter data. So I can pass an array of data and get the filtered results like this model.objects.filter(id__in=id_array). Is there a way to get missing data using Django model query? How to get a list of id_array elements which don't exist in the database? -
Django authenticate() resets password
I have a weird problem here. When I login, it works well as expected but when I try to logout and try to login again, it says that my password is invalid. I checked my User table and it's really changing my password everytime I use authentication() function. login.py after authenticate() function, my password is already changed (tried to put a breakpoint after the function so I know for sure that this is the culprit). user = authenticate(username = data['email'], password = data['password']) Python 2.7 Django 1.9 Postgre 9.4 Thanks! -
django remote access basics
i have scripts producing outputs and other scripts reading these. All data should be read/written from/to a database on a server with corresponding information from multiple remote terminals. I felt like django seems to be a nice solution. Unfortunately the documentation and examples are only about setting up the data base and accessing it locally or via a browser. I get the impression that django is not offering this since i can not find anything about it and i was searching a lot. Could someone help or link some examples how to write/read to the database on a server from an other machine? Cheers, Daniel -
How to login with encrypted password in django
I am using django.contrib.auth for authentication in my project, its working fine, Now i have to work on a module where super members have to login in it's member's account, he should have all the access of their account, so I have to login with member's email id and their encrypted password automatically saved by django Auth while registering members. user_existence = User.objects.filter(email=request.POST['email']).first() if user_existence: email = user_existence.email password = user_existence.password user = authenticate(username=email, password=password) if user is not None: login(request, user) return HttpResponse('user_connected') return HttpResponse('user_auth_failed') Is is possible to encrypt this password or login with encrypted password, or it would be great if its having another solution. -
Real-Time Database Messaging
We've got an application in Django running against a PGSQL database. One of the functions we've grown to support is real-time messaging to our UI when data is updated in the backend DB. So... for example we show the contents of a customer table in our UI, as records are added/removed/updated from the backend customer DB table we echo those updates to our UI in real-time via some redis/socket.io/node.js magic. Currently we've rolled our own solution for this entire thing using overloaded save() methods on the Django table models. That actually works pretty well for our current functions but as tables continue to grow into GB's of data, it is starting to slow down on some larger tables as our engine digs through the current 'subscribed' UI's and messages out appropriately which updates are needed as which clients. Curious what other options might exist here. I believe MongoDB and other no-sql type engines support some constructs like this out of the box but I'm not finding an exact hit when Googling for better solutions. -
After closing terminal without exiting "Connection refused" error. Django 1.8
Without any reason after I have closed terminal window without exiting and stoping server, the next time I run any command like python manage.py migrate/runserver/makemigrations I am getting the following traceback.I can't really understand what is wrong now? -
Order detail_route with ordering query parameter using Django Rest Framework
In a detail_route method like the following, how would I support ordering of the events using the ordering query parameter like this: http://localhost.com/items/123/events?ordering=EventDateTime class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = ( filters.OrderingFilter ) ordering_fields = ('Label') @detail_route() def events(self, request, pk=None): item = self.get_object() events = item.events.all() page = self.paginate_queryset(events) if page is not None: serializers = EventSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializers.data) serializers = EventSerializer(events, many=True, context={'request': request}) return Response(serializers.data) I've tried the following but nothing gets sorted: @detail_route() def events(self, request, pk=None): item = self.get_object() events = filters.OrderingFilter().filter_queryset(request, item.events.all(), self) page = self.paginate_queryset(events) if page is not None: serializers = EventSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializers.data) serializers = EventSerializer(events, many=True, context={'request': request}) return Response(serializers.data) -
Django Model Form not saving
I have a Django model form which when I use the following, isn't saving if request.method == 'POST': form = AbsenceForm(request.POST, instance=request.user) if form.is_valid(): form.save() forms.py class DateInput(forms.DateInput): input_type = 'date' class AbsenceForm(forms.ModelForm): class Meta: model = NotWorking exclude = ['user'] widgets = { 'date': DateInput() } Can you help please.