Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import oauthenticator.LocalDjangoAuthenticator to JupyterHub?
Following the instructions from https://github.com/AaaCabbage/oauthenticator, I have cloned and installed django.py, made a Django Application and added the following lines to the jupyterhub config file: from oauthenticator.django import LocalDjangoOAuthenticator c.JupyterHub.authenticator_class = 'oauthenticator.LocalDjangoOAuthenticator' But I get an error saying: The 'authenticator_class' trait of instance must be a type, but 'oauthenticator.LocalDjangoOAuthenticator' could not be imported Full output pasted on https://pastebin.com/GHTHchS8 when running jupyterhub --debug Full jupyterhub_config.py content: https://pastebin.com/9XQGV8GY Thank you! -
Django REST Api with Django templates?
Does it even make sense to create a REST Api in Django and have your front end as Django templates? -
How do I use the same navbar if I have two different templates? base_generic & blog_generic
One template separates the site content into two columns. Another template does not. The template that only has one column will be used for homepage (when not signed in), and settings page. The template with two columns (content main & content sidebar) will be used for everything else. I tried adding: {% include "base_navbar.html" %} that only contained my nav tags, but nothing happened. -
Django: update_or_create repeated values being populated
I'm trying to update the fields of a model using update_or_create which is getting the data from an api. The problem is that all the fields are being populated with only the last two values from of i['Concessional] and i['Noncessional'] I'm using an external api to update the following model: class Contributions(models.Model): trustee = models.ForeignKey(Trustee, on_delete = models.CASCADE) concessional_caps = models.FloatField(null = True, blank = True) noncessional_caps = models.FloatField(null = True, blank = True) concessional_contributions_to_this_fund = models.FloatField(null = True, blank = True) non_concessional_contributions_to_this_fund = models.FloatField(null = True, blank = True) concessional_contributions_to_other_fund = models.FloatField(null = True, blank = True) non_concessional_contributions_to_other_fund = models.FloatField(null = True, blank = True) concessional_contributions_as_allocated =models.FloatField(null = True, blank = True) non_concessional_contributions_as_allocated = models.FloatField(null = True, blank = True) concessional_amounts_above_caps = models.FloatField(null = True, blank = True) non_concessional_amounts_above_caps = models.FloatField(null = True, blank = True) concessional_available_total = models.FloatField(null = True, blank = True) non_concessional_available_total = models.FloatField(null = True, blank = True) Using the following code: for i in range(len(contribution_caps_data['Data']['Members'])): Contributions.objects.update_or_create(trustee = Trustee.objects.get(trustee_name = contribution_caps_data['Data']['Members'][i]["Name"])) for j in contribution_caps_data['Data']['Members'][i]['YearBreakdown']['ContributionDetails']: Contributions.objects.update_or_create(trustee = Trustee.objects.get(trustee_name = contribution_caps_data['Data']['Members'][i]["Name"]), defaults = { 'concessional_caps': j['Concessional'], 'noncessional_caps': j['NonConcessional'], 'concessional_contributions_to_this_fund': j['Concessional'], 'non_concessional_contributions_to_this_fund': j['NonConcessional'], 'concessional_contributions_to_other_fund': j['Concessional'], 'non_concessional_contributions_as_allocated': j['NonConcessional'], 'concessional_contributions_as_allocated': j['Concessional'], 'non_concessional_amounts_above_caps': j['NonConcessional'], 'concessional_amounts_above_caps': j['Concessional'], 'non_concessional_amounts_above_caps': j['NonConcessional'], 'concessional_available_total': j['Concessional'], … -
Django DateTimeField received a naive datetime
The problem I have is that I don't seem to be able to filter my data based on timestamp, i.e. both date and hour. My model looks as follows: # Create your models here. class HourlyTick(models.Model): id = models.IntegerField(primary_key=True) timestamp = models.DateTimeField(blank=True, null=True) symbol = models.TextField(blank=True, null=True) open = models.IntegerField(blank=True, null=True) high = models.IntegerField(blank=True, null=True) low = models.IntegerField(blank=True, null=True) close = models.IntegerField(blank=True, null=True) trades = models.IntegerField(blank=True, null=True) volume = models.IntegerField(blank=True, null=True) vwap = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'xbtusd_hourly' My view: class HourlyTickList(ListAPIView): serializer_class = HourlyTickSerializer def get(self, request): start = request.GET.get('start', None) end = request.GET.get('end', None) tz = pytz.timezone("Europe/Paris") start_dt = datetime.datetime.fromtimestamp(int(start) / 1000, tz) end_dt = datetime.datetime.fromtimestamp(int(end) / 1000, tz) qs = HourlyTick.objects.filter(timestamp__range = (start_dt, end_dt)) rawData = serializers.serialize('python', qs) fields = [d['fields'] for d in rawData] fieldsJson = json.dumps(fields, indent=4, sort_keys=True, default=str) return HttpResponse(fieldsJson, content_type='application/json') The message I receive is: RuntimeWarning: DateTimeField HourlyTick.timestamp received a naive datetime (2017-01-15 06:00:00) while time zone support is active. RuntimeWarning) However, when I use make_aware to fix this error, I get the error: ValueError: Not naive datetime (tzinfo is already set) My database contains data that looks like this: 2017-01-06T12:00:00.000Z For some reason, the first option returns … -
Script timed out before returning headers: wsgi.py - Django on Elastic Beanstalk
I've got a Django app on Elastic Beanstalk. It works 99% of the time, but sometimes after submitting a request to a function in views.py the app times out, is offline for 3-5 minutes, then pops back online like nothing happened. The only signs of this in the logs are Script timed out before returning headers: wsgi.py Script timed out before returning headers: wsgi.py Script timed out before returning headers: wsgi.py then it's back to normal. I haven't seen an intense / abnormal amount of memory or cpu used during this. The times I've seen this occur: Seemingly randomly When my site was getting hit with a pentest/vulnerability scanner (increased traffic) When the app hadn't been used in a few days and was suddenly used again I'm at a loss for how to debug this. django.config container_commands: 01_migrate: command: "python manage.py migrate --noinput" 02_collectstatic: command: "python manage.py collectstatic --noinput" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: analyzer/wsgi.py aws:elasticbeanstalk:container:python:staticfiles: /static/: static/ files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: | RewriteEngine On <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'"> RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L] </If> I've got the default NumProcesses=1 and NumThreads=15 on. I've found another SO post talking about this error, and their recommendation … -
custom PostgreSQL query execute to django app
i have two models with relationship one to many in django app using app using postgres/postgis database. i have create one not easy query in database and pgadmin panel and works correct. here the query : select string_agg(distinct app_work.id::text, ', ') AS code_work,string_agg(distinct app_work.stage, ', ') AS stage,string_agg(distinct app_work.dfield_work, ', ') AS dfield,app_point.geom from app_point, app_work where app_point.id=app_work.point_field_id GROUP BY app_point.id; now i want to use this query(i need that results from this query) in my django app to create a geojson or json export. i am not sure how convert this query using django method objects and queries(like point.objects.all()) i try to use custom postgres query like this : models.py class point(models.Model): geom = models.MultiPointField(srid=4326) objects = models.GeoManager() def __unicode__(self): return str(self.id) class meta: verbose_name_plural="point_info" class work(models.Model): dfield_work = models.CharField(max_length=100,blank=True, null=True) stage = models.CharField(max_length=100,blank=True, null=True) field1 = models.CharField(max_length=100,blank=True, null=True) field2 = models.CharField(max_length=100,blank=True, null=True) point_field= models.ForeignKey('point', blank=True, null=True) def __unicode__(self): return str(self.id) vews.py from django.db import connection def points(request): cursor = connection.cursor() cursor.execute("""seselect string_agg(distinct app_work.id::text, ', ') AS code_work,string_agg(distinct app_work.stage, ', ') AS stage,string_agg(distinct app_work.dfield_work, ', ') AS dfield,app_point.geom from app_point, app_work where app_point.id=app_work.point_field_id GROUP BY app_point.id from log_point, log_work where log_point.id=log_work.point_field_id GROUP BY log_point.id""") row = cursor.fetchall() print row … -
How to increase the visits only the first time the user accesses the page?
I want to do the following: every time a user enters an article, it increments the visit by +1, but only the first time the user logs in, so I have to save the fact that the user has already entered the page in some place. But I'm not using authentication or anything like that. I know I can use javascript to store in LocalStorage, but I still do not know how to work with APIS in the back end. What's the easiest way to do this on the backend? Currently the function that increments is as below. NOTE: I create a new object instead of using something like "instance.visits + = 1" because I need to save the date of each visit to filter the posts with more visits in a certain period of time, and that was the only way I got it. class ArticlePage(Page): # .... def serve(self, request, *args, **kwargs): request.is_preview = getattr(request, 'is_preview', False) self.views.create(date=datetime.datetime.now()) self.save() print(self.views.all().count()) return TemplateResponse( request, self.get_template(request, *args, **kwargs), self.get_context(request, *args, **kwargs) ) class ArticlePageViews(models.Model): article = models.ForeignKey( ArticlePage, on_delete=models.CASCADE, related_name='views' ) date = models.DateTimeField() def __str__(self): return f'{self.date}' -
Django ORM underscore wildcard
I have been searching for a way of using Django ORM to use the SQL underscore wildcard, and do something equivalent to this: SELECT * FROM table WHERE field LIKE 'abc_wxyz' Currently, I am doing: field_like = 'abc_wxyz' result = MyClass.objects.extra(where=["field LIKE " + field_like]) I already tried with contains() and icontains(), but that's not what I need, since what it does is adding parenthesis to the query: SELECT * FROM table WHERE field LIKE '%abc/_wxyz%' Thanks! -
Django template overrides not loading
New to Django. I'm trying to customize the change_form.html template right now. However, Django is simply refusing to load the local one I have created. My app is listed in INSTALLED_APPS. APP_DIRS is set to True. I even hardcoded an absolute path to a base directory templates folder. At this point I literally have templates in every single possible folder and location Django would look for custom templates overrides. If I alter the base template my change_form and change_list do update. What am I missing here? INSTALLED_APPS = [ 'quizzes', # my app 'django.contrib.admin', #snip TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { Locations I have the templates already: /templates (at the same level as manage.py) /templates/quiz /templates/quizzes /online_training/templates (the main project folder) /quizzes/templates (main app folder) /quizzes/templates/quiz /quizzes/templates/quizzes /quizzes/admin /quizzes/admin/templates /quizzes/admin/quizzes /quizzes/admin/quiz I'm trying the shotgun approach here, and either I completely missed the correct folder to put this stuff in, or something is jacked. -
Django search form returning entire model
I'm trying to make a simple search form for class based views with Django. Everything seems to work, except the search result returns the entire model, so obviously the search/filter isn't working. I cannot figure out why after reading a bunch of tutorials and questions here. models.py: class surveys(models.Model): FAN = models.SlugField(max_length=100, blank=True, null=True) Location = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.FAN def get_absolute_url(self): return reverse('survey-detail', args=[str(self.FAN)]) views.py: class Search(generic.ListView): template_name = 'datalibrary/search.html' model = surveys def get_queryset(self): try: name = self.kwargs['name'] except: name = '' if (name != ''): object_list = self.model.objects.filter(FAN__icontains == name) else: object_list = '' return object_list search.html: {% extends "base_generic.html" %} {% block content %} <form method="get" action="/results/" class="navbar-form pull-right"> <input type="text" id="searchBox" class="input-medium search-query" name="search" placeholder="Search"> <input type="submit" class="btn" value="Search" > </form> {% endblock %} search_results.html: {% extends "base_generic.html" %} {% block content %} {{ object_list }} {% endblock %} Any idea why object_list returns all the values in the model rather filtering based on the input, even when there's no input? -
How can I get a Django view.py to request a selected posts information such as primary key?
I have a Django project with an HTML file that lists all of the CSV files that have been uploaded to my Postgresql database and when you click on the CSV of interest a new page is rendered with the CSV model's basic information (name/time submitted). This is the First Page: {% for csv in Data_List %} <a href = "{{csv.id}}"><button class="btn btn-primary" style = "font-size:1.2em;" >{{csv.name}}</button></a> <br><br> {% endfor %} This is the second page: <p>{{request.user.username}}'s Note <h6>{{worklog.name}} <br> {{worklog.date}} <br> {{worklog.notes|safe}} <br> {{worklog.mycsv|safe}} </h6> </p> However, my goal is that when you click the button a python VIEW will be passed (or just retrieve) the chosen posts primary key (or other information). I want to do this so the view can ask the database for the actual CSV and do some work. How can I get a view.py to request a selected posts information such as primary key? Thanks and Happy Coding -
Django filter "less than" datetime not working correctly
I am trying to filter a Django queryset by timestamp (less than a certain value). However, the filter seems to be letting through records that are NOT less than the specified timestamp. Here is an example function: def check_jobs_status_3(): current_time = datetime.utcnow() time_threshold = current_time - timedelta(seconds=60) print("$$$$$$$$$$$$ current_time = {}, timedelta = {}, time_threshold = {}".format(current_time,timedelta(seconds=60),time_threshold)) stuck_jobs_qs = Job.objects.filter(last_updated__lt=time_threshold) for stuck_job in stuck_jobs_qs: print("############################## Job #{} (last_updated = {}) no encoding status after {} seconds. Re-enqueueing.".format(stuck_job.id,stuck_job.last_updated,get_video_encoding_timeout_seconds())) Here is the output: $$$$$$$$$$$$ current_time = 2019-03-14 20:54:15.221554, timedelta = 0:01:00, time_threshold = 2019-03-14 20:53:15.221554 ############################## Job #20 (last_updated = 2019-03-14 20:54:15.221264+00:00) no encoding status after 60 seconds. Re-enqueueing. As you can see, I am receiving a record with last_updated set to 2019-03-14 20:54:15, which is NOT less than the filter value of 2019-03-14 20:53:15 Here is the definition of the last_updated field: last_updated = models.DateTimeField(auto_now=True) What could the problem be? -
Super class retrieve attributes from a class that inherits it
Is it possible to do in python a class that takes attributes of the class that inherits from it? Something more or less like the Django models class Meta. If possible sample code -
Static files stored locally with django and electron
I recently found out about electron. I also know Django and wanted to make Desktop apps with the knowledge I already have. So I was wondering if it is possible to store the templates and static files of my app on a local machine and connect to the Django server get all the information and fill the templates. Here's an example: {% extends 'blog/base.html' %} {% block body_block %} <div class="shadow-lg p-3 rounded postcontent"> <h1>{{post.title}}</h1> <p class="postinformation">By {{post.author}} on {{post.date_published}}</p> <hr> <p>{{post.text}}</p> </div> {% endblock %} In this example is it possible if all the template files would be stored locally like this and then make a request to the Django server which will provide the information such as the post's title, author, content, etc. -
Django: Is there a way to serialize a Model Field instead of Model?
is there a way to implement a serializer for a field? I have a custom field that is subclass of models.TextField like this: class UpperCaseField(models.TextField): pass I would like to use it in a Person model like this: class Person(models.Model): first_name = models.TextField() last_name = UpperCaseField() Users can create Person object like this: student = Person(first_name='John', last_name='Doe') but I want to save it as John DOE, instead of John Doe. For each object save, I would like to convert last_name to uppercase before saving DB. so I need to write a serializer for UpperCaseField. How can I do this? I can override model's save method but I want to do it on field-level, so I dont have to repeat same logic on any other models that I use UpperCaseField as field. -
Python dictionary inaccessible in django template
I want to access dictionary values with keys passed from view to template. Although after hours of search and struggle, I still am unable to predict the reason. Below are the pictures. post method in views.py def post(self, request): value = request.POST['value'] if value is '': return redirect('home') else: start_time = time.time() obj = CalcClass(value) result=obj.calculate() end_time = time.time() - start_time output={} output['result']=result output['end_time']=end_time return render(request, 'fibohome/home.html', output) template home.html <div class="col-sm-6 col-md-6"> <div class="panel panel-default"> <div class="panel-body"> {% if output %} <h3>Output</h3> <h4>{{ output.result }}</h4> <h3>Time required</h3> <h4>{{ output.end_time }}</h4> {% else %} <h3>None</h3> {% endif %} </div> </div> </div> front end UI- after submitting with any number, it just shows None. Although I get output in console. Hope I've provided enough info. Thanks! -
Django only serving a single static file
I just got started in Django a few days ago from Ruby and have only run into one really annoying problem that I just can't seem to figure out on my own. I've tried everything I can think of to no avail. I am trying to serve up two static files, a custom CSS file (style.css) and a bootstrap.min.css file. While this should be very easy as everybody keeps telling me, I must be staring at the outside of the box because I can't fix it. I would like to note, it does not work in both live (which I don't expect it too because I don't have a root set) or local environments. It currently will only serve up bootstrap.min.css my settings file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] My Main Template: <head> <meta charset="utf-8"> <title>{% block title %}Django Boards{% endblock %}</title> <link href="https://fonts.googleapis.com/css?family=Peralta" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> My File Structure: Main Project boards project1 static css bootstrap.min.css (loads first files) style.css (wont load second file) templates manage.py db.sqlite3 -
One to Many queries in djagno
This is my City object class City(Base): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=255) latitude = models.FloatField() longitude = models.FloatField() And this is my user, class User(AbstractBaseUser, PermissionsMixin, Base): username = models.CharField(db_index=True, null=False, unique=True, max_length=255) mobile = models.CharField(db_index=True, max_length=100, null=True, unique=True) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) How do I query cities which have more than 1 user? -
advance PostgreSQL query to django method to GeoJson format
i have two models with relationship one to many (table 1(point) is fk in table 2(work)) in django app using postgres/postgis database. first table(point) is with geometry field second table(work) is simple table. anyway i have create a simple query in pgadmin and in that panel my query work perfect and takes correct results. Now i have two options where cant complete it myself,first is how to translate that query in django method (using object or something else) in the views.py and second if it can not happen that way how to run that query in django views.py. for both two options have scope to create geojson link to use in leaflet. here the query : select string_agg(distinct app_work.id::text, ', ') AS code_work,string_agg(distinct app_work.stage, ', ') AS stage,string_agg(distinct app_work.dfield_work, ', ') AS dfield,app_point.geom from app_point, app_work where app_point.id=app_work.point_field_id GROUP BY app_point.id; thanks -
html in django page to limit length of text
I am building a tool in django. It allows myself, and others, to make entries (imagine a journal) for various 'topics'. When the topic is clicked a page opens ('topic' page) that shows the entries. I am trying to limit the length of that text to 200 characters such that if someone wants to see the whole entry, they need to click on that entry to open it up to its specific page. I have tried putting a maxlength="200" in a few different places. But nothing worked. The only thing I did that kind of worked was to create a 'textarea' with a maxlength="200" but that was visually odd and unappealing. I know there has to be some way to limit the length in the existing code, without creating a new area and putting the entry in there. Below is the code for the 'topic.html' page. I am thinking that should be enough. If you need the views.py or models.py, let me know. {% extends "AARs/base.html" %} {% block header %} <h2>{{ topic }}</h2> {% endblock header %} {% block content %} <p> <a href="{% url 'AARs:new_action' topic.id %}">Add new action</a> </p> {% for action in actions %} <div class="panel … -
Django : Storing important constants in Database and loading onto the project whenever necessary
I am building a django based backend. There are some very important constants (or you can say data) which defines the functioning of the whole project. I want to store this information in the database so that anyone with admin permission can update those constants via an api call. I could store those constants in setting.py file but then I have to edit the python file every time I update it. I want a non technical person be able to update the data via some web form. One thing I can do is make a database query every time I use those data. Or is there is some concept of local storage in django like cookies. so whats the best policy -
Updating files when deployed
I am trying to update files on a project that already has been deployed. The changes are not taking place when seeing it deployed, though when I sudo vim these files via GitBash, it shows the changes. Here's how I did when I'm logged into the server Ubuntu via AWS. CD into the project git add . git commit -a -m "message" git pull origin master (it comes out a Nano screen--so I input a message then Ctrl X and then respond "no") and it shows the changes through vim. There's no changes when I refresh the deployed project, and not even when I reboot it via AWS. Can someone please share the steps to make changes and show changes on a deployed project? Thank you so much, I appreciate your feedback! -
How does multiplexing in Django sockets work?
I am new at this part of web developing and was trying to figure out a way of creating a web app with the basic specifications as the example bellow: A user1 opens a page with a textbox (something where he can add text or so), and it will be modified as it decides to do it. If the user1 has problems he can invite other user2 to help with the typing. The user2 (when logged to the Channel/Socket) will be able to modify that field and the modifications made will be show to the user1 in real time and vice versa. Or another example is a room on CodeAcademy: Imagine that I am learning a new coding language, however, at middle of it I jeopardize it and had to ask for help. So I go forward and ask help to another user. This user access the page through a WebSocket (or something related to that). The user helps me changing my code and adding some comments at it in real time, and I also will be able to ask questions through it (real time communication) My questions is: will I be able to developed certain app using Django Channels … -
Django - Type Error "is not subscriptable"
I'm trying to create a list which consists of several calculations. next, the idea is to render it in a template. This is what I have so far: views.py : def calculation(request, itemslug): #All the Values ordered chronologically: values = Value.objects.filter(item__slug=itemslug).order_by('date') dates = [] results =[] #Create a list consisting of the dates for value in values: a = value.date dates.append(a) #Peform a calculation per date for date in dates: latestvalue = Value.objects.filter(item__slug=itemslug).get(date=date)['amount'] paidup = CashFlow.objects.filter(item__slug=itemslug).filter(date__lt=date).filter(type='cashin').aggregate(sum=Sum('amount'))['sum'] try: result = round(latestnav/paidup * 100,2) except ZeroDivisionError : result = 0 results.append(result) return render(request, 'overview/detail.html', { 'result':results, }) unfortunately I get the TypeError : 'Value object is not subscriptable' + might be the case there are some other errors in my code.. Many thanks to have a look !! Thanks,