Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webpack hot module replacement through Django template
I'm trying to set up hot module replacement for my bundled frontend static assets that are served through Django's template system, if that's even possible. I'm currently refreshing the page via livereload whenever the compiled assets are changed, but the compile times are getting longer and any CSS changes end up triggering a full page reload. Here is an example of the template file in Django. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <!-- Header Links --> </head> <body> <div id="app"></div> <script type="text/javascript"> window.CONFIG = { /** Injected application configuration from Django. */ }; </script> <!-- Webpack bundle url --> <script src="{{ bundle_url }}"></script> </body> </html> I've been able to serve the assets through webpack dev server and inject the bundle url http://localhost:3000/bundle.js through template variables, so I can see the application in the view. Webpack Configuration 'use strict'; const webpack = require('webpack'); const CONFIG = require('./config'); /** * Webpack configuration for a development environment. * @type {Object} */ module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ require.resolve('core-js/shim'), CONFIG.PATHS.ENTRY, ], output: { path: CONFIG.PATHS.BUILD, filename: CONFIG.OUTPUT_FILENAME, }, module: { rules: CONFIG.SHARED_RULES.concat([{ test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }]), }, resolve: CONFIG.WEBPACK_RESOLVE, plugins: [ new … -
Forbidden 403 Using Django CAS
I'm attempting to implement CAS into a Django Application, I'm using django-cas-ng for my implementation, I've gotten to a point where I'm able to go to https://myproject/accounts/login and successfully login to CAS, but immediately upon logging in, I'm met with a Forbidden 403 page. The URL returned upon a logon is: https://myproject/accounts/login?next=%2F&ticket=ticket. I'm unable to find any documentation on how to proceed next, I synced (makemigrations && migrate for my Django version), and assured that my settings.py had the proper configuration. I'm not sure where to proceed from here, any help is appreciated greatly! -
Django : Primary Key is getting null value
Consider the following model : from django.db import models class Album(models.Model): id = models.IntegerField(primary_key=True,null=False) artist = models.CharField(max_length=200) album_title = models.CharField(max_length = 250) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length = 200) def __str__(self): return "id = " + str(self.id) + " artist = " + self.artist + " album = " + self.album_title + " genre = " + self.genre class Song(models.Model): id = models.IntegerField(primary_key=True) album = models.ForeignKey(Album,on_delete=models.CASCADE) file_type = models.CharField(max_length = 200) song_title = models.CharField(max_length = 200) def __str__(self): return "id = " + str(self.id) + "album = " + self.album.album_title + "song = " + self.song_title When i am inserting a row in either Album or Song using positional parameters and not giving, django is providing NULL to that particular row. Why so? -
How to have user log in and registration on same page using django
Currently I have a user log in page and a user sign up page, how can I have both of these on one single page? Base.html: <!doctype html> <head> {% block head %} <title>base</title> {% endblock %} </head> <body> {% block body %} {% endblock %} </body> </html> signup.html: {% extends 'core/base.html' %} {% block head %} <title> Sign Up</title> {% endblock %} {% block body %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} login.html: {% extends 'core/base.html' %} {% block head %} <title> Login</title> {% endblock %} {% block body %} <h1>Login</h1> <form method = 'post'> {% csrf_token %} {{ form.as_p }} <!--'form' comes from login view imported in urls--> <button type = 'submit'>Login</button> </form> {% endblock %} urls.py: from django.conf.urls import url from django.contrib import admin from django.contrib.auth.views import login from core import views as core_views urlpatterns = [ url(r'^$', core_views.login_redirect, name = 'login_redirect'), url(r'^admin/', admin.site.urls), url(r'^login/$', login, {'template_name': 'core/login.html'}, name='login'), url(r'^signup/$', core_views.signup, name='signup'), url(r'^account/$', core_views.account_page, name = 'account_page') ] views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm def … -
How to keep oauth2_provider tokens in Redis?
I'm using the django framework and found the following situation. I need to keep the access tokens stored in redis, but I could not save those templates on redis, only cache. How i can save my access tokens on redis using oauth2_provider ? -
Adding multiple items using the raw_id_field popup
I am using the Django admin site and I have a m2m relation which uses raw_id_fields in the admin panel. A user can add an item to the m2m model using the popup window but I would like to be able to select multiple items at once and add them all. Is this at possible with the current framework or would customisation be needed. If customisations are needed, how would I go about doing that. -
Django 1.11 TypeError: view must be a callable or a list/tuple in the case of include()
I'm experiencing an error trying to add images to my Django templates. I'm getting this traceback: File "/Users/user/Desktop/Projects/hello-web-app/hellowebapp/urls.py", line 58, in <module> 'document_root': settings.MEDIA_ROOT, File "/Users/user/Desktop/Projects/hello-web-app/venv/lib/python3.6/site-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). This is the originating codeblock from my urls.py file: if settings.DEBUG: urlpatterns += [ url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ] And my following imports: from django.conf import settings from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.views import password_reset, password_reset_done, password_reset_confirm, password_reset_complete from django.views.generic import TemplateView, RedirectView from django.contrib.sitemaps.views import sitemap from collection.backends import MyRegistrationView from collection import views from collection.sitemap import ThingSitemap, StaticSitemap, HomepageSitemap I have a hunch that it is due to me using Django 1.11 and it not accepting the current URL pattern. Can't seem to find a workaround. Any help is appreciated! Thanks! -
django reduce wkhtmltopdf time possible?
is there a way to reduce pdf generate time when using wkhtmltopdf? I am currently using wkhtmltopdf which generates pdf. I have files which can be selected in bulk then being generated into pdf (in average 400kb each pdf) and then zip all pdf being generated and download. I have it all worked out but I realized in production server, it took quite awhile to have the whole process done. Even if there's only one pdf being generated and then compressed into zip, it'll take a bit time too. (by a bit maybe 10-15 secs? for that one file) I had done bulk file zip before with size 2.x mb or more and the zip compressing is quite fast. So I am thinking it should be the wkhtmltopdf that's slowing down? Let me know if I am wrong that I should be asking about reducing zip generate time instead of wkhtmltopdf (I tried googling both options but no luck) Thanks in advance for any advices and help. -
Django: Is this bad practice?
Here's the functionality that I'm looking for -- A user fills out a form on the default page, index.html. When it is submitted, I receive a POST request, whose contents I add to a database. Next, I want to load a new page whose content will be contingent on the information from the form. This is my implementation -- I'm handling the POST request within my index(request) function. I originally returned a HTTPResponseRedirect(navigation/route.html), but I later found after searching StackOverflow that it is not possible to both redirect and send the contents of the form. I'm working around this by returning render(request, 'navigation/route.html', {'form': form}). I'm just concerned because it seems like HTTPResponseRedirect intentionally prevents the user from passing POST request data, meaning my attempt to bypass that structural restriction might be a bad idea. Here is the relevant portion of my views.py: def index(request): if request.method == 'POST': # populate form with information from POST request form = TripForm(request.POST) if form.is_valid(): # input into database trip_instance = Trip(**form.cleaned_data) trip_instance.save() # redirect return render(request, 'navigation/route.html', {'form': form}) else: # either request is not POST or form did not pass validation checks form = TripForm return render(request, 'navigation/index.html', {'form': form}) -
I have a model with a field and I would like a view to order the items in a specific order based on the value for the field
I have an Item model for menu items which can be a daily special. If they are a daily special I would like them to be ordered by day of the week starting with Monday. I believe the view should be doing the sorting. Here is my models.py class Item(models.Model): CATEGORY_CHOICES = (('Sandwich', 'Sandwich'), ('Salad', 'Salad'), ('Slider', 'Slider'), ('Side', 'Side'), ('Drink', 'Drink')) DAYS = ((0,'Monday'), (1,'Tuesday'), (2,'Wednesday'), (3,'Thursday'), (4,'Friday'), (5,'Saturday'), (6,'Sunday')) name = models.CharField(max_length=50) description = models.TextField() category = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField(max_length=30, choices=CATEGORY_CHOICES) order = models.PositiveSmallIntegerField(default=0, blank=True, null=True) day = models.CharField(max_length=30, choices=DAYS, unique=True, blank=True) publish = models.DateField(auto_now=False, auto_now_add=False), updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.name Here is my views.py: def specials(request): # days = (('Monday'), ('Tuesday'), ('Wednesday'), ('Thursday'), ('Friday'), ('Saturday'), ('Sunday')) specials_list = Item.objects.filter(special = True) # specials_list = sorted(specials_list, key=days) //Trying to sort the list by days of the week context = { 'specials_list': specials_list, } return render(request, 'menu/specials.html', context) I feel like I am really close here. Thanks in advance! -
Why are people using Django templates with webpack to connect DRF with ReactJS?
Am I missing something? But I am really not getting the rationale behind most online blogs and tutorials suggesting to use a base Django template to render a ReactJS bundle (bundled from webpack). In my mind, the point of using Django Rest Framework in the first place is to completely isolate the frontend from the backend and have something like Nginx serving an html file that would import the ReactJS library (like any other stndard html/js project). The ReactJS layer would then get or manipulate data solely through the DRF REST API. It is like most developers treat ReactJS as a completely novel beast, when it can be simply treated as standard JS (with added steroids) that runs on the browser. Can someone therefore explain to me what are the advantages of using the methods depicted by blogs such as Jonathan Cox and Owaislone ? -
Dropzone form won't display
I'm trying to add the dropzone form to a django template and it won't show up. I've imported using django's static and downloaded the dist folder from http://www.dropzonejs.com/ and used <form action="/file-upload" class="dropzone" id="my-awesome-dropzone"></form> as instructed by the website. <html> {% extends 'base.html' %} {% block head %} <head> {% load staticfiles %} <script src="{% static '/dropzone/dropzone.js' %}"></script> <link href="{% static '/dropzone/dropzone.css' %}" rel="stylesheet"> <link href="{% static '/dropzone/basic.css' %}" rel="stylesheet"> </head> {% endblock %} {% block body %} <body> <form action="/file-upload" class="dropzone" id="my-awesome-dropzone"> </form> </body> {% endblock %} </html> I know it's not an issue with static in django because I have bootstrap working using static within this project. Any idea as to why dropzone won't display? -
django Error during template rendering Reverse for
I am tring to use 'edit' : in html: {% for people in people_list %} <tr> <td>{{ people.name }}</td> <td>{{ people.phone }}</td> <td> <a href="{% url 'delete' people.id %}">delete</a> <a href="{% url 'edit' people.id %}">update</a> </td> </tr> in views: def edit(request,people_id): if request.method == 'GET': people = get_object_or_404(People,pk=people_id) form = Form(initial={'name': people.name, 'phone': people.phone}) return render(request, 'edit.html', {'form': form}) else: form = Form(request.POST) if form.is_valid(): People.objects.filter(pk=people_id).update(**form.cleaned_data) return HttpResponseRedirect(reverse('detail')) return render(request, 'edit.html', {'form': form }) in urls: url(r'^delete/(?P<people_id>\d+)$', views.delete, name='delete'), url(r'^edit/(?P<people_id>\d+)/$', views.edit, name='edit') i got this error: NoReverseMatch at /edit/9/ Reverse for 'edit' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['edit/(?P\d+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/edit/9/ Django Version: 1.9.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'edit' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['edit/(?P\d+)/$'] Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\django\core\urlresolvers.py in _reverse_with_prefix, line 508 Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.6.0 Is there something wrong in urls? (im a new boy play with django) -
How to set the x-axis of a Django-Nvd3 chart to string format?
I am building a very simple multi-bar chart. I was hoping to make the x-axis into string format. Unfortunately, the default format is an integer, and I couldn't figure out a way to override it. Does anyone know if I could write a javascript to force the override? Thanks! views.py xbardata = ["return", "volatility", "sharpe ratio"] ybardata1 = [expectedReturn, expectedVolatility, expectedSharpeRatio] ybardata2 = [BMReturn, BMVolatility, BMSharpeRatio] barChartData = {'x': xbardata, 'name1': fund, 'y1': ybardata1, 'name2': 'Benchmark', 'y2': ybardata2, } html <div> {% load_chart "multiBarChart" barChartData "multibarchart_container"%} {% include_container "multibarchart_container" 220 450 %} </div> -
The view posts.views.create didn't return an HttpResponse object. It returned None instead
having problem with my posts.view page enter image description here this is my views page but the error still keeps on coming that not httpresponse -
Does Django support fuzzy matching within a queryset?
What I'm doing right now is I'm querying the database for potential matches based off field_0, and then I'm running a loop for all qs entries for potential matches in field_1. Like so: matching_candidates = [] target_words = 'Some relevant string' for record in Records.objects.filter(sender=sender): if Levenshtein.ratio(record.another_field, target_words)>.75: matching_candidates.append(record) Unfortunately this is too slow as it's querying everything, and the larger the database grows, the worse off this becomes. Unfortunately I can't do regex searches since target_words changes all the time. Is there a better way to do this? -
Loading modal image just after clicking on the button
I'm having a hard time trying to do this, find the way to do it and explain myself, so I'll try my best to explain everything. First of all I'm working on a django project. I have a html file where I want to load a series of images which is already done, for certain reason I have to load those images in a javascript I put them on a string and after that it puts them on div in the html Everything works the way it should work but what I have to do is that if someone clicks one of those images, lets say for example the img number 4, a modal will appear and show the img on a bigger scale with some data, data I already have on the js and the image, the problem is: I want to make this more efficient and I want to avoid loading everything at once, I just want to load the image that will appear on the modal just after clicking on it. Thanks -
Delaying evaluation of Hypothesis strategies for Django models
I have a Django model. Among other things it has a ForeignKey to User: class MyModel(models.Model): foo = models.BooleanField() bar = models.ForeignKey(User) I have a method in my tests that generates me an appropriately shaped User - generate_test_user() I want to write some tests with Hypothesis to assert assorted properties about instances of my model. My first implementation looked like this: class MyTestCase(TestCase): @hypothesis.given(models(MyModel, bar=just(generate_test_user()))) def test_my_model(self, mymodel): pass However this fails because generate_test_user gets called at import time and thus tries to create a model before Django migrations etc. have run. What's a good way to craft a strategy such that the right things get evaluated at the right times / delay evaluation of the just call / similar? -
install bs4 in pythonanywhere server
I tried to install requests and beautiful soup module (bs4) in pythonanywhere server by this command: pip3 install requests but it got and error said: requirement already satisfied... and got an address to dist-package directory. I found requests package there but when I run my app and open my django website it gives an error said: no module named requests. on the other hand when I try to install bs4 using this command: pip3 install bs4 it gives permission denied error. what should I do? how can I install a python package in pythonanywhere server. -
Where to programmattically define ProductAttributes
In developing a shipping method for a Oscar Commerce project, I found that I need two attributes; one containing a float value representing the product weight (I'm using the Scale class for weighing products) and an entity attribute that links to a shipping container model. The attributes need to be assigned to any product class that has shipping required. Where/how do I create them? I have the following code, but I'm not sure where it fits. from oscar.core.loading import get_model ProductAttribute = get_model('catalogue', 'ProductAttribute') ProductAttribute.objects.get_or_create(code='weight', product_class=[product class], defaults={ 'name': 'Weight', 'type': ProductAttribute.FLOAT, }) ProductAttribute.objects.get_or_create(code='box', product_class=[product class], defaults={ 'name': 'Box used for shipping' 'type': ProductAttribute.ENTITY, }) Where is the best place to add this code? -
Reset models __init__ get_field().default
I can't reset my init default value. I've got a model whith choices and no default value. I've got two proxy models of this model with init default. class Test(models.Model): CHOICE_LIST = ((1, 'Choice1'),(2, 'Choice2') type_test = models.CharField(choices=CHOICE_LIST, max_length=1) class Test1Manager(models.Manager): def get_queryset(self): return super(Test1Manager,self).get_queryset().filter(type_test='1') class Test2Manager(models.Manager): def get_queryset(self): return super(Test2Manager,self).get_queryset().filter(type_test='2') class test1(Test): objects = Test1Manager() class Meta : proxy = True def __init__(self, *args, **kwargs): self._meta.get_field('type_test').default = '1' super(Test1, self).__init__(*args, **kwargs) class test2(Test): objects = Test2Manager() class Meta : proxy = True def __init__(self, *args, **kwargs): self._meta.get_field('type_test').default = '2' super(Test2, self).__init__(*args, **kwargs) In the admin, when I add an instance of Test1,the value of type_test is 1, as I expected. When I add an instance of Test2, the value is also correct and the default value is 2. But when I add an instance of Test, the default value of the field is the last one opened. In fact, if before I ve open test2_admin, the default value of the field in Test will be 2. So I want to reset the default value of this field on Test model. I've tried to set default=None, but in this case, the select field displays only values 1 and 2, no … -
Use Django ORM outside of Django
I'm new to Django and want to use its ORM in my scripts without running whole django thing. I'm scratching my head how to configure it. Searches on stackoverflow didn't help as answers don't show the full picture. Therefore, I created a small project: app.py manage.py orm/ __init__.py models.py manage.py has configuration: from django.conf import settings settings.configure( DATABASE_ENGINE = 'mysql', DATABASE_NAME = 'db', DATABASE_USER = 'admin', DATABASE_PASSWORD = '', DATABASE_HOST = 'localhost', INSTALLED_APPS = ('orm') ) models.py: from django.db import models class Label(models.Model): name = models.CharField(max_length=50) # required max_length and finally my main file app.py: from django.conf import settings from django.db import models from orm.models import * # do database maniupaltions Though after running app.py I receive an error that: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What am I doing wrong? -
Django website - html metadescription not translated while google searching
I have a weird issue and I still don't know why. I'm working on a website using Django 1.10. Default language is english and it is translated in french and portuguese. The pseudo code of the index.html looks like this : <html lang="{{ LANGUAGE_CODE }}"> <head> <meta charset="utf-8"> <title>{% trans "Some title"%}</title> <link rel="alternate" href="http://www.domain_name.com/en/" hreflang="en"/> <link rel="alternate" href="http://www.domain_name.com/fr/" hreflang="fr"/> <link rel="alternate" href="http://www.domain_name.com/pt/" hreflang="pt"/> <meta name="description" content="{% trans "Some text" %}"> All translations work when I'm on the page, however, when I search my website on google, title and metadescription are in English for the French version (the URL is the right one however). Everything works fine for the portuguese version. I'm quite confused about that, has anyone a clue ? -
Rerendering a model in admin that acceses both an m2m field and a foreign key field
I have a model called Statement and it has a field called "keyword_pairs" that creates a with another model called KeywordInContext. KeywordInContext has two fields: "keyword" and "context". "keyword" develops a foreignkey with an instance of a model called Keyword. "context" develops a m2m relationship with the model Keyword. This is creating a pairing system so that each Keyword has a set of keywords it can pair with. However, the way that the admin change page for Statements renders the KeywordInContext model is just with the default drop down box for m2m relationships. This drop down box allows you to select the "keyword" field of the KeywordInContext model, but doesn't allow any modification or adding of "contexts." Someone would simply be able to update/add a statement and implicitly say "this Statement has a bunch of KeywordInContext objects with their "keyword" field set to what I select from this drop down menu." But they to actually add the context that they want to specify for the keyword, they would have to go the change page for KeywordInContext. This inhibits a paired submission of a 'keyword' and 'context' to add on to the 'keyword_pairs' on the admin side. What can I do … -
Django-wkhtmltopdf Renders Template but the Fields are Empty
I have followed the documentation for Django-wkhtmltopdf and I able to generate a PDF which looks like the html template I have created. What I am not getting is the data that is generated and displayed in the HTML. My views.py: class MyPDF(PDFTemplateView): filename = 'dailygoals.pdf' template_name = 'reports/goals.html' cmd_options = { 'margin-top': 3, } My urls.py: urlpatterns = [ url(r'^pdf/', MyPDF.as_view(), name='pdf'), ] A portion of the goals.html template that initiates the wkhtmltopdf process: <div class="form-group"> <a class="btn btn-success" href="{% url 'reports:pdf' %}">Save to PDF</a> </div> It renders the pdf as my goals.html, the data is just missing. I tried adding context = "function_that_generates_data" to the class MyPDF object but this did not work. I cannot figure out what I am doing wrong.