Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Drupal or Django for my startup? and why
I wanted to know which choice is wiser - try to save up money with a CMS like Drupal or go with a flexible framework like Django or asp.NET The project is a startup for cars that includes: marketplace cars and all kinds of other vehicles marketplace for autoparts marketplace for tires marketplace for all kinds of services around car washing, repairing, etc booking vin checking versus 3rd party databases chat/messaging systems ratings statistics owner tools my garage - where you put data about your own car promo codes/vouchers etc. ... ...in other words, it is huge. It is not the classical startup of 2 people in a garage, but instead a business with funding that aims to topple the leader of car selling in Bulgaria (small country). It would be tremendously helpful to state what your experience is (how good you are at either), have you had specific experiences you didn't like with either and what other specific things might be a problem for one or the other. Any thoughts or guidelines will be super helpful, so thanks in advance. -
Django doesn't show the CSS of my template
thanks for trying to help me. The problem ys described in title. I have this template for a blog that i'm creating using Django. When I open it normally, using double click over the HTML file, it looks like this: The template Working But when I open it via url from the Django project, it looks like this Template doesnt works It only shows a green square (part of the css) but obviously can't open the css correctly. Any idea to solve this? thanks again :) -
'DIRS': [os.path.join(BASE_DIR, 'myfolder', 'templates'),], NameError: name 'os' is not defined - Django
I have installed python3, pip3 and created virtualenv for my project and then installed django. I have installed needed packages and when I am trying to run this command in terminal ./manage.py syncdb --settings=myfolder.settings.local I get this error 'DIRS': [os.path.join(BASE_DIR, 'myfolder', 'templates'),], NameError: name 'os' is not defined I have read some comments to add import os in top of my setting.py file an to add BASE_DIR = os.path.dirname(os.path.abspath(__file__)) I have that already in my settings file but still I'm getting same error. How can I solve it? -
how do we tell where a django redirect comes from
I would like to put in an error line if someone goes to a page that requires authentication. In the view, I have used the @login_required decorator. In settings I have the LOGIN_REDIRECT_URL = '/login/' setting set in the settings.py file. In the view, if there's an error, I put in the reason in the data path: data = {} data['error'] = "Login not correct. Please try again." data['csrf'] = csrf_protect return render(request, "public/auth/login.html", data) How do I determine when the LOGIN_REDIRECT_URL is the cause to come to this view when executed by the @login_required decorator? thanks. -
Django - Only keep selected items from a ListView
I have the following ListView: class IndexView(generic.ListView): template_name = 'meds/index.html' context_object_name = 'meds' model = Medicament def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) return context def get_queryset(self): return Medicament.objects.all() In the template you can select the objects you want to keep and you get their ids in jQuery like so: jQuery(document).ready(function($) { $( "#continue" ).click(function() { var selected = $("#meds").bootgrid("getSelectedRows"); console.log(selected); }); }); The selected variable will be in array format, for example [5, 9] What I would like to do is, upon clicking on continue, have another ListView with only the selected objects ie: object with the pk=5 and object with the pk=9. I have tried using an ajax post call like so: $.ajax({ type: "POST", url: "{% url 'meds:prescription' %}", data: {selected:'selected' , csrfmiddlewaretoken: "{{ csrf_token }}"}, success: function(result) { $('#message').html("<h2>Contact Form Submitted!</h2>") } }); Where meds:prescription is the template for my new ListView: class PrescriptionView(generic.ListView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def post(self, request, **kwargs): selected_ids = request.POST.getlist('selected[]') meds = self.get_queryset().filter(id__in=selected_ids) return render(request, self.template_name, {'meds': meds}) But for some reason even when I click on continue, nothing happens, I don't get redirected to the template with the selected objects. Is there an easier way … -
Is there a way to list all Django registered URL namespaces?
I'm getting an %s is not a registered namespace error in Django 1.11. Is there a way to list what all the registered namespaces are? -
Django - Add several Images/Data to one field of a UserProfile model
I'm creating a UserProfile model where users can add as many or as few images to their profile as they wish. I've considered using an Image model like so: class Image(models.Model): related_profile = models.ForeignKey(UserProfile) # UserProfile is the name of the model class user_picture = models.ImageField(upload_to=get_user_img, blank=True, null=True, height_field='height_field', width_field='width_field') When somebody visits their UserProfile then all of their Image objects will be displayed; however when I want to edit the UserProfile (i.e. delete an image or two) but am unable to do this. The 'instance' doesn't want to return more than one Image object to edit as I get error: get() returned more than one Image -- it returned 2! There's a similar question like this which suggested filter() as opposed to get() here django - get() returned more than one topic though this uses a ManyToMany relationship, and the solution didn't work for my error. Does anybody know any good ways to restructure this so that I can edit each model object from the same page (so not returning the aforementioned error)? Like the title suggests, I'm wondering if it's possible to store a set of images as a list within one field of the UserProfile model because … -
Generic date views and get_context_data
In my month view I would like to count items from another model. class AuctionMonthView(MonthArchiveView): queryset = Auction.objects.filter(visible_from__gte=date.today()) date_field = "visible_from" allow_future = True template_name = 'frontend/schedule/auction-list.html' def get_context_data(self, **kwargs): context = super(AuctionMonthView, self).get_context_data(**kwargs) context['count_cars'] = Car.objects.filter(auction=self.kwargs['pk']).count() return context But django has no 'pk' it is a "KeyError". The error page says my values are: __class__ <class 'frontend.views.AuctionMonthView'> context {'auction_list': <QuerySet [<Auction: Auction April>, <Auction: test auction>]>, 'date_list': <QuerySet [datetime.datetime(2017, 4, 10, 0, 0, tzinfo=<UTC>), datetime.datetime(2017, 4, 22, 0, 0, tzinfo=<UTC>)]>, 'is_paginated': False, 'object_list': <QuerySet [<Auction: Auction April>, <Auction: test auction>]>, 'page_obj': None, 'paginator': None, 'view': <frontend.views.AuctionMonthView object at 0x7f5bdc308b70>} kwargs {'date_list': <QuerySet [datetime.datetime(2017, 4, 10, 0, 0, tzinfo=<UTC>), datetime.datetime(2017, 4, 22, 0, 0, tzinfo=<UTC>)]>, 'object_list': <QuerySet [<Auction: Auction April>, <Auction: noch eine>]>} self <frontend.views.AuctionMonthView object at 0x7f5bdc308b70> How can i get the right result from the Car model? -
Use the `with` django method to produce several aliases
At the beginning I wanted to create an aliases on a variable in a django template with something like {% loan.customer as customer %}. Someone explains to me that the best method is to use {% with loan.customer as customer %} <div> customer </div> {% endwith %} What do I have to do if I want to make several aliases with this method, e.g., {% loan.customer as customer %} and {% request.user as user %} become {% with loan.customer as customer request.user as user %} <div> customer </div> <div> user </div> {% endwith %} I think I can't do such thing, but I would like your opinion on the subject. Thanks in advance! -
Alias attribute in a django template
Could we make an alias on an attribute in a django template? I think this is not work, but I tried {% loan.customer as customer %}. Thanks! -
Django use html template from application directory
I use django 1.10.3 I want use html template from app dir I create app test_page with folder templates and testPage.html In view.py from django.shortcuts import render def page(request): return render(request, 'test_page/testPage.html', locals()) In settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] But it doesn't work. How I can use html template from dir application? -
How to save an image from Google Places API to an ImageField in a Django app?
I'm building population code to populate Django model 'City' with images from Google Places API. This is the model: class City(models.Model): city_image = models.ImageField(blank=True, upload_to='city_pictures') I built the API URL that returns a photo: #fetch image from this url city_image_url = ('https://maps.googleapis.com/maps/api/place/photo' '?maxwidth=%s' '&photoreference=%s' '&key=%s') % (maxwidth, city_image_ref, GoogleKey) Google says the response is a photo and I tested that on Postman so I want to so something like this: with urllib.request.urlopen(city_image_url) as response: city_image = response created_city = City.objects.get_or_create(city_id=city_id)[0] created_city.city_image = city_image #plus other fields But I receive this error: Traceback (most recent call last): File "C:\Users\bnbih\Djangos\excurj_proj\population_script.py", line 68, in populate() File "C:\Users\bnbih\Djangos\excurj_proj\population_script.py", line 64, in populate created_city.save() File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 886, in _save_table for f in non_pks] File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 886, in for f in non_pks] File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\files.py", line 290, in pre_save if file and not file._committed: AttributeError: 'HTTPResponse' object has no attribute '_committed' I'm using Python 3 and Django 1.10 -
Python-Django Screen Streaming [on hold]
I am working on a feature for a project that I'm not sure where to start. I have a django server running client-side and C++ in server-side. I want to make a video streaming from server-side desktop to client-side. One way to make this, is catching/encode each pixel of screen and send to client-side and get/decode this. Like in jsmpeg-vnc. But wanted something simpler TODO, something like javascript framework or django lib where would help me. Can anybody help me? -
Using Django Channels for a progress indicator
I have a django app that carries out some calculations on the server which can take up to 30 seconds. I am trying to use django channels to create a progress indicator. My setup is based on this tutorial: https://realpython.com/blog/python/getting-started-with-django-channels/ Everything is working as expected so far. I submit a task by web socket. This is received by my consumer, which calls other methods to complete the task, then returns the result by websocket. However, when I try to send multiple messages from the same consumer, all the messages arrive together at the end, rather than arriving when they are sent. Here is my consumer code: @channel_session def ws_receive(message): data = json.loads(message['text']) reply_channel = message.reply_channel.name Channel(reply_channel).send({ "text": json.dumps({'progress': 'Starting Work'}) }) # calls outside method to do work result = perform_calculations(data, reply_channel) Channel(reply_channel).send({ "text": json.dumps({'progress': 'Finished Work','result':result }) }) In this example, my front end receives the 'Starting Work' and 'Finished Work' messages at the same time, even though there is a 30 second gap between them being generated. Is there a way to get these messages to arrive in real time? -
Django - Redirecting after ajax post call with the data
I have the following html: <table id="meds" data-selection="true" data-multi-select="true"> <thead> <tr> <th data-column-id="id" data-identifier="true">ID</th> <th data-column-id="nom">Name</th> [..] </tr> </thead> <tbody> {% for med in meds %} <tr> <td>{{ med.id }}</td> <td>{{ med.nom }}</td> [...] </tr> {% endfor %} </tbody> </table> <div class="col-md-offset-10 col-md-2"> <button id="continue">Continue</button> </div> <div id="message"></div> And the following Ajax post call: jQuery(document).ready(function($) { $( "#continue" ).click(function() { var selected = $("#meds").bootgrid("getSelectedRows"); $.ajax({ type: "POST", url: "{% url 'meds:prescription' %}", data: {selected:'selected' , csrfmiddlewaretoken: "{{ csrf_token }}"}, success: function(result) { $('#message').html("<h2>Done!</h2>") } }); }); }); What I'm trying to accomplish is: I select some ids and send them by the ajax post call to a view that will display them in another template, here is my view: class PrescriptionView(generic.ListView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def post(self, request, **kwargs): selected_ids = request.POST.getlist('selected[]') meds = self.get_queryset().filter(id__in=selected_ids) return render(request, self.template_name, {'meds': meds}) For some reason, when I click on the continue button I don't get redirected to the prescription template with the ids I sent in the call, instead I just get the success message. How can I get the same view that handles the post request to list the objects according to the data received from … -
Do someone combined materialized + django 1.11??? i really wish a working template like that
I want to program a software with python-django_1.11, but i dont like the natural bootstrap style it has for default. So i want to know if someone knows how to replace materialize instead bootstrap in a django structure, or if you know a free template to provide, please i will be grateful. -
Run all the code in a Django ModelForm __init__() method after an invalid form submission
Based on this model: class Booking(models.Model): """ Model Booking with foreign key to models Session and Bundle. """ session = models.ForeignKey(verbose_name=_('Session'), to=Session, default=None, null=False, blank=False) bundle = models.ForeignKey(verbose_name=_('Bundle'), to=Bundle, default=None, null=True, blank=True) price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2, default=None, null=False, blank=False) name = models.CharField(verbose_name=_('Name'), max_length=100, default=None, null=False, blank=False) email = models.EmailField(verbose_name=_('Email'), null=True, blank=True) phone_number = models.CharField(verbose_name=_('Phone Number'), max_length=30, null=True, blank=True) def __str__(self): return "%s @%s" % (self.name, self.bundle if self.bundle else self.session) I have the following ModelForm, using a regular Class-based CreateView: class BookingForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True) class Meta: model = Booking fields = ['session','bundle', 'name', 'email', 'phone_number'] widgets = { 'bundle': forms.RadioSelect, 'session': forms.HiddenInput, } def __init__(self, *args, **kwargs): session_pk = kwargs.pop('session', False) super(BookingForm, self).__init__(*args, **kwargs) if session_pk is not False: session = Session.objects.filter(pk=session_pk).first() if session: self.fields['session'].initial = session if not session or not session.is_bookable: raise Exception("Session is not available") elif session.bundles: self.fields['bundle'].widget.attrs['choices'] = session.bundles self.fields['bundle'].initial = session.bundles[0] if len(session.bundles) == 1 else None self.fields['bundle'].empty_label = None else: del self.fields['bundle'] I only want the bundle field to be displayed if the session field has associated bundles, as the code shows. It works when I first render the template. However if I post the form with invalid fields, the bundle … -
define 2 GET ABSOLUTE URL method
Can I use it two times? What is the solution? This is my code: def get_absolute_url(self): return reverse('vehicule_app:container-view') def get_absolute_url(self): return reverse('vehicule_app:details', kwargs={'pk' : self.pk})` -
Django aggregrate/annotate with additional join
I have two model classes: Class A which represents table_a and Class B which represents table_b. Is there a way to aggregate or annotate Class A to include the value of a field in Class B other than the column that is aggregated on? The SQL query that would accomplish what I need is as follows: SELECT a.*, b2.col2 FROM table_a AS a LEFT JOIN (SELECT max(col1) AS m, a_id FROM table_b GROUP BY a_id) AS b1 ON b1.a_id = a.id LEFT JOIN table_b AS b2 ON b1.a_id = b2.a_id AND b2.col1 = b1.m But the aggregate function only retrieves this: SELECT a.*, b1.m FROM table_a AS a LEFT JOIN (SELECT max(col1) AS m, a_id FROM table_b GROUP BY a_id) AS b1 ON b1.a_id = a.id -
Django - javascript doesn't load on html page
My Django website won't load javascript files, but it does fine for the css part even tho both are in the same Static folder. base.html: <head> {% load static %} <meta charset="UTF-8"> <link href="{% static 'login/css/bootstrap.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'login/css/bootstrap-theme.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'login/css/bootstrap-theme.min.css' %}" rel="stylesheet" type="text/css"> <script src="{% static 'login/js/bootstrap.js' %}"></script> <script src="{% static 'login/js/bootstrap.min.js' %}"></script> <title>LOGIN</title> </head> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] and here is the path to static folder: /home/nikola/Desktop/GIA/static I've searched the google and solutions were pretty generic like something with the urls.py or python manage.py collectstatic (which is for deployment only), and none help. Im clueless. What seems to be the problem? -
In Django, Accessing Attributes Across Models and Apps
I have a function in a file (services.py): def balance(revenue, expenses): bottom_line = revenue - expenses return bottom_line The Revenue Model inside the Revenue App: class Revenue(model.Models): revenue = model.DecimalField() The Expenses Model inside the Expenses APP where I'd like to do a calculation on save and populate the "bottom_line" field: class Expenses(model.Models): expenses = model.DecimalField() bottom_line = model.DecimalField() def save(self, *args, **kwargs): bottom_line = balance(revenue, self.expenses) super(Expenses, self).save(*args, **kwargs) How do I access the revenue attribute during the save override on the model above? Do I need to do a queryset to get the bottom_line attribute from the Expenses model? -
calling a Django view function from django HTML template
I'm trying to call the last function in this code (def get_level_msg():) class ProductDetailView(ProductView): model = EnrollableTemplate @functional.cached_property def location(self): return get_object_or_404( Location.actives, slug=self.kwargs['location_slug']) def get_object(self): return get_object_or_404( EnrollableTemplate, slug=self.kwargs['product_slug']) def get_template_names(self): if self.get_object().category.language: return 'pdp_language.html' return 'immersion_pdp.html' def get_faqs(self): object = self.get_object() if object.is_workshop: return c.faqs['workshop'] elif object.category.language: return c.faqs['language'] else: return c.faqs['immersion'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) template = kwargs[self.context_object_name] # only display upcoming classes that have open seats available courses = (template.enrollable_set .upcoming() .select_related('template', 'venue__location') .filter(venue__location=self.location) .order_by('start_date')) loc_filter = self.request.GET.get('neighborhood') context['language'] = language = template.category.language if not self.object.is_workshop: sessions = [enrollable.session_count for enrollable in self.object.enrollable_set.upcoming()] if sessions: context['max_sessions'] = max(sessions) neighborhoods = (Venue.objects.filter(location=self.location) .filter(enrollable__in=courses) .distinct() .values_list('neighborhood', flat=True)) if loc_filter: courses = courses.filter(course__venue__neighborhood=loc_filter) context['filtered'] = True location_filters = [('?neighborhood={}'.format(n), n) for n in neighborhoods.iterator()] path = urlparse(self.request.get_full_path()).path location_filters.insert(0, ('{}#filter'.format(path), "all")) context['filters'] = [('Location', location_filters)] if language: context['featured_teachers'] = self.get_featured_teachers( self.location, language) else: try: context['featured_teachers'] = [courses[0].teacher] except IndexError: context['featured_teachers'] = None context['expectations'] = template.expectation_set.all() context['faqs'] = self.get_faqs() context['courses'] = courses context['template_id'] = template.id # import ipdb; ipdb.set_trace() if courses.exists(): course = courses[0] days_per_week = sum(1 for x in course.schedule if x is True) if days_per_week == 1: days_per_week = 'once' elif days_per_week == 2: days_per_week = 'twice' … -
How to access the request object in FormView
I want to access the request object in FormView and get client IP. As we all know, it's not very reliable to put a hidden-field in the html form because it can be changed by user if user wants do so. Therefore, I choose to do it in the backed. I use ModelForm as the form_class of FormView and exclude the ip field in the form. Here come the problem, I do know how to add the ip field dynamically. I always can't save the model successfully. Here is my code. models.py class MyModel(models): ip = models.GenericIPAddressField() [...] forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel exclude = ['ip'] views.py class MyView(FormView): form_class = MyForm [...] I've tried to change the psot() method and manually added the ip field of request.POST but I just found that I didn't know how to pass the form instance..I spent all night to solve this problem and finally I failed .. Tanks for helping in advance.. Thanks Daniel for answering this question. I changed my code into this: views.py class PollView(FormView): template_name = 'poll.html' form_class = PollForm success_url = '/thanks/' def get_ip(self,request): if request.META.has_key('HTTP_X_FORWARDED_FOR'): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] return ip def … -
What would be the easiest way to add a database to html file?
So I have made a project website with a couple html files, css and some javascript. I was thinking that I would add a login functionality and some other things like that. So I set off to find out what would be good for it. Now its is hard for me because I can't decide which one to use. I saw Django on python but I had to make a whole new project for it and I have to start from scratch. I was just thinking I would add a database to this site using something. I am just doing some lightweight things. What should I use? Thank you. -
Inserting multiple images to a blog post in Django
I want to add multiple images to the body of my blog post. I'll upload images through Admin page. I found couple videos explaining adding single images (like THIS or THIS), which I guess I can handle. I could not find a method to insert images when there might be one or more images for a given blog post. THIS was also helpful but it is more about uploading but not inserting images. # models.py: class Post(models.Model): title = models.CharField(max_length=250) body = models.TextField() slug = models.SlugField(max_length=250) publish = models.DateTimeField(default=timezone.now) class Images(models.Model): post = models.ForeignKey(Post, default=None) description = models.TextField() image = models.ImageField() # views.py: def post_detail_view(request, year, month, day, postslug): post = get_object_or_404(Post, slug=postslug, publish__year=year, publish__month=month, publish__day=day ) return render(request=request, template_name='blogapp/post/detail.html', context={'post': post}) # detail.html: {% extends "blogapp/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <h1>{{ post.title }}</h1> {{ post.body|safe }} {% endblock %} The body of the post would be like: Example blog post Here is some text. And image for this part: <img src="{{ post.image1.filename }}" alt="{{ post.image1.description }}" /> Here is some other text and image for this part: <img src="{{ post.image2.filename }}" alt="{{ post.image2.description }}" /> I'm ending my blog post …