Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django loop inside loop is not working print on teamplates
i am using django framework with python2.7 and in model i am receiving the following values as a query resultset { "receivable": -90786.82, "payable": 8826.72, "receivable_aging": { "age5": 235114.91999999998, "age4": 235114.91999999998, "age3": 0, "age2": 0, "age1": 0, "range": [ {"age5": "overdue in 10 days"}, {"age1": "<30"}, {"age2": "30-60"}, {"age3": "60-90"}, {"age4": ">90"} ], "overdue": 235114.91999999998 } } by the above result set i want to display in django template as below receivable_aging > range >90 is has 0 #0 is from receivable_aging.age1 & >90 is from #receivable_aging.range.age1 30-60 is has 0 #0 is from receivable_aging.age2 & 30-60 is from #receivable_aging.range.age1 I new here , i tried lot of methods but not working pls help me on this my tries are, {% for key, value in response_bills.receivable_aging.items reversed %} <div class="invoice-box-content"> <span class="invoice-box-text"> 31 - 60 Days </span> {% if key not in "age5,range,overdue" %} <span class="invoice-box-value"> <i class="fa fa-inr fa-black fa-4" aria-hidden="true"></i> {{ value }} </span> {% endif %} </div> {% endfor %} -
Javascript strings : Appending django urls
I'm trying to create a simple url builder. For example in javascript I have: var url = document.URL; If I wanted to append something to the url I could just simply type its pattern, but in Django we can use something like this: url = url + "{% url 'object_view' %}"; alert(url); The problem is where the document.URL and Django URL creates a pattern like this: http://localhost:8000//objects/view/ I've tried looking at Javascript string manipulation such as trim() and replace(), but both doesn't have the manipulation to just drop the single slash in the string from document.URL. If I replace all () it may get affected if for example my document.URL is something like: http://localhost:8000/something/something2/ Any suggestions? -
Factory Boy and related objects creation
Some beginner question about Factory Boy: Let's say you have these models related this way: class Service: restaurant = models.ForeignKey(Restaurant) hist_day_period = models.ForeignKey(DayPeriod) class DayPeriod: restaurant = models.ForeignKey(Restaurant) I want to create a Service object, using a Factory. It should create all 3 models, but use the same restaurant. Using this code: class ServiceFactory(factory.django.DjangoModelFactory): class Meta: model = Service restaurant = factory.SubFactory('restaurants.factories.RestaurantFactory') hist_day_period = factory.SubFactory( 'day_periods.factories.DayPeriodFactory', restaurant=restaurant) Factory boy will create 2 different restaurants: s1 = ServiceFactory.create() s1.restaurant == s1.hist_day_period.restaurant >>> False Any idea on how to do this? It's unclear to me if I should use RelatedFactory instead of SubFactory to accomplish this. -
Django TimeStamped mixin with different created/modified fields
Here is the classic mixin used to know when a Django object is created or modified: class TimeStampable(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True The problem (it's not really a problem for most of us I guess) is that created and modified fields are not equals, at the first creation (there is a tiny delta between them). How would you improve this mixin to solve that specific issue? I checked django-model-utils source code but found nothing. I guess we would need to override __init__ method? -
GUI for a simulator
Good day to all, I have a general question but in need of a detailed answer. Sorry, I'm kind a noob in this. I have a project which requires me to build a web GUI for a simulator. I was told preferably to code it in python. But the thing is I'm not a python coder. I asked around my friends, some recommended me Tkinter, QT, Django... So my question will be, which framework will best suit me? (in designing the interface) I'm looking for something easy to work with, like those with drag and drop features but I also need heavy documentation on code like how to make a menu bar with drop out menu, to open / save a file function etc, create a select button, zoom in/out button, refresh button, a console window, and all you can think of when using a simulator. I need the interface to function as well, not those that print statement to command prompt I need to build that interface out, any recommendation? -
Django website tracked by piwik on same webserver
I'm trying to run a django website which is handled over the mod-wsgi module by an apache2 webserver and to track this site with piwik which is "running" on the same maschine and served by the same apache2 webserver. Piwik lives under /var/www/piwik/. <VirtualHost *:80> # ServerName www.example.com ServerAdmin admin@test.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /path/to/django/static-files <Directory /path/to/django/static-files> Require all granted </Directory> <Directory /path/to/django/wsgifile> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django-cms python-home=/path/to/python/env python-path=/path/to/django-project WSGIProcessGroup django-project WSGIScriptAlias / /path/to/django/wsgifile/wsgi.py # DocumentRoot /var/www/piwik # <Directory /var/www/piwik> # Require all granted # </Directory> </VirtualHost> Later running on port 443 (SSL). But what do I need to change to access piwik? Use seperate port for it? -
Index/Stock Quote on Website-Python-Django
I am trying to create a portfolio management website. I want to add a realtime ticker for some of the indexes and stocks. I can fetch the realtime data using googlefinance or some other module. But how can I display it on my website. -
Get URL response from Python swiftclient
While putting object into OpenStack Swift by swiftclient client library, I would like to have URL adress in the response from POST/PUT request, while posting file into storage. I utilize this code to post file into storage, but this method brings any response: import swiftclient conn = swiftclient.Connection( authurl=settings.SWIFT_AUTH_URL, user=settings.SWIFT_USERNAME, key=settings.SWIFT_KEY, tenant_name=settings.SWIFT_TENANT_NAME, auth_version='2.0', os_options={settings.SWIFT_REGION_NAME} ) with open(file_path, 'rb') as file: conn.put_object(container_name, file_name, contents=file.read(), content_type=some_format) Question is, how to produce response containing URL adress of uploaded file? -
Passing a fixed query term to django-haystack
I'm looking to make a page that displays a fixed set of search results using django-haystack. I already have a page that can be used to make searches using haystack's SearchView, and want to make a second page that by default shows the results from a specific search -- in this example, searching for all documents that contain Fruit. Here's my urls.py: from haystack.views import SearchView from django.conf.urls import url import haystack from .search_Queries import custom_query from .forms import CustomSearchForm urlpatterns = [ url(r'^fruit/', SearchView(form_class=CustomSearchForm, searchqueryset=custom_query)), url(r'^$', SearchView(form_class=haystack.forms.SearchForm, searchqueryset=custom_query), ] And I am trying to make the view display the initial Fruit search term by overriding the get_queryset method in the form -- however, this doesn't seem to be the correct way to go about it forms.py class CustomSearchForm(SearchForm): def get_queryset(self): queryset = super(CustomSearchForm, self).get_queryset() queryset = queryset.auto_query('Fruit') return queryset How can I display a set of search results for a specific term as the default in a view using django-haystack? I want to make a separate view so that my ^fruit/ URL shows the Fruit search results directly, rather than redirecting to /q=Fruit. -
Django models TextField/CharField: Remove null characters
I have a view that takes, in many parts, data from a, let's say, untrusted source, and I want to save the data in a Django model's TextField. The input may have null characters, and, if I understand correctly, Postgres (the backend of my project) prohibits saving null characters in the database. I could use str.replace to replace the null characters, but I would have to riddle my codebase with str.replace, since I have many points where I create models out of the untrusted data. Is there a way to force the cleaning of the data in the model level? I mean, so that I could do my_model.save() and in a unique place in my code have str.replace, instead of having it in all the places I have a TextField. -
Django - Limit object level access based on foreign key
I have a django data model that roughly looks like class Project: ... owner = FK(User) class User: ... project = FK(Project) class Data: .... project = FK(Project) And I'd like to enforce that a User can only interact (view/delete whatever) with Data if his he has a FK to the Project that the Data does. I can query this at every access point but I think that's error prone, and am also concerned about performance penalty of frequent joins. Are their other alternatives ? Thanks -
How can I turn an AngularJS template into a string?
I want to pass my variables into that template, let it render, and then get the resulting HTML as a string. How can I do that in AngularJS? Is there a similar function to the render_to_string() function in Django? The purpose is to make an API request to a service that sends emails and needs the html to be sent as a parameter of the request. Thanks a lot in advance! -
How to set instance variables in a class based view?
I want to check if a user is in a specific group on initilisation of the class based view. Then use that variable in a number of methods like get_form()and get_context_data() However I get an error: File "/projects/hr_project/entries/views.py", line 117, in get_form_class if self.is_manager: AttributeError: 'EntryCreateView' object has no attribute 'is_manager' Here is the methods in the class based view: def dispatch(self, request, *args, **kwargs): self.is_manager = False manager_group = Group.objects.get(name='Managers') if manager_group in request.user.groups.all(): self.is_manager = True def get_form_class(self): if self.is_manager: return ManagerEntryForm return UserEntryForm -
Django Foreign Key Not Rendering Related Model Data In Template
New to coding so apologies if this has been covered. Spent the last few evenings on Django's docs, YouTube, Google and here trying all kinds of ways to fix this. I have a model Route which is related to Driver and I am trying to display all the routes with the relevant drivers associated with that route on my template. However at the moment all I can get is the data from the Route model, not the associated Driver. Would appreciate any help on this as I'm struggling to get my head around it! Models.py class Driver(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) tel = models.CharField(max_length=120, blank=True, null=True) slug = models.SlugField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.first_name def save(self, *args, **kwargs): self.slug = slugify(self.first_name) super(Driver, self).save(*args, **kwargs) class Route(models.Model): leave_from = models.CharField(max_length=120, blank=True, null=True) destination = models.CharField(max_length=120, blank=True, null=True) date = models.DateField(auto_now_add=False, auto_now=False) time = models.TimeField(auto_now_add=False, auto_now=False) drivers = models.ForeignKey(Driver, on_delete=models.CASCADE) def __str__(self): return self.leave_from Views.py def drivers(request): qs = Route.objects.all().select_related() context = { "qs": qs, } return render(request, 'drivers.html', context) Template {% for instance in qs %} <p>{{ instance.user }} <br> {{ instance.first_name }} … -
Django Notifications when new alert fired in alertmanager
I have an application developed using django framework which displays alertmanager alerts in different format.I have a requirement in which i need to send a notification message to the web application when new alerts is being fired in alertmanager using django framework.I don't know how to implement that.Main doubt is, how to check in alertmanager when new alerts is fired.Kindly help me out in this.. -
Log long-running queries in django
We're running postgres and sometimes the django ORM generates long-running queries. You can log queries in postgres as detailed here. Any query generated by the log can be difficult to tie back to actual code that generated it. Is there a good way of tying a query to the actual code? -
ModelChoiceField - вопрос по required
Please explain , I have model = TestModel , which has attribute testatribute = models.CharField(blank=True , null=True,choices=test_choice, max_length=15) I Have been using this Form: tarrif = forms.ModelChoiceField(required=....) Task : filter form so that the value in the attribute testatribute was available in the form. TestModel.objects.all() - Cannot using because models has other attributes -
Django - How to pull a logged in users data from a database table?
I am relatively new to Django, and web development in general. Basically, I want to pull a logged in users data from a database table so he can view/edit it on a 'My profile' page. I'm guessing the best way to do this would be to call the logged in users 'id', then somehow use it to call the row in the database table I want? This is how far I have got, but I don't want the user's 'id' in the url, I want the users 'row id' in the database table: urls.py url(r'^my-profile/(?P<id>[0-9]+)', my_profile, name="my_profile"), views.py user = request.user template <a href="{% url 'my_profile' id=user.id %}">My profile</a> Any help would be much appreciated! -
Django - How to run a function inside a constructor?
As far as I've read, overriding the init function is not recommended in Django. Then how can I assign value to "hashed" and "salt"? They will not have the value of the original text, there are functions named def createSalt(self): and def createHash(self, salt, password): that will take the original text and convert it to something different. I tried this in model class but it didn't work: (it probably looks stupid ) salt = models.TextField(createSalt()) or salt = models.TextField(createSalt(self)) Another suggestion was to define a new function named create and use it like a constructor. But then it's not really a constructor, is it? Here is my model: class User(models.Model): username = db.Column(db.String(100), primary_key=True) hashed = models.TextField() salt = models.TextField() -
Insert count objects fields in Array Django Rest Framework
I get a problem in Django Rest Framework. class FeedDetailSerializer(ModelSerializer): user = UserFeedSerializer(read_only=True) comment_count = SerializerMethodField(default=0) comment_list = CommentFeedSerializer(many=True, read_only=True) class Meta: model = Feed fields = [ 'id', 'comment_count', 'comment_list', ] def get_comment_count(self, obj): comment_count = Comment.objects.filter(feed=obj.id, parent__isnull=True).count() return comment_count This is the CommentFeedSerializer I've created: class CommentFeedSerializer(ModelSerializer): url = comment_detail_url class Meta: model = Comment fields = [ 'url', 'id', 'comment', 'posted_on', ] With this Serializer I've done, API will render like this: "comment_count": 2, "comment_list": [ { "url": "http://localhost:8000/api/v1/comments/2/", "id": 2, "comment": "haha", "reply_count": 0, "posted_on": "2017-11-24T10:23:28.353000Z" }, { "url": "http://localhost:8000/api/v1/comments/1/", "id": 1, "comment": "Good", "reply_count": 1, "posted_on": "2017-11-24T09:54:48.680000Z" } ] But this is very hard to manage. So I want to put comment_count into comment_list: commentlist [comment_count:1, {}] How can I do that? -
Divide multipolygon Area into subarea
I am working on an application, where I have shapes (.shp) files, I have read those shapes file into my Postgres database and show those shapes file coordinates over the Google Map. Now I'm having a use-case, I need to divide these LGA (Local Governance Area) into sub area (like divide an LGA into 10km2 sub-area). Can anyone have any idea how can I do this using python/Django/GeoDjango? suggestions are welcome. Thanks -
How can I use the forloop.counter0 as a key in Django Template
I use a custom Widget to modify the context for the widget template (add more information). Context: 'selected': [[3, 9], [3, 4, 7, 6]], 'depth_levels': {0: [{'name': 'Category A', 'value': 3, 'depth': 0, 'parent_id': None, 'children': [4, 9]}, {'name': 'Category B', 'value': 8, 'depth': 0, 'parent_id': None, 'children': []}], 1: [{'name': 'Category A_1', 'value': 4, 'depth': 1, 'parent_id': 3, 'children': [5, 7]} {% for path in widget.selected %} {% for selected in path %} {% for level in widget.depth_levels.forloop.counter0 %} {{ level }} {% endfor %} {% endfor %} {% endfor %} First I cycle thru the selected(path) and the internal arrays(selected). I want to use the {{forloop.counter0}} as a key for depth_levels. The issue: {{widget.depth_levels.forloop.counter0}} doesn't return anything. If I use the key 'manually'{{widget.depth_levels.0}} is working returning the value, the array of dictionaries. My end goal is to access the name, value in the dictionaries that are in the array. -
I get a csrf error when saving db from django's admin
MIDDLEWARE_CLASSES = ( # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'django.middleware.security.SecurityMiddleware', ) This is my settins.py code. I have no problem logging in and viewing the db. If I press the save button to modify or add a db, I get a 403 error. -
(Django) ORM in airflow - is it possible?
How to work with Django models inside Airflow tasks? According to official Airflow documentation, Airflow provides hooks for interaction with databases (like MySqlHook / PostgresHook / etc) that can be later used in Operators for row query execution. Attaching the core code fragments: Copy from https://airflow.apache.org/_modules/mysql_hook.html class MySqlHook(DbApiHook): conn_name_attr = 'mysql_conn_id' default_conn_name = 'mysql_default' supports_autocommit = True def get_conn(self): """ Returns a mysql connection object """ conn = self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '' } conn_config["host"] = conn.host or 'localhost' conn_config["db"] = conn.schema or '' conn = MySQLdb.connect(**conn_config) return conn Copy from https://airflow.apache.org/_modules/mysql_operator.html class MySqlOperator(BaseOperator): @apply_defaults def __init__( self, sql, mysql_conn_id='mysql_default', parameters=None, autocommit=False, *args, **kwargs): super(MySqlOperator, self).__init__(*args, **kwargs) self.mysql_conn_id = mysql_conn_id self.sql = sql self.autocommit = autocommit self.parameters = parameters def execute(self, context): logging.info('Executing: ' + str(self.sql)) hook = MySqlHook(mysql_conn_id=self.mysql_conn_id) hook.run( self.sql, autocommit=self.autocommit, parameters=self.parameters) As we can see Hook incapsulates the connection configuration while Operator provides ability to execute custom queries. The problem: It's very convenient to use different ORM for fetching and processing database objects instead of raw SQL for the following reasons: In straightforward cases, ORM can be a much more convenient solution, see ORM definitions. Assume that there is already established systems like … -
Display Django DateTime Field with strftime() method
I am trying to format the string of a DateTimeField contained in one of my models. I am using this method inside the model: def HTMLDisplayTime(self): time = self.time.date.strftime(%a %H:%M %d/%m/%y) return time Where "self.time" refers to the DateTimeField in question. I have tried several variations, omitting some items, with and without .date preceding the .strftime method, and have imported both import datetime and from datetime import datetime.