Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
parse python datetime object in javascript within django app
I'm passing the following variable to a template: from django.utils import timezone dt = timezone.now() print(type(dt)) # <class 'datetime.datetime'> Everything works fine if I use it in my HTML directly: {{ dt | date:'D d M Y' }} which renders to Thu 14 Dec 2017. However when I try to access the variable in my javascript I get an error: <script> {{ dt | safe }} </script> Uncaught SyntaxError: missing ) after argument list Furthermore, I get a slightly different error when I try to render a list of datetime objects: dt_list = [timezone.now() for _ in range(3)] and within my js: <script> console.log({{ dt_list | safe }}) </script> Uncaught SyntaxError: Unexpected token < So my question is how can I convert a python datetime object to something I can use in JS? -
Rendering internally linked markdown files in django
I want to link to markdown pages in a markdown page served by django. For example, in a markdown page index.md, I have a link [link label](path/page1.md) But when I click the link, I don't get the rendered page (as I intended). In stead I get the option to download the file. The markdown page index.md is rendered as expected. Is there a solution? -
Is there a Pythonic way to handle object chains that could contain None?
My Django codebase has foreign key references that are a few objects deep and it feels like a code smell to have to check for truthiness at each level. Is there a way to check for this kind of thing in a more pythonic way with less boilerplate? Take this simplified example: if page.banner.image: # ... If page.banner is optional and it doesn't exist it will return None and throw an exception saying, rightly, that NoneType doesn't have an image attribute. The obvious fix is if page.banner and page.banner.image: # ... But this will get repetitive and verbose. I suppose you could use getattr() to do something like I'm after but it's even uglier: if getattr(getattr(page, 'banner', None), 'image', None): # ... Is there a concise way to do this without all these conditional clauses? -
Routing with Polymer and Django
I am trying to set up an app using Polymer/Django. I have one template that basically exists to instantiate my base component (admin-panel), which works rather swell. The trouble is that now the that I use inside my component doesn't pick up any changes! What gives? Here's my template: <head> <link rel="import" href="{% static 'index.html' %}"/> <script src="{% static 'bower_components/webcomponentsjs/custom-elements-es5-adapter.js' %}"></script> <!-- Load webcomponents-loader.js to check and load any polyfills your browser needs --> <script src="{% static 'bower_components/webcomponentsjs/webcomponents-loader.js' %}"></script> <link rel="import" href="{% static 'src/admin-panel.html' %}"/> </head> <body> <admin-panel></admin-panel> </body> My Django urlpatterns all resolve to the above template: urlpatterns = [ url(r'^(?!api).*$', views.index, name='index'), ] And here's the part of my admin-panel component: <app-location route="{{route}}" url-space-regex="^[[rootPath]]"> </app-location> <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{routeData}}" tail="{{query}}"> </app-route> <app-drawer-layout fullbleed narrow="{{narrow}}"> <!-- Main content --> <app-header-layout has-scrolling-region> ... stuff ... <iron-pages selected="[[page]]" attr-for-selected="name" fallback-selection="not-found-page" role="main"> <landing-page name="landing-page"></landing-page> <organization-detail-page name="organization-detail-page" route="[[query]]"> </organization-detail-page> <not-found-page name="not-found-page"></not-found-page> </iron-pages> </app-header-layout> </app-drawer-layout> Anyone else used app-route with django templates? What did you do? -
Annotating an annotation in Django
I would like to perform an aggregation by group, and then count the distinct results of that aggregation. For example, this would apply to making a histogram of total sales across a company: Product.objects.values('salesperson')\ .annotate(total_sales = Sum('quantity_sold'))\ .values('total_sales')\ .annotate(count = Count('total_sales')) This would ideally result in a list of counts of total_sales (over salespeople) like (0, 10) (1, 24) (3, 55) ... But I get an error like: FieldError: Cannot compute Count('total_sales'): 'total_sales' is an aggregate This seems to be because I can't perform the second aggregation after the first. I can probably do this outside of SQL, but it would be nice if there was a clean solution inside SQL. -
Django/Nginx server says Android app's POST requests are connecting, but they aren't
I am trying to send JSON from an Android app to a Django/Nginx/UWSGI server and return an HttpResponse to the app. The Android code worked perfectly when I ran it on a Django server without Nginx or UWSGI, but it did not work when I tried to use it with Nginx/UWSGI installed. My app logs a java.io.FileNotFoundException: https://www.placeholder.com/my_url error when I try to POST the JSON, but my server's /var/log/nginx/access.log shows the POST request as successfully connecting. Moreover, nothing shows up in /var/log/nginx/error.log;. I suspect something on my server is preventing the POST request from being completed. I modified my keepalive_timeout and keepalive_requests in nginx.conf but it made no difference. I also tried adding a configuration recommended here to my sites-enabled/sites-available files. For reference, here are the uncommented parts of my nginx.conf file: # nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; # (original) keepalive_timeout 65; keepalive_timeout 1000; # keepalive_requests added to file keepalive_requests 100000; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } Plus the content … -
Insert a variable into url string - Django App
I am developing a Django App and I need to insert a variable into a url string defined in the front-end (javascript) to get a json file from a user's folder: '{% static "users/ userName /file.json" %}' I would like to have userName as a variable. I tried different syntaxes but no luck so far. Do you know any solution for this? Thank you very much for your help ! -
Django models for non user-created tables
I am working on a project using veekun's pokedex sqlite database, and using it in a django project. They have many tables including encounter rates, pokemons, types, etc. Most of these the user will not need to interact with (really only needs to read from database, not create, update, or delete). Is it worth it to create models based off the database either manually or through inspectdb? Will I see any performance boost? I am new to django so I may be misunderstanding the purpose of models here. -
allowing different users to edit fields of a matrix
what i want to achieve: i have a page with a matrix that can be edited by a single mainuser and viewed by several basicusers. the mainuser can allow each basicuser to edit a certain amount of rows. -> Each basicuser can edit their assigned rows and the mainuser can oversee everything and accept everything when finished The solution that first came to mind was creating matrices according to this matrix model in django and adding permissions viewing and editing to each cell object. The mainuser has a permission cell_distribution which displays additional buttons that allow him to grant basicusers editing permission for cells/rows and move forward once the matrix is completely filled. Is this the best way to achieve what i want or are there easier ways? (e.g. with packages like django-matrix-field or django-numpy) -
Mobile application and django
Is there in github or somewhere else a template for a mobile application (with a server) in which a user can submit something, and other users can subscribe for observing it? -
Annotating Django querysets with ForeignKey Counts subject to conditions
Here is a simplified version of my models: class Airport(models.Model): iata = models.CharField() name = models.CharField() latitude = models.FloatField() longitude = models.FloatField() class Flight(models.Model): origin = models.ForeignKey('Airport', related_name='origins') destination = models.ForeignKey('Airport', related_name='destinations') owner = models.ForeignKey(User) Given a User, I would like to create a list of all the Airport objects that appear in either the origin or destination fields of the Flight objects he owns, each annotated with the corresponding number of Flight objects. For example, suppose a user has been on 3 flights: LAX-LHR, LHR-CDG, and CDG-JFK. Then I would like a query which returns the following object: [LHR, id__count=2}, {CDG, id__count=2}, {LAX, id__count=1}, {JFK, id__count=1}] In the above, the three letter codes stand for Airport objects or all their fields. Generally, there may be thousands of Users and tens of thousands of Airports and Flights, so I am seeking something more efficient than the obvious solution with for loops and if statements, preferably in a single database query. My current progress is this query: Airport.objects.filter( Q(origins__owner=user) | Q(destinations__owner=user) ) .distinct() .annotate( id__count=Count('origins', distinct=True) + Count('destinations', distinct=True) ).order_by('-id__count') This works perfectly with only one user, because the initial filter only keeps those airports which appear somewhere in his flights. … -
Stripe with Django - make form clean() method return value that isn't a form field
I am integrating Stripe payment processing into my Django app, and I can't figure out the 'correct' way to verify the customer's card information and insert a row into my Users table that contains the user's Stripe Customer ID. Ideally, I'd love to do something along the lines of the following, in which my CheckoutForm verifies card details and raises a form ValidationError if they are incorrect. However, using this solution, I can't figure a way to get the customer.id that's generated out of the clean() function. forms.py class CheckoutForm(forms.Form): email = forms.EmailField(label='E-mail address', max_length=128, widget=forms.EmailInput(attrs={'class': 'form-control'})) stripe_token = forms.CharField(label='Stripe token', widget=forms.HiddenInput) def clean(self): cleaned_data = super().clean() stripe_token = cleaned_data.get('stripe_token') email = cleaned_data.get('email') try: customer = stripe.Customer.create( email=email, source=stripe_token, ) // I can now get a customer.id from this 'customer' variable, which I want to insert into my database except: raise forms.ValidationError("It looks like your card details are incorrect!") views.py # If the form is valid... if form.is_valid(): # Create a new user user = get_user_model().objects.create_user(email=form.cleaned_data['email'], stripe_customer_id=<<<I want the customer.id generated in my form's clean() method to go here>>>) user.save() The only other solution I can think of is to run the stripe.Customer.create() function in views.py after the form is … -
Generic "Please correct the error below." Django Admin
I've found some Django tickets talking about this issue, but I can't get it to work. Basically, I have a parent model which has 3 inlines (Each having a foreign key to the same field according to the parent model). Something like this, class ModelA(models.Model): somefield = models.TextField(unique=true,null=true) ... class ModelB(models.Model): somefield = models.ForeignKey('ModelA', to_field='somefield'...) ... class ModelC(models.Model): somefield = models.ForeignKey('ModelA', to_field='somefield'...) ... class ModelD(models.Model): somefield = models.ForeignKey('ModelA', to_field='somefield'...) ... I can make any changes to the parent models and/or to inlines except for the field that is a Foreign key to others child models. In the Admin I get the "Please correct the error below." even though no error appears on my form. I'm looking for possible solutions since my problem won't be easily reproducible. -
repo2 is a library for repo1
In the moment, I have two github repositories, i.e. repo1 and repo2. Both are two django projects created by our team. In requirements.pipin ~/work_projects/repo1, I have the line -e git+ssh://git@gitlab.com/repo2.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=repo2 Hence, repo2 becomes a library used by repo1 in ~/.virtualenvs/venv/src (repo1's virtual environment). In the moment, I need to modify both repositories at the same time. So my main focus in the moment is each time I modify repo2, I need to test out the results on repo1. I want to look at the impact of repo2 on repo1 once modified. I don't want to push my changes on github and reinstall repo2 on repo1 each time I want to see those changes. How could I make it works easily, workaround? -
django simple history - how to create history when the object is not created in admin
I'm using django-simple-history==1.9.0 package with django 1.8. When I create an object outside the admin and then look at the history of the object in the admin page, it shows a message This object doesn't have a change history. It probably wasn't added via this admin site. I tried setting the user for that object: user = User.objects.get(username='john') Poll.objects.get(id=536).history.update(history_user=user) but that did not solve the problem. Poll.objects.get(id=536).history.all().count() returns 1 so there is a history generated. Any ideas how to make it show the history or how to create an additional history? I also tried update_change_reason but that did not work at all. -
Django - Authenticate users from external source (IPB Forum)
I'm fairly new to Django - I've been building a small web app for our forum community, which is powered by IPB 4. Initially I didn't have any need for users on the Django site since it was just displaying data, but I've come up with some new ideas and I would love to be able to make it such that if a user has an account on the forums, they could sign into the Django site using the same credentials. I don't need any sign-up functionality on the Django site - if a user isn't registered I can simply redirect them to the forum signup. I've been doing plenty of research on this and there is a lot of information about authenticating users from an external source in Django but I'm having trouble understanding how to go about it with an IPB forum as all of IPB's documentation on SSO relies on PHP. Would Django's authentication back-ends be capable of something like this? Or would setting up an OAuth server on the forum work better? IPB does have a great built in REST API so perhaps that could be utilized as well. Thanks for any guidance you guys might … -
using self.request.user in model queryset in Django
I am using Django 2 I have a model within which I have written a queryset class to add the search function. I want to display only those results which are associated with the authenticated user. For that I'm using user=self.request.user in filter in queryset Notes/model.py class NoteQuerySet(models.query.QuerySet): def authenticated(self): return self.filter(user=self.request.user) def search(self, query): lookups = Q(title__icontains=query) | Q(tags__icontains=query) return self.filter(lookups).authenticated().distinct() class NoteManager(models.Manager): def get_queryset(self): return NoteQuerySet(self.model, using=self._db) def search(self, query): return self.get_queryset().search(query) class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True, default='Untitled') tags = models.CharField(max_length=150, blank=True) objects = NoteManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('notes:update', kwargs={'pk': self.pk}) In Notes/views.py class SearchNoteView(ListView): template_name = 'notes/my_notes.html' context_object_name = 'notes' def get_queryset(self, *args, **kwargs): query = self.request.GET.get('q', None) if query is not None: return Note.objects.search(query) But this return errors as AttributeError: 'NoteQuerySet' object has no attribute 'request' As the error states, it is trying to locate request funtion withing the class. How can I use the request in the queryset class? -
Form does not save time in database with generic class
Good afternoon, I have a form with different types of fields, including one where one hour is required (where I do not use a timepicker but a textinput). For the development of this form I use a .form class next to a generic view createview; where all the data except those that require the entry of an hour are saved. When presenting the data using another generic view, this field appears as None. I have tried, among several things, using the TextInput instead of the TimeInput, but without any difference. This is my model: class Reserva(models.Model): ESTADOS_CHOICES = ( ('AP', 'Aprobado'), ('PE', 'Pendiente'), ('NE', 'Negado'), ) SALONES_CHOICES = ( ('S1', 'Salon 1'), ('S2', 'Salon 2'), ('S3', 'Salon 3'), ('CA', 'Cafeteria'), ) usuario = models.ForeignKey(User) fecha_peticion = models.DateTimeField(auto_now_add=True, blank=True, null=True) asunto = models.CharField(max_length=80) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) salon = models.CharField(max_length=2, choices=SALONES_CHOICES, blank=True, null=True) hora_inicio = models.TimeField() hora_fin = models.TimeField() estado = models.CharField(max_length=2, choices=ESTADOS_CHOICES, blank=True, null=True) observaciones = models.CharField(max_length=100, blank=True, null=True) Este es mi formulario de la clase .form. class F_EnvioPeticion(forms.ModelForm): hora_inicio = forms.TimeField(input_formats=('%H:%M'), widget=forms.TimeInput(format='%H:%M')), class Meta: model = Reserva fields =[ 'asunto', 'fecha_inicio', 'fecha_fin', 'salon', 'hora_inicio', 'estado', ] labels = { 'asunto' :'Este es mi asunto:', 'fecha_inicio' … -
ValueError on uploading text file
ValueError at /path/upload/ Invalid file path or buffer object type: class 'django.core.files.uploadedfile.InMemoryUploadedFile'> I get the error above on uploading a text file (CSV) using Pandas. On my development environment, everything works smoothly but I get the error below on environment set up using uwsgi as app server and nginx as web server. -
Not able to get groups that belong to current user
I'm building a Django app that needs two things. First, it needs the set of groups that the user has access to. With this set of groups, my template is supposed to create a button for each group. Next, it needs the set of "Property" objects that are ManyToMany related to a group in the previously found set of groups (this is to say that I need every property that is assigned to a group that the user has access to). For each of these properties, a button is created. I'm working with an admin user on localhost right now while building this, and I've created a test group with test properties and assigned the admin user to that group. Django however, doesn't seem to be detecting this. The relevant code is below: views.py from __future__ import unicode_literals from django.shortcuts import render from UsageData.models import Property, User, Group, MeterData from django.contrib import auth def reports_proerty_list(request): if request.user.is_authenticated(): current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) return render(request, 'App/App-Template-Page.html') else: # The user is redirected to the sign-in page App-Template-Page.html <div class="row"> {% if current_user_groups %} {% for group in current_user_groups %} <div class="col-sm-2 col-md-2 col-lg-2 text-center"> <button class="tab-selector inactive" id="{{ group.id }}">{{ … -
Update content of static html file in Django
I saved an HTML as a static file in order to save it in cache and render it through a service worker when Offline. I would like to make a small change on my HTML in order to get the appropriate encoding. I am using pythonanywhere as my server. And I have defined in my settings.py the following paths: STATIC_URL = '/static/' STATIC_ROOT = u'/home/cocoa/cocoa/static' When I look at my file in the server in the following directory is: /home/cocoa/cocoa/static/login/Offline/HTML/mEstado.html My file looks like this: If I visit the following URL: https://cocoa.pythonanywhere.com/static/login/Offline/HTML/mEstado.html My file looks like this: I allready tried reloading on shift. Unabling the service-worker and python manage.py collectstatic But nothing seems to work. I do not know where the problem is, nor how to solve it. Any help would be appreciated. -
Missing argument inside a form of django app
I am trying to access a user product list inside the form of my django app. The user information should be the input options of a form from the app. What argument should I pass in my list_prod bellow? I am receiving the following error message: TypeError: list_prod() takes exactly 1 argument (0 given) Please Help! Form class ProductsForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(ProductsForm, self).__init__(*args, **kwargs) def list_prod(self): user_name = (self.request).user.username u = User.objects.get(username=user_name).accesslevel.prod.split(',') v=(('---------','---------'),) for l in u: v=v+((l.lstrip(),l.lstrip()),) model = Factory Lists = forms.ChoiceField(choices=list_prod()) -
how to use ManyToManyField of model in itself
scenario i have group of users instrest in each others activity when ever a user of this group see a feed (record) or show some activity (like , comment , star) and continue. then whenever next user opens the app randomly sees the feed or show some activity (like , comment , star) so app will lead the second user to first user foot steps until it ignore the at least 3 feeds (records) so the best i come up with is ManyToManyField of model in itself by this method i will be able to classify every record (feed) and add all it's related feed back to the same model even witout adding a new record . example : Sam saw a feed 1 then Sam saw feed 5 then Sam saw feed 10 now it will add feed 5 and 10 as inner_feed to feed 1 and feed 10 to 5 is something like this model possible in django ? class NewsFeed(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, models.DO_NOTHING, related_name="feeduser") date_created = models.DateTimeField(default=timezone.now) last_update = models.DateTimeField(default=timezone.now) inner_feed = models.ManyToManyField(NewsFeed) if there is anything hard to understand please ask -
Django converts value to tuple after model-field updating
I'm using Django 2.0. I have a model with a field declared as: px = models.DecimalField(max_digits=10, decimal_places=2, default=0) After getting an instance of this object from database, I try to update its property with: obj.px = "-2.6" The value "-2.6" comes from a variable, but I've tested with hard code: -2.6, 2.6, decimal.Decimal("-2.6"), etc. It always converts that value to a tuple I don't know why. What I get in django result is: argument must be a sequence of length 3 Django raises this error when calling the "save" method from the model, and it internally does the conversion: return decimal.Decimal(value) When I print the new value of "px" I get this: (2.6,) The only fix that I did was the following: if isinstance(obj.px, tuple): obj.px = obj.px[0] -
Django IntegerField ignores specified default value when blank=True and empty string posted
Consider the following model field: myfield = models.IntegerField(_('My field'), blank=True, default=0) If the myfield is completely omited from the post the default is properly used by default ModelForm implementation. However if empty string is posted for that field the field value stays None and postgres fails with the IntegrityError on non-null field: IntegrityError: null value in column "myfield" violates not-null constraint Question: How to enforce a default for both cases where either the myfield value is not present or present but empty string?