Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Only Boolean Field = True to show, How to write in the template?
Hey everyone and sorry for my english, I'm very new to Django and web-development so here is my question: I have a model/table with only Boolean Fields and want to show them in my detail.html but ONLY the columns which are True. How can I manage this? I have tried to do it with a query but it doesn't worked. Now I have a solution where my template shows the Boolean Fields as checkboxes but it doesn't synchronize with the real values. So I have an problem with my input I think. I have tried it with and ifequal but it just turns it always True. Here is my template part of one Boolean Field: <div class="form-row field-firstfield"> <div class="checkbox-row"> <input id="id_firstfield" name="firstfield" type="checkbox" value="on" {% ifequal Table.firstfield true %}checked="checked"{% endifequal %} disabled /><label class="vCheckboxLabel" for="id_firstfield">First Field</label> </div> </div> -
Downloading a ReportLab PDF
I am trying to download a ReportLab PDF. I do not want to view it in browser. Below is the view where the generation happens. I would like to save the PDF to a folder "C:\Users\Evan\Desktop\Webapp\". Is there a way I can do this? import os from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from orders.models import OrderEntry, Items from orders.forms import Details, View_Order from reportlab.pdfgen import canvas def entry(request): if request.method == 'POST': form = Details(request.POST) if form.is_valid: customer = request.POST.get('customer') quote = request.POST.get('quote_number') purchase = request.POST.get('po_number') a1 = request.POST.get('i1') a2 = request.POST.get('i2') a3 = request.POST.get('i3') a4 = request.POST.get('i4') a5 = request.POST.get('i5') a6 = request.POST.get('i6') a7 = request.POST.get('i7') a8 = request.POST.get('i8') a9 = request.POST.get('i9') a10 = request.POST.get('i10') obj_oi = Items(quote_num = quote, item_1 = a1, item_2 = a2, item_3 = a3, item_4 = a4, item_5 = a5, item_6 = a6, item_7 = a7, item_8 = a8, item_9 = a9, item_10 = a10) name = quote + ".pdf" response = HttpResponse(content_type='application/pdf') response['Content-Dispostion'] = 'filename = name' p = canvas.Canvas(response) p.drawString(280, 800, quote) p.drawString(50, 750, "Customer:") p.drawString(110, 750, customer) p.drawString(400, 750, "Customer PO:") p.drawString(480, 750, purchase) p.drawString(50, 600, "Item 1:") p.drawString(100, 600, a1) p.drawString(500, 600, "Quantity") p.drawString(515, 600, "1") p.drawString(50, … -
How to convert the Raw Sql query to Django Model
My models.py: class TheaterShowTimings(models.Model): showname = models.CharField(max_length=100) showtime = models.TimeField() # stores only time theatershowtimingsid = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.theatershowtimingsid class MovieActiveDays(models.Model): date = models.DateField() # stores single only date moviedetails = models.ForeignKey(MovieDetails, on_delete=models.CASCADE) theaterbase = models.ForeignKey(TheaterBase, on_delete=models.CASCADE) activedayid = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.activedayid class ActiveShowTimings(models.Model): TheaterShowTimings = models.ForeignKey(TheaterShowTimings, on_delete=models.CASCADE) MovieActiveDays = models.ForeignKey(MovieActiveDays, on_delete=models.CASCADE) activeshowid = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.activeshowid My views.py: show_name_list = TheaterShowTimings.objects.raw('SELECT distinct * FROM Book_TheaterShowTimings where theatershowtimingsid IN (select TheaterShowTimings_id from Book_ActiveShowTimings where MovieActiveDays_id IN (select activedayid from Book_MovieActiveDays where date = "2016-12-19"))') The above query in views.py is working fine. But, I want to convert it into a django queryset. please help me, I`m stuck at converting that raw sql query to queryset. Thanks in advance. -
django-autocomplete-light: Forward works fine in admin but returns None when used in template
I can't get django-autocomplete-light to forward values when NOT in admin. Here's the issue: I have 2 linked select boxes. It is for a train connections app, so when you select City from the first box (departure) only the destination-Cities for which there is a connection should appear on the second. The simplified models: class City(models.Model): name = models.CharField(max_length=64) destinations = models.ManyToManyField( 'self', symmetrical=False, through='Connection') class Connection(models.Model): departure = models.ForeignKey( City, on_delete=models.CASCADE, related_name='departure') destination = models.ForeignKey( City, on_delete=models.CASCADE, related_name='destination') And here are my views: class DepartureAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = City.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class DestinationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = City.objects.all() departure = self.forwarded.get('departure', None) if not departure: return [] else: qs = qs.filter(id=departure)[0].destinations.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class HomeView(generic.UpdateView): model = City form_class = ConnectionForm template_name = 'intercity/home_template.html' success_url = reverse_lazy('home_view') def get_object(self): return City.objects.first() Finally my forms.py: class ConnectionForm(forms.ModelForm): departure = forms.ModelChoiceField( queryset=City.objects.all(), widget=autocomplete.ModelSelect2( url='departure-autocomplete' ) ) destination = forms.ModelChoiceField( queryset=City.objects.all(), widget=autocomplete.ModelSelect2( url='destination-autocomplete', forward=['departure', ] ) ) class Meta: model = Connection fields = ('__all__') Everything works fine in admin (in the Add Connection page), but I need to expose this to the front end. The rendered html structure seems the … -
dynamic formset clone selectize dropdown
I have created a dynamic inline formset. Unfortunately, I need to clone the selectize dropdowns with the script as well. When I click the 'add another' button, the formset is copied but clicking the new dropdowns activates the first dropdown field. How can I copy the script so that every new dropdown can have it's own selectize mechanism? My views.py are pretty much common: def menu(request): menu = Menu.objects.all() form = MenuForm(request.POST) sides = Sides.objects.all() dishes = Dishes.objects.all() if form.is_valid(): addnew = form.save() addnew_formset = MenuFormSet(request.POST, instance=addnew) if addnew_formset.is_valid(): addnew.save() addnew_formset.save() return HttpResponseRedirect('menu') else: form = MenuForm() addnew_formset = MenuFormSet(instance=Menu()) return render(request, 'stolowka/menu.html', {'form': form, 'addnew_formset': addnew_formset, 'menu': menu, 'sides': sides, 'dishes': dishes}) forms.py: class DishesForm(forms.ModelForm): class Meta: model = Dishes fields = '__all__' class SidesForm(forms.ModelForm): class Meta: model = Sides fields = '__all__' class MealForm(forms.ModelForm): class Meta: model = Meal fields = '__all__' class MenuForm(forms.ModelForm): class Meta: model = Menu fields = '__all__' MenuFormSet = inlineformset_factory(Menu, Meal, fields='__all__', extra=1, can_delete=True) the template goes like this: <script src="/static/menu/js/dynamic-formset.js"></script> </head> <body> <script type="text/javascript" charset="utf-8"> $(function() { $(".sides").selectize({ plugins: ['remove_button'] }); }); $(function() { $('.meal_set-0-dish').selectize({}); }); $(function () { $('.add-row').click(function() { return addForm(this, 'form'); }); $('.delete-row').click(function() { return deleteForm(this, 'form'); }) }); … -
Is it possible to pass a variable from JavaScript to Django?
Hello guys I'm was trying to find some examples trying to find a variable from JavaScript to Django last night but I could not find anything. The only examples I could find were about Ajax, I wonder if it's possible to use JavaScript or only Ajax. If it's possible to use it can you guys could give me a simple example to achieve this? I only want to pass a variable to Django but I have no idea how to do it Thank you -
Django form field label- how to change its value 'if' it belongs to a certain field
I have a Django form, and the fields/ field labels for the form are all displayed using a for loop: {% load utilities %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} {% if field|is_checkbox %} <tr><td colspan="1">{{field}}</td><td colspan="6"><label>{{field.label}}</label></td></tr> {% else %} <tr><td colspan="7"><label>{{field.label}}</label></td></tr> <tr><td colspan="7">{{field}} </td></tr> {% endif %} {% endfor %} I want to add some text to the labels for certain fields displayed by this for loop (if the field is a 'date' field, I want to instruct the user to enter values in the format 'dd/mm/yyyy hh:mm'). I know that if the field is a 'date' field, its name will contain the word 'date', so how can I nest an if inside the if statement here, to say: if field.name contains "date": field.name = field.name + "dd/mm/yyyy hh:mm" I understand the logic of how to do this, I'm just not sure about the Python syntax... would it be something like: {% if "string" in {{field.name}} %} {{field.name}} = {{field.name}} + " (dd/mm/yyyy hh:mm)" I gave this a go, but my browser displayed a syntax error that said: TemplateSyntaxError at /projects/5915/info/ Could not parse the remainder: '{{field.label}}' … -
Positional Arguments withDjango url patterns
I have been stuck on this django error for a while. The error I get is "tutorials() missing 1 required positional argument: 'tutorial_id'". Below are the files. Using Python 3.5 and Django 1.10. tutorials/urls.py from django.conf.urls import url from . import views app_name = 'tutorials' urlpatterns = [ url(r'^(?P<tutorial_id>[0-9]+)/$', views.tutorials, name='tutorials'), url(r'^$', views.tutorials, name='tutorials'), ] tutorials/views.py from django.shortcuts import render, get_object_or_404 from .models import Tutorial, Lesson def tutorials(request, tutorial_id): tutorials = get_object_or_404(Tutorial, pk=tutorial_id) return render(request, 'tutorials/tutorials.html', { 'tutorials': tutorials}) When I visit website.com/tutorials I get the error but it will work fine if I go to website.com/tutorials/1 which is good. But I want to be able to access /tutorials so I can ad information to this link. -
How to select all objects from a model by selection of an item from another model?
I want to select & render specific RegulationItem objects by Project.regulation selection. If Project.regulation=REG1, then select & display all rows from RegulationItem with REG1. I can filter somehow? need to define/modify the view.py? how to render it in template? Thank you in advance. models.py Class Project(models.Model): number = models.CharField( max_length=256, unique=True, ) regulation = models.ForeignKey( 'Regulation', related_name='regulation', null=True, ) Class RegulationUpload(models.Model): REG1 = 'REG1' REG2 = 'REG2' REG3 = 'REG3' LIST = ( (REG1, ugettext_lazy(u'REG1')), (REG2, ugettext_lazy(u'REG2')), (REG3, ugettext_lazy(u'REG3')), ) name = models.CharField( blank=True, choices=RegulationType.LIST, default=None, null=True, ) checklist = models.FileField( upload_to='regulations/', blank=True, null=True, ) Class RegulationItem(models.Model): reg_ref = models.ForeignKey( 'Regulation', null=True, related_name='reg_ref', ) item = models.CharField( max_length=256, unique=True, blank=True, null=True, ) title = models.CharField( max_length=256, unique=True, blank=True, null=True, ) description = models.TextField( blank=True, null=True, ) def __unicode__(self): return '%s' % (self.reg_ref) views.py def project_details(request, number): project = get_object_or_404(Project, number=number) assert isinstance(request, HttpRequest) return render( request, 'app/page/project.html', { 'project':project, } ) urls.py url(r'^projects/(?P<number>\w{3}\-\w{2}\d{3})', app.views.project_details, name='project_details'), -
Take last object in queryset and set value in field
I have app in Django 1.8 and I want to take last object (based on pub_date) and set for this object filed is_mainteaser on True and rest ssould be set on False. Here is my code, but latest object hasn't field set to True. class ArticleListView(ListView): model = Article queryset = Article.objects.order_by('-pub_date') def get_context_data(self, **kwargs): context = super(ArticleListView, self).get_context_data(**kwargs) lates_object = Article.objects.latest('pub_date') lates_object.is_mainteaser = True return context Here is my model: class Article(model.Models): title = models.CharField(max_length=255) short_text = models.TextField(max_length=10000, default='') image = FilerImageField(null=True) pub_date = models.DateTimeField('date published') online_from = models.DateTimeField('online from', blank=True) online_to = models.DateTimeField('online to', blank=True) position = models.PositiveIntegerField(default=0) is_mainteaser = models.BooleanField(default=False) def __str__(self): return self.title class Meta: ordering = ['position'] -
Tornado + Django + sockJS - broadcasting messages to given list of users
I am playing with a real-time chat available here on Github using sockJS lbrary. As for now, I have a marvelous working website where you post a letter, and this letter is broadcast to all open pages. Now the question is, how do I modify the code to add a specific address for which the letter should be broadcast (in other words, I don't want to send the letter to everyone; I want it to receive only one target user). Here is my python code: def on_message(self, data): data = json.loads(data) #print "DATA", repr(data) msg = Message.objects.create( name=data['name'], message=data['message'] ) self.broadcast(self._connected, self._package_message(msg)) def _package_message(self, m): return {'date': m.date.strftime('%H:%M:%S'), 'message': m.message, 'name': m.name} And here is the js part that receives the letter: sock.onmessage = function(e) { //console.log('message', e.data); var data = e.data; if (data.message && data.name) { var out = $('#out'); $('<span>') .addClass('date') .text(data.date) .appendTo(out); $('<p>') .append($('<strong>').text(data.name + ': ')) .append($('<span>').text(data.message)) .appendTo(out); out.scrollTop(out.scrollTop() + 1000); } }; -
How to make readonly Python Chatterbot Library with Django intregation
I'm making Chat Bot using Python Chatterbot Library with Django intregation. I want to know how to make it readonly ? I got this code chatbot = ChatBot("Johnny Five", read_only=True) but don't in which file i have to put this. So, that it can works. -
Disable form field in Django's CreateView
This question may also be formulated as: "How to change attributes of a CreateView generated form?" I am using "CreateView" to generate a view and related form in Django 1.10. The idea is that a regular user (a teacher) can create an instance of the model only as himself/herself but a privileged user can create an instance and assign to any teacher. I would like to use the same view/form for both. The model: class Set(models.Model): name = models.CharField( max_length=40, ) matter = models.ForeignKey( Matter, on_delete=models.SET_NULL, null=True, ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, null=True, ) teacher = models.ForeignKey( Teacher, on_delete=models.PROTECT, ) Technically, it would consist on populating the form with the current "teacher" logged in and disable the field unless the current user is privileged. I currently do the initial value setting with the following code, but I do not know how to prevent regular users from modifying the "teacher" field. class SetCreate(LoginRequiredMixin, CreateView): model = Set fields = ('name', 'matter', 'group', 'teacher') def get_initial(self): return {'teacher': self.request.user.teacher.id} # code to limit 'teacher' field editing Another option I tried is to create the instance with the right 'teacher', like: class SetCreate(LoginRequiredMixin, CreateView): model = Set fields = ('name', 'matter', 'group') … -
Redirect http to https in Django (usiing sslserver)
I have a django project working with HTTPS using django sslserver.I want http to be redirected to https. I tried adding SECURE_SSL_REDIRECT = True which does not seem to have any effect. Similarly to test if my redirection was right, I tried the following on a test project. Created a new django project Added SECURE_SSL_REDIRECT = True to the settings.py file. Here now, when I try to run the server with http it redirects to https. But asof now my server does not support https cause of which desired web page is not displayed. Installed sslserver Ran the project with the command python manage.py runsslserver 8000 This succesfully redirects the webpage to https even if I open the url with http This test redirection works fine like this. But if I already have sslserver installed ssl redirection does not seem to have any effect. I have been stuck with this problem for a while now and would really appreciate some help. -
Prepend or append icon in field of django-crispy-forms
I have the following field in a Form: <div class="form-group "> <div class="input-group"> <input class="form-control" id="To" name="To" placeholder="To" type="text"/> <i class="glyphicon glyphicon-map-marker form-control-feedback"></i> </div> </div> which looks like and I am trying to have a similar result using crispy-forms. I tried self.helper.layout = Layout( Fieldset( 'Title', PrependedText( 'From', <i class="glyphicon glyphicon-map-marker"></i> ), 'To', 'Date', ButtonHolder( Submit('submit', 'Search', css_class='button white') ) ) ) but I get a SyntaxError: invalid syntax. Is it possible to add an icon as PrependedText in crispy-forms? If not, is there any alternative? -
How to get total downloads of an android app in django python from google play store
I have a android app on Google play store and I want total number of downloads in django project,I am new on python, I don't have any idea how to do this, please help in this. Big Thanks In Advance. -
Postgres Query to retrieve data in JSONField
models.py:- class data(models.Model): interaction = JSONField(db_index=True,null=True) If I run the query SELECT * FROM data WHERE interaction IS NOT NULL Result :- [{"callDate": "2016-12-19T10:22:53.809Z", "callStatus": "Promotional Email Sent", "vendorManager": "Iresh"}] [{"callDate": "2016-12-19T05:58:01.856Z", "callStatus": "Mail Received", "vendorManager": "niyati"}, {"callDate": "2016-12-19T07:15:53.129Z", "callStatus": "Switched Off", "vendorManager": "Manish"}] [{"callDate": "2016-12-17T12:44:22.874Z", "callStatus": "Company Profile Sent", "vendorManager": "kshitij"}] [{"callDate": "2016-12-17T12:28:24.947Z", "callStatus": "Switched Off", "vendorManager": "kamal"}, {"callDate": "2016-12-17T12:50:42.500Z", "callStatus": "Profile Data Filled", "vendorManager": "Rahul"}] I need to select rows where "callStatus"="Switched Off" using both postgres and Django ORM query. I have tried SELECT * FROM data WHERE interaction->>'callStatus'='Promotional Email Sent'; But it's giving me empty result. -
What does deconstructible do in Python?
What does deconstructible decorator in Python do? I encountered this decorator looking at someone else code, but I have searched the Python docs and cannot find what this decorator actually does? @deconstructible class UserValidator(object): def __call__(self, value): if value: etc Given the code above, what does adding 'deconstructible' do to this class? -
Django test runner causing db operational errors
I have inherited a website built with Python 3.4, Django 1.10 with a MySQL database that has been built with no tests in place except for some old, unused legacy tests. I have since started writing tests but experience an error when trying to run manage.py test (this works for about 5 minutes on removing the old db before the exception is raised) Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_rmpublic'; database exists") Type 'yes' if you would like to try deleting the test database 'test_rmpublic', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/projectpath/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/projectpath/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 110, in execute return self.cursor.execute(query, args) File "/projectpath/lib/python3.4/site-packages/MySQLdb/cursors.py", line 220, in execute self.errorhandler(self, exc, value) File "/projectpath/lib/python3.4/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue File "/projectpath/lib/python3.4/site-packages/MySQLdb/cursors.py", line 209, in execute r = self._query(query) File "/projectpath/lib/python3.4/site-packages/MySQLdb/cursors.py", line 371, in _query rowcount = self._do_query(q) File "/projectpath/lib/python3.4/site-packages/MySQLdb/cursors.py", line 335, in _do_query db.query(q) File "/projectpath/lib/python3.4/site-packages/MySQLdb/connections.py", line 280, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1072, "Key column 'establishment_id' doesn't exist in table") The above exception was the direct cause of the following … -
Django - Unable to import _ssl module
i've seen all the topic about this subject and most are outdated or doesn't work for me. I'm on Linux version 4.4.0-21-generic (buildd@lgw01-21) (gcc version 5.3.1 20160413 (Ubuntu 5.3.1-14ubuntu2) ) I've already installed django (i can make some import from django) And i didn't know why but when i try python3 manage.py runserver The error traceback tell me that there is no module named _ssl i've trying to resolve this problem all the weekend but cannot solve it. Django import _ssl error Thanks a lot for helping and sorry for my not really good english -
In a django save() method, how should you identify a new object if id is UUIDField?
self.pk is None is not working, because it is generated automatically. Any ideas? -
django-select2-forms autocomplete options render in admin panel but not in inline form
I'm using the django-select2-forms library and Django 1.11 and the select2 form autosuggests and completes perfectly in admin, but on my HTML page it doesn't. In HTML, i'm inserting my form with: {{forms.media}} {{forms.tags}} forms.py tags = select2.fields.MultipleChoiceField(Tag,overlay="Choose several skills...") models.py tags = select2.fields.ManyToManyField(Tag,overlay="Choose several skills...",ajax=True,search_field="name") Is my forms.py accurate? The documentation for this library is scarce and I've been working hours on this problem. -
Django models: choices
I am new to Django an I am trying to combine two different choice attributes to be one. This is my Minutes_Choices = [(0, '0'), (5, '5'), (10, '10'), (15, '15'), (20, '20'), (25, '25'), (30, '30'), (35, '35'), (40, '40'), (45, '45'), (50, '50'), (55, '55')] Hours_Choices = [(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6')] Task_TimeM = models.BigIntegerField(verbose_name='Task duration (minutes):', choices=Minutes_Choices) Task_TimeH = models.BigIntegerField(verbose_name='Task duration (hours):', choices=Hours_Choices) I have tried this but it didn't work. Minutes_Choices = [(0, '0'), (5, '5'), (10, '10'), (15, '15'), (20, '20'), (25, '25'), (30, '30'), (35, '35'), (40, '40'), (45, '45'), (50, '50'), (55, '55')] Hours_Choices = [(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6')] Task_TimeM = models.BigIntegerField(verbose_name='Task duration:', choices=(Hours_Choices,Minutes_Choices)) Is there a way to do it? -
Storing different variables for every session
I'm playing with django as a beginner. I wasn't workin with django sessions till now and i'm stucked. So far I know that comand below starts session: from django.contrib.sessions.backends.db import SessionStore from django.contrib.sessions.models import Session request.session['something']='test' s = SessionStore(session_key=request.session.session_key) My problem is that i want store different variables for every single session and the do some math for every session after page refresh. What would be the best way to do it using session not cookies ? So far I can check if session allready exists: check = Session.objects.get(session_key=s.session_key) Summary what i'm trying to do is: create session no 1 ( 1-st web browser ) store variable for session no 1 create session no 2 (2-nd web browser) store another different variable for session no 2 ---meanwhile refresh both web browsers )----- if session no 1 get variable for this session and for example mulptiply by 2 if session no 2 then add 5 to this value and so on. Thank you in advance. -
Get single object in Django rest framework
Im building Django + Angular2 project. I have side bar and need to add Settings there, which will route to /users/{{ user.id }}, at the moment it works with bug, that when I login, this: <li *ngFor="let user of users"><a routerLink="/users/{{ user.id }}" style="cursor: pointer">Settings</a></li> will not show because for loop will not have any data. If I refresh page it will show in sidebar and will work perfect. This is how I get users: getUsers() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token'); headers.append('Authorization', `JWT ${authToken}`); return this.http .get(this.apiURL, { headers }) .toPromise() .then(res => res.json()); } Problem is that I need to use for loop because in django framework I filter objects and get list of items. Actually I filter them to get only one, user who is logged in at the moment (code from users.service.ts): class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): user = self.request.user queryset = User.objects.filter(id=user.id) return queryset queryset = User.objects.filter(id=None) Is there way to get only one object not list of data to not use for loop in angular (maybe that will fix the bug). Or maybe you can explain me and say how to fix that thing, that Settings …