Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, wsgi StreamingHttpResponse not actually streaming
In a Django app that I am writing, a piece of it needs to support data streaming. This is supported via StreamingHttpResponse in Django. My application works completely as expected, except for the data seeming to be queued or buffered somewhere. I am not using Apache, or nginx, or mod_python. I am simply using Django and wsgi to run this locally at the moment. All the stream data is returned to the 'client' all at once, but when looking in Wireshark, they do actually come in separate packets, so I know everything is being assembled properly, it's just getting stuck in the pipe somewhere. I have no idea where this could be. My wsgi.py in my app looks like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE", "my_app.settings") application = get_wsgi_application() and the relevant views are like this: def stream(): for x in range(0, 5): yield json.dumps({'a':1},cls=DjangoJSONEncoder) + '\n' time.sleep(1) @condition(etag_func=None) @allow_http_method(['Post']) def request_stream(request): resp = StreamingHttpResponse(stream()) return resp There must be some configuration somewhere that needs to be changed, or something else kind of trivial, that I am just missing. -
Menu_Opciones() missing 2 required positional arguments: 'Pregunta' and 'Opciones'
I have a problem which evolve a script: "script.py" and a view in "views.py" in a django project. The goal is to show in a page a question: "Pregunta" and a list of options: "Opciones" In a part of the script I need to call a view's function "Menu_Opciones" in this way: ESI_App.views.Menu_Opciones(request, Pregunta, Opciones) In views.py I have the function defined in this way: def Menu_Opciones(request, Pregunta, Opciones): for i in range(len(Opciones)): ModelOpciones.objects.create(opciones=Opciones[i]) form = OpcionesForm(request.POST or None, field1_qs = ModelOpciones.objects.all()) context = { 'pregunta': Pregunta, 'form': form, } if form.is_valid(): opcion = form.cleaned_data['Campo_Opciones'] return render(request, "Menu_op.html", context) Here's the traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Menu_Opciones/ Django Version: 1.9.7 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ESI_App'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Miguel\Desktop\VenvProyecto\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\Miguel\Desktop\VenvProyecto\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /Menu_Opciones/ Exception Value: Menu_Opciones() missing 2 required positional arguments: 'Pregunta' and 'Opciones' More information: I have this error since I changed computer but I created a new proyect and app, copied the code, modified all paths, project files and folder names, app … -
Django compressor and manage.py compress problems
My problem: When debug=true in settings.py django compress works just fine, takes all the js concatenates everything and minifies, when debug-false is basically useless: if i set COMPRESS_ENABLED = True (default when debug=false) i get a 500 error, but don't really know what's going on: It:mysite italo$ ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 25, 2016 - 17:37:47 Django version 1.10, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [25/Aug/2016 17:37:51] "GET / HTTP/1.1" 500 6098 [25/Aug/2016 17:37:51] "GET /static/scss/app.css HTTP/1.1" 304 0 [25/Aug/2016 17:37:51] "GET /static/CACHE/js/f6979994c378.js HTTP/1.1" 200 3524 [25/Aug/2016 17:37:51] "GET /static/CACHE/js/029dc704a0f3.js HTTP/1.1" 200 3788 [25/Aug/2016 17:37:51] "GET /static/CACHE/js/bd8a8faf4632.js HTTP/1.1" 200 135985 [25/Aug/2016 17:37:51] "GET /static/CACHE/js/50721ef0285b.js HTTP/1.1" 200 98 [25/Aug/2016 17:37:51] "GET /static/CACHE/js/2f9428d5f621.js HTTP/1.1" 200 138405 looks like i get different javascript loaded (apparently not concatenating at all) but the files are minified... a my solution used to be to set COMPRESS_ENABLED = False on production and then write a script to do: 1) collectstatic 2) compress --force (because ompressor is disabled, i tried to enable it temporary before running runserver and using just compress but i get the same results) 3) runserver What i get is … -
django-excel how could I export sheet with model method as column
So I am trying to use django-excel to export a sheet of a certain model. Problem is there are some methods in this model that I also want to appear in the sheet. I tried to pass in those directly: query_record = Equipment.objects.all().values('manufacturer','_latest_calibration_date',) return excel.make_response_from_records( query_record, 'xls', file_name="sheet") in which manufacturer is a charfield and _latest_calibration_date is a method, and this doesn't work. Trying to save the work of creating the sheet from scratch, I tried this a link that seems to maintain value of a field with a method, and do: _latest_calibration_date = models.DateField(db_column = 'latest_calibration_date') @property def latest_calibration_date(self): return self._latest_calibration_date @latest_calibration_date.setter def latest_calibration_date(self): return Calibration.objects.filter(cal_asset__id = self.id).order_by('-id')[0].cal_date Still, this gives me errors like this: ProgrammingError at /calbase/export/sheet ('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'latest_calibration_date'. (207) (SQLExecDirectW)") Could somebody pls have me with this? -
Django and action attribute of form elements
HTML5 stipulates that action attribute of the form element "must have a value that is a valid non-empty URL potentially surrounded by spaces" (https://www.w3.org/TR/html5/forms.html#attr-fs-action). Could you help me understand why the documentation of Django always suggests this: {% csrf_token %} Example: https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/ Leaving action="" seems to be error prone. So, why is that? -
How to deploy a django-channels app on digital ocean using daphne and worker?
I am new to VPS server deployment. I am using digital ocean but dont know how to server my django-channels app using dapne and worker so that it runs my app every time someone hits my IP address -
Django CBV Authentication login/logout solution
I got the CBV setup to login from going to URL "/" of my Django website, but I was trying to get the login to redirect to the URL "/blah/" after successful login. This is my myapp/urls.py from django.conf.urls import include, url from django.contrib import admin from content import views as content_views urlpatterns = [ url(r'^', include('content.urls')), url(r'^(?P<slug>[a-zA-z0-9]+)/$', content_views.BlahDetailView.as_view(), name='blah_detail'),] Here is my content/urls.py from django.conf.urls import url from . import views app_name = 'content' urlpatterns = [ url(r'^$', views.IndexList.as_view(), name='index'), url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', views.LogoutView.as_view(), name='logout'), ] Here is content/views.py class LoginView(FormView): """ Provides the ability to login as a user with a username and password """ success_url = '/' form_class = AuthenticationForm redirect_field_name = REDIRECT_FIELD_NAME template_name = 'content/login.html' @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): # Sets a test cookie to make sure the user has cookies enabled request.session.set_test_cookie() return super(LoginView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): auth_login(self.request, form.get_user()) # If the test cookie worked, go ahead and # delete it since its no longer needed if self.request.session.test_cookie_worked(): self.request.session.delete_test_cookie() return super(LoginView, self).form_valid(form) def get_success_url(self): import ipdb; ipdb.set_trace() redirect_to = self.request.GET.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to class LogoutView(RedirectView): """ Provides users the ability to … -
Splitting Django CharField as if it's a string
I'm taking user input into a Textarea widget, then looping by line, and trying to split the three "words" (first name, last name, email) from each line into a list, which I'll then deal with later. When I use split() on the line, though, it always splits into characters, which I assume is part of the CharField def'n of the field, meaning that it's not a string and the split() method won't behave as I want it to. What's the workaround for that? class UserImportForm(forms.Form): importtext = forms.CharField(required=True,widget=forms.Textarea(attrs={'cols': 40, 'rows': 15})) elif "UserImport" in request.POST: g = UserImportForm(request.POST, prefix='usrimp') rawtext = g['importtext'].value() if g.is_valid(): newusers = [] for lines in rawtext: row = lines.split(" ") if len(row) == 3 and validate_email(row[2]): newusers.append(row) -
Response with content disposition equal to 'attachment' not returning downloaded file
I am using Python to create a csv file in Django. The function to create the csv file is hit through an AJAX call. I am setting the response's Content-Disposition header equal to 'attachment', but It is not giving me a downloaded file. In my AJAX function on success, I am logging the returned data to the console, and can see that it prints out the csv file, but it doesn't download for me. The HttpReponse content_type is set to text/csv, but is the AJAX call somehow overriding that and returning it as JSON anyway ? def export_csv(request): queryset = request.POST.getlist('order_list[]') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="connection_activity.csv"' writer = Writer(response, excel) response.write(u'\ufeff'.encode('utf8')) writer.writerow([ smart_str(u"ID"), smart_str(u"Created On"), smart_str(u"Full Name"), smart_str(u"Shipping Address"), smart_str(u"Total Price") ]) for obj in queryset: order = Cart.objects.get(id=int(obj)) writer.writerow([ smart_str(order.id), smart_str(order.created_on), smart_str(order.first_name + ' ' + order.last_name), smart_str( order.shipping_street1 + ' ' + order.shipping_city + ', ' + order.shipping_state + ' ' + order.shipping_postal_code), smart_str(order.order_total) ]) return response JQuery AJAX function $('#export-data').on('click', function(){ var order_list = [] $('.result-row').each(function(){ var number = Number($(this).find('.cart_id').html()) order_list.push(number) }) $.ajax({ method: 'POST', url: '/cart/export', data: {csrfmiddlewaretoken: '{{ csrf_token }}', 'order_list': order_list}, success: function(data){ console.log(data) }, error: function(data){ console.log(data) } }) }) -
Django oauth2 request.user returns AnonymousUser
I'm a Django newbie and am trying to create an API to the backend for use by iOS client. Currently I am testing my API access with curl. I have successfully generated access tokens using: curl -X POST -d "grant_type=password&username=example_user&password=example_password" http://clientID:clientSecret@localhost:8000/o/token/ which generated the following response - { "access_token": "oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY", "scope": "write read", "expires_in": 36000, "token_type": "Bearer", "refresh_token": "pxd5rXzz1zZIKEtmqPgE608a4H9E5m" } I then used the access token to try to access the following class view: from django.http import JsonResponse from oauth2_provider.views.generic import ProtectedResourceView from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator class post_test(ProtectedResourceView): def get(self, request, *args, **kwargs): print(request.user) return JsonResponse({'Message': "You used a GET request"}) def post(self, request, *args, **kwargs): print(request.user) return JsonResponse({'Message': 'You used a POST request'}) @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super(post_test, self).dispatch(*args, **kwargs) with the following curl request: curl -H "Authorization: Bearer oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY" -X GET http://localhost:8000/api/post-test/ Which properly responds to the client with: {"Message": "You used a GET request"} But in the console, where I expect the request.user variable, I get AnonymousUser. Isn't the token supposed to be assigned to example_user? Shouldn't that be what request.user returns? -
SSL SYSCALL error: Bad file descriptor on Heroku with postgres and Celery
I've been using Celery successfully with a Django site on Heroku but it's just started generating the error below, which stops it running. It looks like it's having trouble with postgres, but I'm stumped as to how to fix it, given it's Celery rather than my code that's having the problem (I assume...). I'm using CloudAMPQ as a broker, and my Django settings include: CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' Here's the traceback from the Heroku logs: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.5/site-packages/kombu/utils/__init__.py", line 323, in __get__ return obj.__dict__[self.__name__] KeyError: 'scheduler' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.OperationalError: SSL SYSCALL error: Bad file descriptor The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.5/site-packages/billiard/process.py", line 292, in _bootstrap self.run() File "/app/.heroku/python/lib/python3.5/site-packages/celery/beat.py", line 553, in run self.service.start(embedded_process=True) File "/app/.heroku/python/lib/python3.5/site-packages/celery/beat.py", line 470, in start humanize_seconds(self.scheduler.max_interval)) File "/app/.heroku/python/lib/python3.5/site-packages/kombu/utils/__init__.py", line 325, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/app/.heroku/python/lib/python3.5/site-packages/celery/beat.py", line 512, in scheduler return self.get_scheduler() File "/app/.heroku/python/lib/python3.5/site-packages/celery/beat.py", line 507, in get_scheduler lazy=lazy) File "/app/.heroku/python/lib/python3.5/site-packages/celery/utils/imports.py", line 53, in instantiate return symbol_by_name(name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.5/site-packages/djcelery/schedulers.py", line 151, in __init__ Scheduler.__init__(self, *args, **kwargs) … -
Vue.js For loop is not rendering content
I am building a web application using vue.js, vue-resource, vue-mdl and google material design lite. JS compilation is performed using webpack through laravel elixir. In this app I have to render a table row for each object from an array returned from a Rest API (Django Rest Framework). I have made the following code inside the html to render content using vue.js: <tr v-for="customer in customers"> <td class="mdl-data-table__cell--non-numeric">{{ customer.status }}</td> <td class="mdl-data-table__cell--non-numeric">{{ customer.name }}</td> <td class="mdl-data-table__cell--non-numeric">{{ customer.company }}</td> <tr> This should render all objects in the array as a table row. I have also tried to wrap the above in a template tag like this: <template v-for="customer in customers"> <tr> <td class="mdl-data-table__cell--non-numeric">{{ customer.status }}</td> <td class="mdl-data-table__cell--non-numeric">{{ customer.name }}</td> <td class="mdl-data-table__cell--non-numeric">{{ customer.company }}</td> </tr> </template> This did not change either. I have also tried to hardcode the array inside the ready() function of the vue instance, but this did not help either. window._ = require('lodash'); require('material-design-lite'); window.Vue = require('vue'); require('vue-resource'); var VueMdl = require('vue-mdl'); Vue.use(VueMdl.default); const app = new Vue({ el:'body', ready: function(){ //this.getCustomerList(); this.customers = [ { name: "Peter", status: "true", company: "Company 1"}, { name: "John", status: "false", company: "Company 2"} ] }, data: { customers: [], response: null, … -
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured
I use django 1.10 with python 2.7 I have a problem running python script this script use models in django but not identify this. python contentui_app/content-util.py --sig Traceback (most recent call last): File "contentui_app/content-util.py", line 9, in from models import * File "/var/django-project/contentui/contentui_app/models.py", line 12, in class AuthGroup(models.Model): File "/var/django-project/contentui/contentui_app/models.py", line 13, in AuthGroup name = models.CharField(unique=True, max_length=80) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/init.py", line 1043, in init super(CharField, self).init(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/init.py", line 166, in init self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/usr/local/lib/python2.7/site-packages/django/conf/init.py", line 53, in getattr self._setup(name) File "/usr/local/lib/python2.7/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 or call settings.configure() before accessing settings. -
JSON serialization error in Django Rest Framework when using pagination
I just tried to add pagination using pagination_class = TenItemsSetPagination to my class-based-view. As a result, I get an error trying to access my endpoint: <Response status_code=200, "text/html; charset=utf-8"> is not JSON serializable views.py: class AllCartsView(ListModelMixin, generics.GenericAPIView): permission_classes = [AllowAny] authentication_classes = [] queryset = Cart.objects.all() serializer_class = carts_serializers.DataCartSerializer renderer_classes = (BrowsableAPIRenderer, JSONRenderer,) pagination_class = TenItemsSetPagination def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) paginators.py class TenItemsSetPagination(PageNumberPagination): page_size = 10 Versions : Django 1.9.9 / DRF 3.3 Any idea? Thanks. -
Django + DRF: Optimizing retrieval + serialization of model with multiple FKs
I'm using Django REST Framework to provide an API between a Django backend and AngularJS frontend. It's gone well so far- DRF is very easy to get started with, and the model-related viewsets & serialization make things very intuitive. However, I've started running into performance issues related to (I believe) heavily nested model serializers- which is certainly a common issue with DRF. I've been reading a lot about select_related() and prefetch_related(), as well as this very helpful guide. I think my particular situation may be a little different than the ideal setup for either of the eager loading methods, or (more likely) I'm missing something important about how they work. Even after adding a setup_eager_loading() as described in the link above, and trying both select_related() and prefetch_related() on the FKed fields of the model serializer causing issues, I'm not seeing any improvement. Example (but quite similar) models and serializers are below. models.py class BookLeaders(models.Model): reading_group = models.ForeignKey(ReadingGroup) most_books_read_user = models.ForeignKey(UserBookStats) most_books_read = models.IntegerField(default=0) fastest_read_time_user = models.ForeignKey(UserBookStats) fastest_read_time = models.IntegerField(default=0) highest_pages_single_night_user = models.ForeignKey(UserBookStats) highest_pages_single_night = models.IntegerField(default=0) least_books_read_user = models.ForeignKey(UserBookStats) least_books_read = models.IntegerField(default=0) slowest_read_time_user = models.ForeignKey(UserBookStats) slowest_read_time = models.IntegerField(default=0) most_books_owned_user = models.ForeignKey(UserBookStats) most_books_owned = models.IntegerField(default=0) most_books_read_user = models.ForeignKey(UserBookStats) most_books_read = models.IntegerField(default=0) class … -
How can I use an existing git repository in heroku
I'm using heroku for creating a web application in python-django. I need to use an existing git repository in heroku. The name of my repository is first-blog. When I'm using git clone https://github.com/heroku/first-blog.git I got Cloning into 'first-blog'... Username for 'https://github.com': AparnaBalagopal Password for 'https://AparnaBalagopal@github.com': remote: Repository not found. fatal: repository 'https://github.com/heroku/first-blog.git/' not found this. I connect my github to the heroku account. How can I possible to connect this repository to my app in heroku. -
how to search in django models if some fields are not required
so in my models i've got blank=True fields. I also have search in this model, but if some fields are blank=True user can not fill this fields. And what should I do if some fields are empty? For example I have model with name and surname(blank=True). If surname not fill in search form i should make one filter, but if surname is fill I should make FILTER with surname? -
How do I send emails using django-simple-email-confirmation?
I have just started using django-simple-email-confirmation. They have an example of how to use it, which invokes a send-email method, as below: email = 'original@here.com' user = User.objects.create_user(email, email=email) user.is_confirmed # False send_email(email, 'Use %s to confirm your email' % user.confirmation_key) # User gets email, passes the confirmation_key back to your server I was wondering where this send_email method came from. I can't find it by searching the repo, besides when they use it in this example (which does not import anything). Everybody else seems to use the send_mail method in django, so I was wondering what exactly was going on here? Thanks -
python : list index out of range error in sys.argv
I have this code that I have taken from to train to recognize hand written images. However I get compilation error. Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/distpackages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile execfile(filename, namespace) File "/home/jahangir/projects/Image-Digit-Recognitionmaster/multilayer_neural_network.py", line 287, in main() File "/home/jahangir/projects/Image-Digit-Recognition- master/multilayer_neural_network.py", line 212, in main f = open(sys.argv[1], 'r') IndexError: list index out of range I am not able to understand what is the cause of this problem. I am new to python and Google or stack did not have much explanation. This is my code : #! /usr/bin/python import sys import math import random import matplotlib.pyplot as plt num_hidden_units = 14 num_op_units = 10 num_ip_units = 28*28 eta = 1 threshold = 0.01 K = {} hidden_values = [4, 8] hidden = [] output = [] confusion_matrix = {} num_k = 2 mean_accuracies = [] def activation(x): if (x<-5): x = -5 ans = 1.0/(1.0 + math.e**(-1.0*x)) return ans def activation_derivative(x): temp = activation(x) return float(temp*(1-temp)) def test(inputs): z = [] for a in xrange(len(inputs)): y = [] for j in xrange(len(hidden)): s = 0 for k in xrange(len(inputs[a])): s += float(inputs[a][k]*hidden[j][k]) y.append(activation(s)) z.append([]) for i in xrange(len(output)): s = 0 for … -
Errno 13 Permission denied with Django on a directory I don't want to use
I have this error appearing in my Django app on my production server : [Errno 13] Permission denied: '/var/www/.config' I never asked to access to this unexisting file or directory in my code. The server is running in a different directory defined in my httpd.conf and I haven't defined the use of any /var/www/ elements in my Django settings. In my case I'm using the biopython library with Django : from Bio import Entrez Entrez.email = "my@email" handle = Entrez.efetch("taxonomy", id="123, 1") records = Entrez.parse(handle) This code is working in a python console on the server. But the instruction Entrez.parse(handle) return the error in a Django environment. I haven't seen any instruction asking to write or open anything in the source code of the function so it seems to be a problem with Django? Is it a configuration problem? A background Django function trying to access to a file when I call a specific function? My configuration : Python 3.3 Django 1.8 Biopython 1.67 -
Queryset is returned inside children key
I wanted to list all the reviews along with the replies to specific review of specific restaurant but i could only list the review. While trying to fetch all the replies to its specific review, i called the children() which is defined in Review model. It returned queryset. On the other hand i want all the specific replies with the name of replier. serializers.py class ReviewSeraializer(ModelSerializer): reply_count = SerializerMethodField() children = SerializerMethodField() class Meta: model = Review read_only = ('id',) fields = ('id','content_type','object_id','parent','review','children','reply_count','created') def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0 def get_children(self, obj): obj_children = [] if obj.is_parent: return str(obj.children()) # for obj in obj.children(): # print(obj.review) # obj_children.append(obj.review) # return str(obj_children) return None review/models.py class Review(models.Model): reviewer = models.ForeignKey(User, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True, related_name="parent_review") review = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ReviewManager() def children(self): # replies return Review.objects.filter(parent=self) @property def is_parent(self): if self.parent is not None: return False return True How to list all the replies and replier name inside children key of a specific review? -
May I display the field from other table in the template in Django 1.10?
May I display the field from other table in the template in Django 1.10? I have 3 tables as the following models.py import datetime from django.db import models from django.forms import ModelForm from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Group(models.Model): group_name = models.CharField(max_length=255) no_of_monk = models.IntegerField() def __str__(self): return self.group_name class Meta: ordering = ['id'] @python_2_unicode_compatible class Tbl_Province(models.Model): province_code = models.CharField(max_length=2) province_name = models.CharField(max_length=150) geo_id = models.IntegerField() def __str__(self): return self.province_name @python_2_unicode_compatible class Contact(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) order = models.IntegerField() name = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True) amount = models.DecimalField(max_digits=10, decimal_places=2) confirm = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) province = models.ForeignKey(Tbl_Province, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ['order', 'province'] and I would like to display tbl_province.province_name where id=contact.id in the following template, is it possible? {% for contact in group.contact_set.all %} <tr> <td width="10%" class="table-text"><div><strong>{{ forloop.counter0|mod:5|add:1 }}</strong></div></td> <td width="10%" class="table-text"><div>{{ forloop.counter }}</div></td> <td width="10%" class="table-text"><div>{{ contact.order }}</div></td> <td class="table-text"><div>{{ contact.name }}</div></td> {% if contact.province_id %} <td class="table-text"><div>{{ **Want to display tbl_province.province_name where id=contact.id here** }}</div></td> {% endif %} <td width="13%" class="table-text"><div><input type="text" name="ord" id="con-ord" class="form-control" value="{{ contact.amount|intcomma }}"></div></td> <td width="10%" class="table-text"><div>บาท</div></td> <td> <form action="{% url 'contribution:contactdel' contact.id %}" method="POST"> {% csrf_token … -
SSH tunnelling to a remote server with django
I'm trying to set up an SSH tunnel to access my server (currently an ubuntu 16.04 VM on Azure) to set up safe access to my django applications running on it. I was able to imitate the production environment with Apache WSGI and it works pretty good but since I'm trying to develop the application I don't want to make it available to broader public right now - but to make it visible only for a bunch of people. To the point: when I set up the ssh tunnel using putty on Windows 10 (8000 to localhost:8000) and I run http://localhost:8000/ I get the folowing error: "Not Found HTTP Error 404. The requested resource is not found.". How can I make it work? I run the server using manage.py runserver 0:8000. I found somewhere that the error may be due to the fact that the application does not have access to ssh files, but I don't know whether that's the point here (or how to change it). Regards, Dominik -
Solving django's manytomany symmetrical recursive through by extending field's through value
A lot was said about django's ManyToMany recursive/through/symmetrical "pick two" limitation. The best solution I could find online was Charles Leifer's symmetric relation implementation by manually creating links in both directions (by implementing add_relationship and remove_relationship). Although this is a valid implementation, I'm considering doing something a bit different and would like a general opinion about what I'm going to do. My question would be wether what I'm trying to do is a good or bad idea? Let Instance be a recursively relating object, and matches it's many to many field. I noticed matches has an @property object called through, and calling it returns an object of type Instance_matches. I'd like to inherit it in a model object we'll call MatchDetails, creating a Multi-table inheritance and manually making sure I create a MatchDetails object for every Instance_matches. Then, I could always get the extra attributes I originally wanted matches to have, by doing instance.matches.matchdetails. I did not try doing that, and would update on results after i get some community scrutiny. Thanks! -
Django query in one to many
I have 2 tables, User and Payment with a relationship of One-TO-Many. On payment I have the fields date_updated and status. Can I make in one query, to get all the users which have payments with date_updated < 3 months ago and if has other payments bigger than 3 months ago than the status should be different than completed. If such payments are found on an user than the user should be returned else not. For example I have the user with just one payment made last year, I want to be returned, but if the same user has another payment made recently than 3 months ago, and the status is completed than the user should not be returned. What I'm trying: User.objects.filter( Q(orders__payments__date_updated__lte=time_x_months) & Q(Q(orders__payments__date_updated__gte=time_x_months) & ~Q(orders__payments__status=Payment.STATUS_COMPLETED)) )