Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
InheritanceManager bug when access parent-class elements (Django 2.0)
I'm currently trying to have a object oriented schema in Django 2.0 (Python 3.6.3) with a parent class Program and some children classes Snippet and Software. I saw that the model_utils module contains some tools to handle the polymorphism, and tried to replicate the tutorial (http://django-model-utils.readthedocs.io/en/latest/managers.html), here is what it gives in my case: models.py from django.db import models from model_utils.managers import InheritanceManager class Program(models.Model): name = models.CharField(max_length=100) objects = InheritanceManager() class Snippet(Program): code = models.TextField() class Software(Program): repoLink = models.URLField() Django shell >>> from coding.models import Program >>> programs = Program.objects.select_subclasses() >>> programs Traceback (most recent call last): File "<console>", line 1, in <module> File "...\py3django\lib\site-packages\django\db\models\query.py", line 248, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "...\py3django\lib\site-packages\django\db\models\query.py", line 292, in __getitem__ qs = self._chain() File "...\py3django\lib\site-packages\django\db\models\query.py", line 1156, in _chain obj = self._clone() File "...\py3django\lib\site-packages\model_utils\managers.py", line 100, in _clone return super(InheritanceQuerySetMixin, self)._clone(**kwargs) TypeError: _clone() got an unexpected keyword argument 'subclasses' I don't understand this error and how to fix it, and even don't know if it is a fail in my design or a bad use of the InheritanceManager. So what can be the origin of this error message? -
Configure django model form with jquery and javacript
I have three models : class Instances(models.Model): name_of_instances = models.CharField(max_length=255) url_of_instances=models.URLField(max_length=255,default='') def __str__(self): return self.name_of_instances class Projects(models.Model): name_of_instances = models.ForeignKey(Instances,on_delete=models.CASCADE) name_of_jproject = models.CharField(max_length=255) project_id= models.CharField(max_length=25) def __str__(self): return self.name_of_project class All(models.Model): choices_instance=Instances.objects.all() b = [str(i.name_of_instances) for i in choices_instance] a=[str(i.url_of_instances) for i in choices_instance] choices_instance=tuple(zip(a,b)) name = models.CharField(max_length=255,choices=choices_instance) project = models.CharField(max_length=255,) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) def __str__(self): return self.name I have a models form: class Form(ModelForm): class Meta: model = All fields =('name','project','story','depends_on','rfc') In template i want to know what user has drop down in 'name' field , and i want to send the name value to back end function where i willl filter out all the prijects associated with name value , and send the result to 'project' field as choices (drop down). Kindly help . -
Django Rest add 2 models from single post
Here is my models.py: from django.db import models class User(models.Model): name = models.CharField(max_length=140) class DatewiseTweets(models.Model): name = models.ForeignKey(User) tweets = models.TextField() date = models.DateTimeField(null=True) serializers.py from rest_framework import serializers, fields from twitterApp.models import User, DatewiseTweets class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DatewiseTweetsSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = DatewiseTweets fields = ('tweets','date','user') view.py class SaveTweetCountView(APIView): datewiseTweetsSerializer = DatewiseTweetsSerializer() def post(self, request, *args, **kwargs): name = request.data['name'] tweetCount = 10 tweets = get_tweets(name, tweetCount) return Response(tweet_dict ,status=status.HTTP_201_CREATED) POST METHOD { "name":"netflix" } Here I'm sending tweeter account name and according to this twitter handle(name) it will find top ten tweets from get_tweets() function. So I want to save this name and all tweets in db. I'm confused how to store data in two tables. here are sample tweets: [ { "date": "2017-12-09T22:36:24", "tweet": "Dear Cluster: I Love You Always" }, { "date": "2017-12-09T22:25:25", "tweet": "RT @sense8: *tap tap* \n\nis this thing on?" }, { "date": "2017-12-09T16:13:54", "tweet": "RT @rachmeetsworld: Personal announcement: I just ordered room service (soup and breadsticks) and I'm going to watch A Christmas Prince!!" }, { "date": "2017-12-09T07:12:02", "tweet": "@emilynussbaum @ilovebakedgoods I would be happy to send you both free corn dogs … -
Celery interval schedule time
I am using django celery beat to schedule my task . Currently i am just creating a interval schedule of 2 days and creating a periodic task to run at that interval . My main problem is , when i schedule a task to run at 2 days , at what time does it run ? and cant i change that time , because i need to run the interval task at certain time provided by the user . The code written so far is periodic_task=PeriodicTask.objects.update_or_create( name='my-interval-task, defaults={ 'interval': schedule, #interval schedule object 'task': 'myapp.tasks.auto_refresh', } ) -
Serilizer.response messing out model Response
I am having an issue that I do not know how to solve. I am using the REST framework, in my views.py I have a model called Response that I want to query with Response.objects.all() The thing is since I imported the serializer from rest_framework.response import Response I think that that Django is getting lost and give me an output that AttributeError: type object 'Response' has no attribute 'objects' Is there a way to deal with that issue without having to rename my model ? Thx you, Raphael -
Access TTN GET request info in Django
I am working on a Django app to process information from The Things Network (TTN). The backend sends information by a GET request, and I want to process this information. A POST request would also be a possibility but then I have to configure/disable CSRF. I can view the information I need when I use request.body but then the information is converted to a byte string. Here is how the input of request.body looks like: b'{"app_id":"111111111111","dev_id":"111111111111","hardware_serial":"11111111111111","port":2,"counter":119,"payload_raw":"UEtUICN2","metadata":{"time":"2017-12-10T09:14:40.469432186Z","frequency":868.1,"modulation":"LORA","data_rate":"SF7BW125","coding_rate":"4/5","gateways":[{"gtw_id":"eui-11111111111111","timestamp":1204471818,"time":"2017-12-10T09:14:40.439773Z","channel":0,"rssi":-66,"snr":6,"rf_chain":0,"latitude":51.986214,"longitude":6.742897,"location_source":"registry"}]},"downlink_url":"https://integrations.thethingsnetwork.org/ttn-eu/api/v2/down/f4ce46a550ec/12?key=ttn-account-v2.-1111111111111-1111111111111111"}' The output of request.META is: {'PATH_INFO': '/', 'wsgi.run_once': False, 'uwsgi.version': b'2.0.15', 'REMOTE_PORT': '42732', 'SERVER_NAME': 'myapp.mydomain.com', 'HTTP_HOST': 'myapp.mydomain.com', 'HTTP_CONTENT_TYPE': 'application/json', 'QUERY_STRING': '', 'SERVER_PORT': '80', 'HTTP_CONTENT_LENGTH': '649', 'DOCUMENT_ROOT': '/home/myapp/domains/myapp.mydomain.com/public_html', 'CONTENT_TYPE': 'application/json', 'REQUEST_URI': '/', 'wsgi.file_wrapper': <built-in function uwsgi_sendfile>, 'wsgi.multiprocess': True, 'wsgi.url_scheme': 'http', 'REQUEST_METHOD': 'GET', 'CONTENT_LENGTH': '649', 'wsgi.version': (1, 0), 'HTTP_USER_AGENT': 'http-ttn/2.6.0', 'REMOTE_ADDR': '111.111.111.111', 'wsgi.errors': <_io.TextIOWrapper name=2 mode='w' encoding='UTF-8'>, 'wsgi.multithread': False, 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.input': <uwsgi._Input object at 0x7ffa3deaf390>, 'SCRIPT_NAME': '', 'HTTP_ACCEPT_ENCODING': 'gzip', 'uwsgi.node': b'server.myserver.com'} Shout I convert the byte string from request.body to a dictionary, or is there an easier way to access the data? -
Display Django logs in templates
I'm working on a project with Python(3.6) and Django(1.10) in which I'm doing some execution in Django views.I'm printing some messages and other execution information in the console but I want to display this information inside the template which is going to be rendered after the completion of a request from Django views. Here's an example code from my Django views: # Start deployment # Setup istio on cluster service = discovery.build('container', 'v1beta1', http=views.getGoogleAuth(), cache_discovery=False) svc_req = service.projects().zones().clusters().get(projectId=deployment.project, zone=deployment.zone, clusterId=deployment.cluster) svc_res = svc_req.execute() print('Status is : {}'.format(svc_res['status'])) status = svc_res['status'] while status != 'RUNNING': svc_res = svc_req.execute() status = svc_res['status'] print('Current Status is : {}'.format(svc_res['status'])) print('Fetching Cluster configs ....') print(subprocess.call( 'gcloud container clusters get-credentials ' + deployment.cluster + ' --zone ' + deployment.zone + ' --project ' + deployment.project, shell=True)) print('Cluster is still Provisioning - Current Status is: {}'.format(status)) How can I display this log information inside Django template when the request has been completed. Help me, please! Thanks in advance! -
Django template and dynamic url
I have a few links that I need to link to via a submit button. Let's say that I have links_ 'http://link/problem1', 'http://link/problem2' and 'http://link/problem3' In my django template I'm trying to link to a random link out of those three: So in my django template I have: <a href="http://link/problem" class="btn btn-success"> Some Text </a> Is there a way that I can have a numeric loop that would loop through numbers 1 to 3 and add those numbers to the 'http://link/problem' I have found a few examaples on how to make a numeric for loop in a django template but I dont know how to add those numbers to the link in an a tag. -
prefetch_related and Prefetch object issue, filtering thru reverse Foreign Key
I have 2 models, company and Product. class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) form the database I'm trying to get the Company data and the corresponding products. From the products I want to get only the name and to be ordered descending by updated_at, created_at. I'm working with Prefetch object and prefetch_related and definitively I have multiple misunderstandings how they work. def get_queryset(self): qs = Company.objects.prefetch_related( Prefetch('products', queryset=Product.objects.only('name').order_by('-updated_at', '-created_at'))).get() return qs The error that I receive is: get() returned more than one Company Because I closed the prefetch_related method/function with ))) : I thought get() will act over the Company object and get it using the pk/slug from the url(as get do by default in DetailView). Seems that is not the case. I'm already using 'products' the related name in the Prefetch object, why in queryset is necessary to tell again the model queryset=Product.objects.... ? I was looking at the following example in django documentation: Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all() If there is 'choice_set' in Prefetch object why is called at the end choice_set.all() ? Isn't Django attached to the quesryset in prefetch_related the products to the queryset (question.choice_set) ? I think my problem is that I don't understand the order of execution, … -
Django / Geodjango / Raster / geotiff: Problems with practice task
I greet you First, I apologize for my bad english. I can read English to some extent, but I can not write well. I hope you can help me. I got a practice task, which I can not get any further. The task is the following: Project Description The goal of the projects is to create a map view similar to the Google Maps, where user can see some imagery data captured by drones. User should be able to move around the map freely, as well as zoom in and zoom out to take a closer look at the captured imagery data. It is strongly desired that the served imagery data will support transparency while minimizing the file size and bandwidth usage. This does not have to be implemented, but solution ideas are welcomed. The raw imagery data will be provided as GeoTIFF files. Imagery visible on the map can be added by placing a file inside a directory that is read by the server. Project Delivery Method Project should be delivered as a Git repository with documentation required to setup and run the project. Requirements 1. Server implementation in Python 3.5+ 2. Project must be able to run on … -
Update Django Status Field Based On Real-time Status of Celery Task?
In my model, I have a status field with a default value of 'Processing'. In the Django admin interface, after user clicks 'Save' button, the form inputs are passed to a celery task that just sleeps for 30 seconds. After that 30 seconds, how do I: determine if the celery task was successful? update the model's status field from 'Processing' to the actual status (ex: Completed, Failed? models.py from django.db import models class Scorecard(models.Model): name = models.CharField(max_length=100, unique=True) status = models.CharField(max_length=20, default='Processing') def __str__(self): return self.name admin.py from django.contrib import admin from scorecards.models import Scorecard from scorecards.tasks import get_report class ScorecardAdmin(admin.ModelAdmin): list_display = ['name', 'status'] def save_model(self, request, obj, form, change): if form.is_valid(): data = form.cleaned_data name = data['name'] get_report.delay(name) super().save_model(request, obj, form, change) admin.site.register(Scorecard, ScorecardAdmin) tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from time import sleep @shared_task def get_report(name): sleep(30) Real-time status of the celery task updating the status field every x time intervals would be nice, but for now I'm just really curious how to do this at all. -
Contact Us form on a Django Website not sending emails
I followed the instructions from the official documentation and another Stack Overflow post to get django-contact-form working on my django website. I need it to send an email. I tried setting up a debugging server through: python -m smtpd -n -c DebuggingServer localhost:1025 I have a HTML form working with Django on the site. When I click submit on the form, it gives me an acknowledgement that my message has been sent. However, I can't see anything on the Terminal output. In my settings.py, I have the following: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_HOST_USER = 'my email' EMAIL_HOST_PASSWORD = 'my password' I have also tried it with the SMTP settings for Zoho mail, which is the one that I am currently using. I am not getting any emails in my inbox or the others folder either. Another thing that I have tried is changing the settings so that the emails get stored in a tmp folder. I don't want to deploy the code on the site until I can test that it works properly. Any help will be appreciated. I'm not really sure what I'm missing. Let me know if any other files are needed from … -
Django: Sum Total value over Foreign Key Data
I am using Django 1.11 and Python3.5 I have created a table. This is a screenshot. When I got a table from my query database, it is showing 10+2+3... but I want to get total sum value for every customer within Due Taka update column in table like this 10+2+4+2 = 18 this is my model.py file class CustomerInfo(models.Model): customer_name = models.CharField('Customer Name', max_length=100) customer_mobile_no = models.CharField( 'Mobile No', null=True, blank=True, max_length=12) customer_price=models.IntegerField('Customer Price',default=1) customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10) customer_sell_date = models.DateTimeField('date-published', auto_now_add=True) customer_product_id=models.CharField('Product ID',max_length=300,null=True, blank=True) customer_product_name=models.TextField('Product Name') customer_product_quantity=models.IntegerField('Quantity',default=1) customer_uid = models.CharField(max_length=6, blank=True, null=True) customer_info=models.TextField('Customer Details Informations', blank=True, null=True) customer_conditions=models.CharField('Conditions',blank=True, null=True, max_length=300) customer_due_taka_info=models.IntegerField(default=0) customer_discount_taka=models.IntegerField(default=0) customer_first_time_payment=models.IntegerField('First Time Payment',default=0) customer_first_due_info = models.CharField('First Due Info',default='No due info', max_length=200, blank=True, null=True) customer_product_mrp=models.IntegerField('Products MRP', default=0) customers_refrence=models.CharField(max_length=100) customer_updated = models.DateTimeField(auto_now=True) customer_type=models.CharField('Customer Type', default='MobilePhone', max_length=50) def __str__(self): return self.customer_name def remainBalance(self): if self.customer_price > self.customer_due_taka_info: remain=self.customer_price - self.customer_due_taka_info return remain def totalRetalsPerSingle(self): return self.customer_product_quantity * self.customer_product_mrp #def product_warrenty(self): #expire_date_oneyr =self.customer_sell_date+ datetime.timedelta(days=365) #return 'This product expire on this date ' + str(expire_date_oneyr) class Meta: verbose_name = ("গ্রাহকের তথ্য") verbose_name_plural = ("গ্রাহকের তথ্যসমূহ") #intregated with Customerinfo Model (Using foreignKey) class DueTaka(models.Model): customer_due = models.IntegerField('Due Taka', default=0) customer_due_date=models.DateTimeField(auto_now_add=True) customer_due_info=models.CharField('Due Info', max_length=200, blank=True, null=True) customerinfo = models.ForeignKey(CustomerInfo, on_delete=models.CASCADE) due_customer_updated = models.DateTimeField(auto_now=True) … -
Django View Usage
I'm still quite confused on when to use a View in django A view returns a webpage back or a HttpResponse. Suppose my website had a button "Get total" that adds up the numbers in a user-inputted checkbox To give this button functionality, what are the steps I would take? Would pressing the button call a URL, which would call a view, which would return a response? How would I "fetch" this response? I'm sorry this is vague, but I don't know what I need to search to be able to do the above using Django. Is this an example of REST? I want to create a form that can be processed by Django and then return a response to the user such as "Answer is correct", without refreshign the webpage. I am using django 1.11, I've been working with django for like a month now, and I"m starting to get better everyday (I can use models and all the similar stuff alright) but I'm stuck at this point forward -
How to embed related data in Django from models?
I've been working on Django since couple of days. I know how to get what I want in Laravel but I need help in Django. Suppose I have two tables. authors and books books table contain: id, name, author authors table contain: id, name With Laravel, I can just add a function which gives relationship between books and authors and Book::with('authors') will give me all the data of books along with extra field author which contains detail of the author of the book. I don't know how to do this Eager Loading with Django. -
'no [query] registered for [filtered]'
I am using haystack with elasticsearch backend for full text searching. I am wanting to show the search result using ajax. However I am getting an error of elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') . I build the index using python manage.py rebuild_index --verbosity=2 and it showed me 4 furnitured indexed as well I am just into this so I did not understand the below solution Django/Haystack error: elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception',...) Here filter should be replace with bool solution is provided but i dont know where is that file to change version of library used Django==1.11.6 elasticsearch==5.6.1 django-haystack==2.6.1 -
Django Model Factory get or create
I have a Django Model defined like below class CustomModel(models.Model): column = models.CharField(max_length=50, unique=True) Define a Factory for the model class CustomModelFactory(DjangoModelFactory): column = 'V1' FACTORY_FOR = CustomModel How do i make sure that factory implements get_or_create instead of a create everytime ? Does anyone know how can this be done ? -
Where is my django installation in windows 7
I use Django but I need to find the default templates and applications. I don't know where it's installed. How can I find that ? -
Can't load statics Django
Project structure: project_folder ├── apps │ ├── app1 │ ├── app2 ├── static │ ├── css │ │ ├── bootstrap.min.css │ ├── images │ └── js │ │ ├── bootstrap.min.js ├── templates │ ├── base │ │ ├── base.html Here is my settings.py: STATIC_PATH = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_PATH, ] I got this response: [10/Dec/2017 02:43:58] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1676 [10/Dec/2017 02:43:58] "GET /static/images/Logo-ISCAV.png HTTP/1.1" 404 1676 [10/Dec/2017 02:43:58] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 1670 [10/Dec/2017 02:43:58] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 1670 And here are some tags in the HTML {% load staticfiles %} <!DOCTYPE html> <html lang="es-CL"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta charset="UTF-8"> <title>ISCAV | {% block title %}{% endblock %}</title> <!-- Carga el path de los archivos estaticos y estilos --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {% block extrastatic %} {% endblock extrastatic %} </head> I can't see what is wrong. -
Django ModelMultipleChoiceField Form
On my website, I've got a "Compose Email" page with three fields - Subject, Recipients, & Body. In my database, I've got this custom user model in models.py: class MyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.CharField(max_length=100) def __unicode__(self): return self.user I want to create a form to import contacts that includes all of the MyUser objects. Currently, I've got this in forms.py: class ContactForm(forms.Form): contacts = forms.ModelMultipleChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), queryset=MyUser.objects.all().order_by('user'))#, empty_label=None) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['contacts'].queryset = MyUser.objects.all() In my views.py, I've got the following view: def import_contacts(request): contact_form = ContactForm() if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid: # send data to be processed return render(request, 'compose_email.html', { 'contact_form': contact_form, }) errors = contact_form.errors or None # form not submitted or it has errors return render(request, 'apple/contact_import_form.html', { 'contact_form': contact_form, 'errors': errors, }) return render(request, 'apple/contact_import_form.html', {'ContactForm': form}) contact_import_form.html ... <div class="form-panel"> <form method="post"> {% csrf_token %} {{ form.as_p }} <div id="sub"> <button type="submit" class="button">Add</button> </div> </form> </div> ... And finally, here is the .html file from which I link to import_contact_form.html compose_email.html: ... <a class="emailButton" id="b1" href="/gordie/home/templates/">Import Template</a> <a class="emailButton" id="b2" href="/home/send_email/import_contacts/">Import Contacts</a> <!-- <button class="emailButton" id='b2'>Import Contacts</button> --> <div class="form-panel"> <form method="post"> {% … -
whatsapp has banned my 3 mobile numbers
I am developing an application in django which will listen whatsapp messages and echo back to corresponding sender. I am using selenium webdriver in python and javascript to do this. Following code is the 'whatsapp_login' view function which launches a firefox instance in which I read the qrcode and login at https://web.whatsapp.com/ from django.http import HttpResponse from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import json from django.core import serializers from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import os from django.views.decorators.csrf import csrf_exempt driver = None @csrf_exempt def whatsapp_login(request): global driver profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True driver = webdriver.Firefox(firefox_profile=profile) driver.get('https://web.whatsapp.com/') script_path = os.path.dirname(os.path.abspath(__file__)) script = open(os.path.join(script_path, "jquery.js"), "r").read() driver.execute_script(script) script_path = os.path.dirname(os.path.abspath(__file__)) script = open(os.path.join(script_path, "add_eventlistener.js"), "r").read() driver.execute_script(script) resp = HttpResponse('show qrcode page') return resp I have passed the 'jquery.js' and my 'add_listener.js' files to selenium webdriver's 'execute_script' method. 'add_listener.js' script contains MutationObserver code which adds listener to each of contact list in whatsapp web. Following is my 'add_listener.js' code var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if(mutation.attributeName === 'class') { var attributeValue = $(mutation.target).prop(mutation.attributeName); console.log("attributeValue: "+attributeValue); if(attributeValue.indexOf('hover') > -1) { var user … -
How to Rehydrate React Components of Python App with Server-side Rendering
I'm using the python-react library to create a Django app with server-side rendering of react components. Although I've implemented basic rendering successfully, I've been unable to rehydrate the DOM - so React event handlers aren't working. Any thoughts on how to resolve? I've tried including a script tag with a webpack bundle. My code closely resembles an app the docs provided as a basic example; that app is available here: https://github.com/markfinger/python-react/tree/master/examples/basic_rendering. Please note that the example app uses Flask. -
Writing nested queries in Django
I am trying to write a nested query in Django. It is very simple to do in SQL, but with Django I am having some trouble deciding if I am doing it right or not. I have three models. Area, Location, and Measurement. Area class Area(models.Model): name = models.CharField(max_length=200) longitude = models.FloatField() latitude = models.FloatField() Location class Location(models.Model): name = models.CharField(max_length=200) altitude = models.IntegerField() area = models.ForeignKey(Area, on_delete=models.CASCADE) Measurement class Measurement(models.Model): value = models.FloatField() date = models.DateTimeField() location = models.ForeignKey(Location, on_delete=models.CASCADE) Inside Area, I need a function that will return the average of the measurements for this area. So basically, I need the average measurements of all locations for this area. Area can have many locations, but locations can have one area. In the Area Model, I made this function: def average_measurement(self): all_locations = self.location_set.all() return all_locations.measurement_set.all().aggregate(Avg('value')) This is my equivalent to writing a nested query in Django. I get all locations first and then find the average of all their measurements. Am I doing this correctly? On a side question, would this query be equivalent to doing something like this: avg = 0 locations = self.location_set.all() sum = 0 counter = 0 for l in locations: measurement = l.measurement_set.all() … -
migration error with Django 1.8
I'm brand new to Django and Python. So I git cloned the code from my team's repo. Then I started virtualenv, and did pip3 install -r requirements.txt. started the server. I think I also installed sqlite3/sqlite/mysql. i made some changes to db through 127.0.0.1:8000/admin. then i couldn't find the added info in homepage. So i ran python manage.py migrate. Terminal return this error: Traceback (most recent call last): File "manage.py", line 16, in execute_from_command_line(sys.argv) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/init.py", line 338, in execute_from_command_line utility.execute() File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/init.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv self.execute(*args, **cmd_options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute output = self.handle(*args, **options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/init.py", line 120, in call_command return command.execute(*args, **defaults) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute output = self.handle(*args, **options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in init self.loader = MigrationLoader(self.connection) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in init self.build_graph() File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/loader.py", line 299, in build_graph _reraise_missing_dependency(migration, parent, e) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/loader.py", line 282, in _reraise_missing_dependency raise exc django.db.migrations.graph.NodeNotFoundError: Migration contenttypes.0002_remove_content_type_name dependencies reference nonexistent parent node (u'contenttypes', u'0001_initial') i removed all the pyc files, still the same error python 2.7 Django 1.8 -
How to store a DOMDocument (Node) object in Django?
Background I would like to store the text a user is highlighting when they click a button. I first get the Range from a user's selection with window.getSelection().getRangeAt(0). Given this [Range] object, I would like to be able to store some data in my Django server so that when another user visits my website, they can see what others highlighted. If you know the answer, stop reading here. The following are solutions I have considered. I am wondering how I could do this most efficiently. Possible Solutions: Creating a Node Field in Django. I am not extremely experienced in Django. However, I was wondering if it would be possible to write a custom Django Field which stores a Range or Field object. It would be ideal for the field to work like so: script.js function getSelectionRange() { return window.getSelection().getRangeAt(0); } $.post({ url: "http://127.0.0.1:8000/range/", data: { string_key: foo().toString(), ... range: getSelectionRange() }, processData: false }); views.py ... range = Range.objects.create(range=request.POST.get('range') ... or, with a field for Node objects: ... first_node = Node.objects.create(node=request.POST.get('first_node') end_node = Node.objects.create(node=request.POST.get('end_node') ... Would the ajax call work? Would string values be a Python str in my views.py using request.POST.get('string_key')? Reconstructing the Range object using its constructor: The …