Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use angularjs with Django?
I'm new to Django and angularjs can someone guide me through how can I build application by using them together? I'm not getting proper solution for this.. Can someone please help me out? -
chat application as separate endpoint
I am planning to design the chat(web socket) application for my eCommerce django REST application. What is the best design Integrate the chat inside application inside the same django REST server Deploy chat as a separate end point for chat only. If put different server and db for chat. how we communicate with rest sever to validate.? and whats the best design. ? -
how to make this raw sql to django orm
I wanna change below raw sql code to Django ORM. How can I do? SELECT ad_id, count(distinct(user_id)) FROM reachcount GROUP BY ad_id; I did like this queryset = ReachCount.objects.values('ad_id').annotate(Count('user_id',distinct=True)) but it's not the result what I want. So I checked raw sql code with querset.query. below code is the raw code SELECT `test_reachcount`.`ad_id`, COUNT(DISTINCT `test_reachcount`.`user_id`) AS `user_id__count` FROM `test_reachcount` GROUP BY `test_reachcount`.`ad_id`, `test_reachcount`.`user_id` ORDER BY `test_reachcount`.`ad_id` ASC, `test_reachcount`.`user_id` ASC if I get rid of "test_reachcount.user_id" in group by clause. I think this code is similar what I want. let's summarize about question. Why did test_reachcount.user_id add automatically? How can I get rid of test_reachcount.user_id code. if you make code better. plz share me. Thank you for reading long question. -
Haystack search engine using nyt API
I want to write a search engine in django using nyt API. My question is Haystack can be used for this purpose or not. If yes, How? Can you please give one example. I am unable to get through. Thank you!! -
Django CreateView cancel with empty fields
I have a CountryCreateView for my Country model and I'm trying to add a cancel button to it. However if there isn't something filled out in every field and I press the cancel button, I get a pop-up that says Please fill out this field. When I press the cancel button, I don't care what's in the fields, I just want to go to the page I'm redirecting to. On top of this, I want this field non-requirement to be only for this. I don't want anything else to allow blank fields. views.py: class CountryCreateView(generic.edit.CreateView): model = Country fields = ['code', 'name'] template_name_suffix = '_create' def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('appName:country_list')) else: return super(CountryCreateView, self).post(request, *args, **kwargs) models.py: class Country(AutoUpdateModel): # extends models.Model code = models.CharField(primary_key=True, max_length=2, validators=[validate_nonempty, validate_string_length_two, validate_string_all_caps]) name = models.CharField(max_length=50, db_column="Name", validators=[validate_nonempty]) # etc... country_create.html: {% extends "appName/base.html" %} {% block content %} <h2 class="title">Create a new Country:</h2> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" class="btn btn-primary"/> <input type="submit" name="cancel" value="Cancel" class="btn btn-secondary"/> </form> {% endblock %} -
Django-Pandas-Matplotlib: The image cannot be displayed because it contains errors
I'm building a website with Django to analyse data collected by household devices. I can create a pandas dataframe from the django queryset (df.head() and for row in df.items() both look fine), but I'm unable to display the image created by matplotlib. Firefox tells me: The image "https://127.0.0.1:8000/graph/device/" cannot be displayed because it contains errors. I tried changing the content type of the HttpResponse to "text/plain" but nothing is shown. I simplified my code as much as I could to pinpoint the problem and fixed a few things along the way but now I'm not sure where to look. From the view: fig = Figure() for d in devices: dev = Device.objects.get(address=d) if dev.value_set.values("timestamp", "pcb_temp"): df = pd.DataFrame.from_records(Value.objects.filter(device=dev).values("timestamp", "pcb_temp")) df.dropna(inplace=True) df.set_index("timestamp", inplace=True) df.sort_index(inplace=True) print(df.head()) # debug ax1 = fig.add_subplot(111) df.plot(ax=ax1) break # debug fig.autofmt_xdate() canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response Result of print(df.head()): pcb_temp timestamp 2016-12-23 05:05:11+00:00 2168 2016-12-23 05:05:21+00:00 2162 2016-12-23 05:05:31+00:00 2168 2016-12-23 05:05:41+00:00 2162 2016-12-23 05:05:51+00:00 2168 Specs: Python 3.5, Django 1.10, Pandas 0.19, Matplotlib 2.0 -
Passing parameter with reverse used with HttpResponseRedirect
I currently have something like this return HttpResponseRedirect(reverse("named_foo"),request) How do I pass parameter to named_foo definition through reverse ? The parameters of named_foo definition is as follows: def fooMethod(request) : print "inside foo method" -
blockage while reviewing instagram data
We have built a code to go through our instagram and look at all of the publicly listed data - we have hit a limit of 14k users - does anyone know how to get around this? -
Python convert list of tuples into single tuple
Is there a way to convert a list of tuples into a single tuple? I have received a list of tuples from cursor.fetchall() but would like to make this into a single tuple: curr_table_columns = cursor.fetchall() For example: [(u'w_id',), (u'w_name',), (u'w_street',)] becomes [(u'w_id', u'w_name', u'w_street')] -
how serializer ImageField in django rest framework mongoengine?
When i save a ImageField this create collections images.chunk and images.files and in the rest framework mongoengine return Id. I would like get url for image and thumbnail. Thanks. -
Create a REST API in R
I want to start a project to expose data from diverse institutions, that are not well structured, using a web service, I'm proficient in R, so that's my language of choice, but I know its limitations, I know of this "framework": https://github.com/trestletech/plumber/blob/master/README.md But I'm not sure if its mature enough or the best using R. So I want to know if you have any idea of other R package to do this or if you would recommend me to use some other framework (Flask, Django, etc) or if I should use plumber. -
How to convert a value to a string inside a loop for in a template
I want do the following: In the tamplate candidate_list I list all of candidates registered, and I must show the candidate average beside of him, but the average of a candidate are saved in another model (Evaluation).So I try put a loop for inside the loop for that shows the candidate (Candidate) and in this second loop for he search the Evaluation that have the attribute candidate(it's a ForeignKey) and compare with the candidate.name, witch is taken in the extern loop for, but the candidate.name is a string and the evaluation.candidate is a ForeignKey, and I thought in convert this attribute to a string and compare, but I don't really know how do this, I tried the following: template: candidate_list.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>Lista de candidatos</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link href="{% static 'css/app.css' %}" rel="stylesheet"> </head> <body> <h1><a href="/"> Lista de candidatos: </a></h1> {% block content %} {% for cand in candidates %} <p> <div><a href="{% url 'candidate_detail' pk=cand.pk %}">Nome:{{ cand.name }}</a></div> <!--<div id="average">Média:{{cand.average}}</div>--> </p> {% for e in eva %} {% if e.candidate |stringformat:" " == cand.name %} <p>{{ e.score }}</p> {% endif %} {% endfor %} … -
Error converting Unix timestamp to int - ValueError: invalid literal for int() with base 10: ''
I am writing a Django Framework app that receives Unix Timestamps as parameters in an Ajax call and uses them to query a database. My issue is in converting the timestamp strings to Python ints, which throws ValueError: invalid literal for int() with base 10: ''. This is the snippet: start = request.GET.get('start','') start = int(start) I tried printing the timestamp and copying the output into a shell for the same operation, which completed successfully: >>> int(1485939600) 1485939600 The error suggests it's being passed an empty string yet I can print it. Not sure what the problem could be? -
How can I run UnitTests of a Django application from the right click context menu in PyCharm Community Edition?
I must emphasize on PyCharm Community Edition which does not have any Django integration. I've Google'ed my problem and (surprisingly,) I did not get any answers (of course I don't exclude the possibility that there might be some, be but I just missed them). The question is simple, in PyCharm, one can Run(Debug) an Unit Test (TestCase or one of its methods) with a simple mouse right click (from the context menu) just as in the image below: Unfortunately, that yields an exception: Traceback (most recent call last): File "C:\Install\PyCharm Community Edition\2016.3.2\helpers\pycharm\utrunner.py", line 254, in <module> main() File "C:\Install\PyCharm Community Edition\2016.3.2\helpers\pycharm\utrunner.py", line 232, in main module = loadSource(a[0]) File "C:\Install\PyCharm Community Edition\2016.3.2\helpers\pycharm\utrunner.py", line 65, in loadSource module = imp.load_source(moduleName, fileName) File "E:\Work\Dev\Django\Tutorials\proj0\src\polls\tests.py", line 7, in <module> from polls.models import Question File "E:\Work\Dev\Django\Tutorials\proj0\src\polls\models.py", line 9, in <module> class Question(models.Model): File "E:\Work\Dev\Django\Tutorials\proj0\src\polls\models.py", line 10, in Question question_text = models.CharField(max_length=200) File "E:\Work\Dev\VEnvs\py2713x64-django\lib\site-packages\django\db\models\fields\__init__.py", line 1043, in __init__ super(CharField, self).__init__(*args, **kwargs) File "E:\Work\Dev\VEnvs\py2713x64-django\lib\site-packages\django\db\models\fields\__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "E:\Work\Dev\VEnvs\py2713x64-django\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__ self._setup(name) File "E:\Work\Dev\VEnvs\py2713x64-django\lib\site-packages\django\conf\__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE … -
Django: $ python manage.py runserver
I was just setting up the virtual environment with Django for my first time. And I couldn't find any resources for this issue. When I was in virtual environment, in the same directory as the manage.py file, I type in the command: python manage.py runserver I can't get the development server up and running. Instead, I got the error: Segmentation fault I tried some solutions but nothing good happened. python -vvvvv manage.py runserver python manage.py migrate I'm using python 3.6.1 and django 1.10.5 -
Update data in a JsonField django
I want to update a json object that is in a jsonfield in django, i am having a problem updating the data. My model looks like this https://codeshare.io/Gbeonj My json looks like this https://codeshare.io/5obDPX so basicly the json has wrong data , instead of "NATIONAL ID Card" it has "NATIONAL ID" so i want to update this json object to have the right data. here is what am talking about "info": { "mobilePhone": "", "firstName": "david", "tags": [], "middleName": "mirale", "gender": "Male", "documentType": "NATIONAL ID", "beneficiary": false, "dateOfBirth": "1995-03-04T08:01:42.165Z", "documentNumber": "519011016721", "dateOfBirthExact": false, "role": "Child", "lastName": "ABSURG0058", "recipient": "Alternate", "homePhone": "" }, the "documentType": "NATIONAL ID", should be "NATIONAL ID Card" i am using the following script to update the json object in the server. import django django.setup() import sys reload(sys) # to re-enable sys.setdefaultencoding() sys.setdefaultencoding('utf-8') import json from django.db import transaction from maidea.apps.mobile.models import MobileDocument office = 'sa_de' #we fetch all the mobile documents from that have failed uploads = MobileDocument.objects.filter( status=MobileDocument.ERROR, mobile_upload__office__slug=office ) print('Number of uploads fetched: %d' %(uploads.count())) with transaction.atomic(): for upload in uploads: for member in upload.data['members']: try: doc_type_value = member['info'].get('documentType') except: doc_type_value = None if doc_type_value == 'NATIONAL ID': doc_type_value = doc_type_value.replace('NATIONAL ID', 'NATIONAL ID … -
Loop through a Python list in Django template with for loop
I need to simplify this Django template, {{ var.1 }} {{ var.2 }} {{ var.3 }} {{ var.4 }} {{ var.5 }} var is Python list passed as context to the template how do you convert the above template using a for tag construct. I tried this but does not work. {% for i in var|length %} {{ var.i }} {% endfor %} -
Time trial login that expires Django
So I have a Django app set up with auth and a few Groups and users. What I'm trying to do now is have a timed trial so users could have a login that would expire after 7 days. I've researched this and haven't been able to find anything. Feel like I'm missing something obvious. Any suggestions? -
In Django, is there a way to show the admin for a model under a different app?
I've extended the standard User with a Profile model using a one-to-one relationship: class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, editable=False) # Additional user information fields This is in an app called account_custom. The issue is that in the admin site, I would like this model to show up along with User under "Authentication and Authorization". I was able to make this show up in the right place in the admin by setting Meta.app_label: class Profile(models.Model): class Meta: app_label = 'auth' db_table = 'account_custom_profile' I set Meta.db_table so this uses the existing database table, and everything seems to function properly. The problem is that Django wants to generate migrations for this, one in account_custom to delete the table and one in auth to create it again. I'm guessing this would either fail or wipe out the data depending on the order the migrations are run, but the deeper problem is that it's trying to create a migration in auth which isn't part of my code base. Is there a way around this, or is there some better way to control where a ModelAdmin shows up in the admin site? -
Strange Timezone behaviour Django
Some weirdness here I can't get my head around: Given these settings: >>> from django.conf import settings >>> settings.TIME_ZONE 'Europe/London' >>> settings.USE_TZ False Given the model of: class ProductManager(models.Manager): def get_queryset(self): from_date = datetime.now() - HALF_YEAR return super(ProductManager, self).get_queryset().filter(start_date_time__gt=from_date) class Product(models.Model): product_number = models.CharField(max_length=45) start_date_time = models.DateTimeField() cover_renewal_date = models.DateField() objects = ProductManager() Which gives us the database table: shopapp=>\d shop_product Column | Type | Modifiers -----------------------+--------------------------+---------------------------------------------------------- id | integer | not null default nextval('shop_product_id_seq'::regclass) product_number | character varying(45) | not null start_date_time | timestamp with time zone | not null shopapp=> show timezone; TimeZone ---------- UTC (1 row) With the following data: shopapp=> select product_number, start_date_time from shop_product where product_number in ('PN63145707', 'PN57284554', 'PN57291674', 'PN66177827'); product_number | start_date_time ---------------+------------------------ PN57284554 | 2013-04-05 00:00:00+00 PN57284554 | 2014-04-05 00:00:00+00 PN57284554 | 2015-04-05 00:00:00+00 PN57284554 | 2016-04-05 00:00:00+00 PN57284554 | 2017-04-05 00:00:00+00 PN57291674 | 2013-04-04 00:00:00+00 PN57291674 | 2014-04-04 00:00:00+00 PN57291674 | 2015-04-04 00:00:00+00 PN57291674 | 2016-04-04 00:00:00+00 PN57291674 | 2017-04-04 00:00:00+00 PN63145707 | 2015-03-25 00:00:00+00 PN63145707 | 2016-03-25 00:00:00+00 PN63145707 | 2017-03-25 00:00:00+00 PN66177827 | 2017-03-25 00:00:00+00 (14 rows) But running this code: now = datetime.now().date() start_time = now - timedelta(days=1) end_time = now + timedelta(days=14) res = Product.objects.filter(start_date_time__range=(start_time, end_time), product_number__in=['PN63145707', … -
Building Python3 proxy server between PostgreSQL and Dynamics 365 Web API
After several days of some progress, I am coming to terms with the fact I lack the knowledge, or level of skill, to put all of these pieces together and finish this project. Thus, I am appealing to, and grateful to, anyone who can help me out with this. Technology CentOS 7.5 Python 3.6.0 Django 1.10.5 PostreSQL 9.2 Microsoft CRM Dynamics 365 online which has most current client data, thus have to use the Web API: https://msdn.microsoft.com/en-us/library/gg334767.aspx Issue CRM has the most current client data in it and want to bring it into PostgreSQL to use for numerous things Want to use www_ftw since it is the only foreign data wrapper I have seen for PostgreSQL than can use Web API's: https://github.com/cyga/www_fdw/wiki The Dynamics Web API uses OAuth2 and www_ftw does not support any type of authentication natively Talked to the dev of www_ftw who recommended making a proxy server to handle the OAuth2 authentication with Microsoft PostgreSQL with www_ftw would talk to the proxy, which would in turn send authentication to Microsoft culminating in the ability to treat the Web API as a Foreign Table so that it is treated like any other table The three parts and what … -
Django DB error with nonexistent table
I try to reinitialize my DB and I have this error: django.db.utils.OperationalError: no such table: app_evaluation I don't have any variable with this name, I try to dele db.sqlite3 and all files of migrations folder and run the migrate and makemigrations command but nothings works models.py from django.db import models from jsonfield import JSONField from site_.settings import MEDIA_ROOT from django.core.validators import MaxValueValidator class Criterion(models.Model): label = models.CharField(max_length=100) def __str__(self): return self.label class Candidate(models.Model): name = models.CharField(max_length=100) e_mail = models.EmailField(max_length=100, default = '') github = models.URLField(default = '') linkedin = models.URLField(max_length=100, default = '') cover_letter = models.TextField(default = '') higher_education = models.BooleanField(default = False) average = models.IntegerField(default = 0) #############################################################score = models.ForeignKey() docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True) def __str__(self): return self.name class Evaluation(models.Model): candidate = models.ForeignKey(Candidate, unique=True) #s_candidate = models.CharField(max_length=100) criterion = models.ForeignKey(Criterion, default='') score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)]) appraiser = models.ForeignKey('auth.User') def __str__(self): return str(self.candidate) class avarage(models.Model): eva = Evaluation.objects.get() view.py from django.shortcuts import render, get_object_or_404 from .models import Candidate, Criterion, Evaluation from django import forms from .forms import CandForm from .forms import EvalForm from django.shortcuts import redirect def canditate_list(request): candidates = Candidate.objects.all() eva = Evaluation.objects.all() eval_cand_list = [] #aqui guarda uma lista com os FK candidates convertidos p/ … -
How to send email to dinamic email accout in Django?
I have a contact form in my template, when a user requests information about a house, users can contact diferents sellers to request information, So I don't know how can send email to differents accout as you knows in the system exist multiple sellers. This is my contact form : Where "Nombre" is the name of the user that wants information and "Mail" is the e-mail of the user that wants information. The seller of the House is who will receive the email. I can't use that: EMAIL_HOST_USER = EMAIL_HOST_PASSWORD = because not only one person will receive all emails -
Python Flask Divisional Accessing Base Templates
http://exploreflask.com/en/latest/blueprints.html#divisional Divisional Structure Is like Django Structure. I want to make Reusable Modular component in Flask and just call blueprint for that feature. yourapp/ __init__.py admin/ __init__.py views.py static/ templates/ home/ __init__.py views.py static/ templates/ control_panel/ __init__.py views.py static/ templates/ models.py Problem is that i don't know how to access the base temple form jinja {% extends "base.html" %} from a different templates folder because in the blueprints i Specified a the template location. contact = Blueprint('contact', __name__, url_prefix='/contact',template_folder='./templates') Any thoughts on the file structure on flask or how to get the same base template to all the blueprints? -
Why are changes to existing record not getting saved to table?
I am just starting out with django and trying to edit an existing record in a table via modelform. I found this post which seems to to jive with what I have in my view, but when I make changes to the form, no changes are reflected in the table. If I reload the form, I can see the changes in the form, but still not in the table itself. What is wrong? from django.http import HttpResponseRedirect from django.shortcuts import render, render_to_response from django.views.generic import View from .models import Mapindex as MapIndexModel from .forms import MapIndexForm instance = MapIndexModel.objects.get(pk=650) class MapIndexView(View): template_name = 'add.html' def get(self, request): form_mapindex = MapIndexForm(instance=instance) return render(request, self.template_name, { 'title': 'Map Index Update Form', 'form_mapindex': form_mapindex }) def post(self, request): form_mapindex = MapIndexForm(request.POST, instance=instance) if form_mapindex.is_valid(): form_mapindex.save() return HttpResponseRedirect('/update/') return render_to_response('add.html', {'form': form_mapindex})