Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override accepted renderer in django-rest-framework on exception
I'm using django-rest-framework to create an endpoint which returns a PDF. However, when there is an error rendering the PDF, I want to return a JSON response. But DRF passes the data for the exception to my PDFRenderer class. How can I use JSONRenderer instead, only if there is an error? class PDFRenderer(BaseRenderer): """ DRF renderer for PDF binary content. """ media_type = 'application/pdf' format = 'pdf' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return bytes(data) For example, when my view says raise PermissionDenied(), because the authorized user does not have permission to view the requested PDF, DRF passes {'detail': 'You do not have permission to perform this action.'} as the data argument to PDFRenderer.render. -
Why is checkmarx reporting XSS for my template?
I'm not sure I understand enough as to why checkmarx is reporting that there is a XSS issue with this code. I am using multiple templates in the very same fashion and there is no issue, but the one for my base.hml is. I thought django had security protections in place to handle these sorts of attacks? Am I not understanding something? I've even tried removing all the urls but that is not the issue. Here is the checkmarx message: This element's value flows through the code without being properly sanitized or validated and is eventually displayed to the user in method base_html at line 616 of views.py. This my enable a Cross-Site-Scripting attack. ScreenShot: checkmarx report views.py def base_html(request): return render(request, "base.html") temlplate.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/src/jquery/jquery-3.2.1.min.js"></script> <link rel="stylesheet" href="/src/bootstrap-3.3.7/dist/css/bootstrap.min.css"> {% block header_style_sheet %} <link rel="stylesheet" href="/src/css/base.css"> {% endblock %} <script src="/src/bootstrap-3.3.7/dist/css/bootstrap.min.css"></script> <style> {% block header_style %} {% endblock %} </style> {% block script_addons %} {% endblock %} <script> {% block header_constants %} const BASE_ADDRESS = "http://127.0.0.1:8000"; {% endblock %} {% block addon_script %} {% endblock %} </script> </head> <body> {% load staticfiles %} <ul id="top-nav"> <h4 id="nav-title" style="margin-left:10px;margin-top:15px;color:white;float:left;"></h4> <li … -
Trying to Load on Template Image Uploaded to ImageField
With the Code Below all that renders in the alt option of the image... The code works if I hardcode the below HTML statment with the actual filepath of the image : src"media/media/image.jpg. This is my html statement: <img class="first-slide" src="media/{{Home.slide_1.photo.url}}" alt="First slide"> This is my Models.py: class Photo(models.Model): photo = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg') photo_caption = models.CharField(max_length=25) photo_description = models.CharField(max_length=50) master_album = models.ManyToManyField('Album', related_name="album") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = PhotoManager() def __str__(self): return self.photo_caption class Home(models.Model): slide_1 = models.ManyToManyField('Photo', related_name="slide_1") slide_2 = models.ManyToManyField('Photo', related_name="slide_2") slide_3 = models.ManyToManyField('Photo', related_name="slide_3") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Real-time chat using Django backend with Angular 4 frontend and PostgreSQL database
I am trying to create real-time chat using Django backend with Angular 4 frontend and PostgreSQL database. Let's assume that I would like to create chatbot for instance like A.L.I.C.E. I would like to write message on frontend, press enter and send my message to backend. Then I would like to get a response. In addition I would like to add all messages to my database. I am trying to do this in the way shown below but I am not sure how can I add messages to database. It seems to me that it should be done using models. I am not sure but it seems to me that response should be also defined in models.py not in routing.py as it is done at this moment. I will be grateful if you could show me how it should be done. Thanks in advance. routing.py: from channels.routing import route from backend.consumers import ws_connect, ws_receive, ws_disconnect channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] consumers.py: # In consumers.py from channels import Group import json # Connected to websocket.connect def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_receive(message): … -
Django: "wsgi_dev.py is not execitable"
I'm brand-new to Django and sort-of new to ython. I'm trying to set up Django on my windows-based machine. I'm using Apache as the web server. I am using a local wsgi_dev.py instead of the generated wsgi.py. I'm getting the following errors: [Fri Aug 04 14:58:12.267407 2017] [win32:error] [pid 3604:tid 1272] [client 127.0.0.1:52207] AH02102: C:/wamp/www/circuits/circuits/circuits_database/wsgi_dev.py is not executable; ensure interpreted scripts have "#!" or "'!" first line [Fri Aug 04 14:58:12.267407 2017] [cgi:error] [pid 3604:tid 1272] (9)Bad file descriptor: [client 127.0.0.1:52207] AH01222: don't know how to spawn child process: C:/wamp/www/circuits/circuits/circuits_database/wsgi_dev.py [Fri Aug 04 14:58:12.308435 2017] [win32:error] [pid 3604:tid 1268] [client 127.0.0.1:52208] AH02102: C:/wamp/www/circuits/circuits/circuits_database/wsgi_dev.py is not executable; ensure interpreted scripts have "#!" or "'!" first line, referer: http://circuits-dev.local/circuits/circuits [Fri Aug 04 14:58:12.308435 2017] [cgi:error] [pid 3604:tid 1268] (9)Bad file descriptor: [client 127.0.0.1:52208] AH01222: don't know how to spawn child process: C:/wamp/www/circuits/circuits/circuits_database/wsgi_dev.py, referer: http://circuits-dev.local/circuits/circuits I have the following in my httpd.conf file: AddHandler cgi-script .py And then further down: WSGIPythonPath "c:/wamp/www/py3DjangoVenv/lib/python3.6/site-packages" WSGIPythonHome "c:/wamp/www/py3djangovenv" <VirtualHost *:80> VirtualDocumentRoot "C:/wamp/www/%0" ServerName circuits-dev.local SetEnv DB_NAME circuits WSGIScriptAlias / "c:/wamp/www/<myapp>/<myapp>/<appname>/wsgi_dev.py" Alias /static/ "c:/wamp/www/<myapp>/<myapp>/static/" #C:\wamp\www\<myapp>\<myapp>\<appname> <Directory C:/wamp/www/<myapp>/<myapp>/<appname>> <Files wsgi.py> Require all granted </Files> </Directory> <Directory C:/wamp/www/<myapp>/<myapp>/static> Require all granted </Directory> Any suggestions as to what might be going … -
Using js and ajax to retrieve data from django server
I want to load info on mouse hover, mouse event is working but don't know if it's hitting the url $(document).ready(function() { $('.user').hover(function (e) { var offset = $(this).offset(); var left = e.pageX; var top = e.pageY; var theHeight = $('#myPopoverContent').height(); $('#myPopoverContent').show(); $('#myPopoverContent').css('left', (left+10) + 'px'); $('#myPopoverContent').css('top', (top-(theHeight/2)-10) + 'px'); $.ajax({ url: $(this).closest(".username").attr("data-url")/, type: 'get', data: form.serialize(), dataType: 'json', }); }); $('#myPopoverContent').focusin(function (e) { $('#myPopoverContent').active(); }); $('#myPopoverContent').mouseout(function (e) { $('#myPopoverContent').hide(); }); }); <div class="user-block"> <span class="username" data-url="{% url 'pop_user' question.user %}"> <a class="user" href="{% url 'profile' question.user %}"> {{question.user.profile.get_screen_name }} </a> </span> </div> I have views function accordingly I want to return the data from views, but it;s not working -
In Django, why can you call `order_by` on a field created by extra, but not `filter`?
Let's say I have a Django model called MyModel. I'm allowed to say query = MyModel.objects.all() query = query.extra(select={is_sam : "name = 'sam_bobel'"}) query = query.order_by('is_sam') (Go down to the order_by bullet in this link for proof). But replace that last line with query = query.filter(is_sam=True) and you would get an error, because you're not allowed to filter by extra fields. (As said HERE) I don't understand why you would be able to do one and not the other. To me, it seems like they both require Django to know about the is_sam field, so I'm surprised they're treated differently. The more in-depth the answer, the better. I would really love to know. I'm using Django 1.8 by the way, if that makes a difference. -
how to make a django subcategory
How do i make a subcategory for django. I want something like this Question mathematics 1984 this is my model class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.name class PastQuestion(models.Model): category = models.ForeignKey(Category) subject = models.CharField(max_length=128) question = models.TextField() posted_by = models.CharField(max_length=50) def __unicode__(self): return self.subject` -
How to show how many records in django databes I have?
I have a little problem. In my models.py file I have two classes: class Categories and class Websites. In Categories by the admin panel I added many records of categories. How to show in html file for example : how many webstites were added in the category 'Company' or in the another categories? -
Can you pass a kwarg key as a parameter into a function?
I'm repeating a block of code and would like to a write a function to reduce clutter. I'm having trouble passing in the kwarg key hourly_id (last line of the original code). Original Code # Create Hourly data. hourly_data = validated_data.pop('hourly') hourly_points_data = hourly_data.pop('data') hourly = Hourly.objects.create(**hourly_data) for hourly_point_data in hourly_points_data: hourly_point = HourlyPoint.objects.create( hourly_id=hourly.pk, **hourly_point_data) <-- This New Function def create_data_block(self, data, block_str, DataBlock, DataPoint, id): block_data = data.pop(block_str) points_data = block_data.pop('data') block = DataBlock.objects.create(**block_data) for point_data in points_data: point = DataPoint.objects.create( id=block.pk, **point_data) <-- This Function Call self.create_data_block(validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id') So you can see here I am trying to pass hourly_id as id using a string, but I get a database error saying that that hourly_id was missing so I'm clearly not passing it in correctly. Traceback Traceback (most recent call last): File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.5/contextlib.py", line 30, in inner return func(*args, **kwds) File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch … -
I keep running into issues with web.py
Okay, so I actually had an issue with this line of code beforehand but I realized, thanks to a fellow answer from this site, that I had to delete my web.py folder from my directory and reinstall an updated version. I decided to go with the developer version. Upon doing so I noticed that my initial run of code worked, but after I updated it and refreshed my browser, I got a huge error. I have tried to fix this several times, and I reinstalled like 10 times. I went into debugger.py and found no real solution as every time I updated it, the code refused to run. I have searched the internet for days trying to find a proper fix but no one has reciprocated my error. To better illustrate my error his my code. import web urls = ( '/(.*)', 'index' ) app = web.application(urls, globals()) class index: def GET(self, name): print ("Hello", name, '. How are you today?') if name=="main": app.run() It runs without an error, but when open my page or refresh it after an initial run, it gives me this... enter image description here Now keep in mind, that my first run works, and if … -
Menu shared by all applications in Django
I've built a menu as a templatetag in Django>1.9. The problem is that following this solution, I can't put the templatetag at the root of the folder, as I'm getting a: TemplateSyntaxError: 'menu' is not a registered tag library Below is the part of my settings.py that I've modified: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Look for base template at root of project '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', ], # Look for base templatetags at root of project 'libraries': { 'project_tags': 'templatetags.menu', } }, }, ] Does Django support project-wide templatetags at all? -
How to ignore or redirect a http request in Django?
I use a Angular 4 frontend and Python Django int the backend. If I click on a the detail button I run the openDetail methode in my component openDetail(id:number){ this.router.navigate(['/motor/detail', {"id": id}]) } the browser opens the detail componente with the URL http://localhost:8000/motor/detail;id=21. Perfekt. Important to know is, that I just need the id to work with them in my detail component. But if I refresh the page I run into a 404 error. --> The current path, motor/detail;id=21, didn't match any of these. Well, this is also clear and jumpt into the backend. main - urls.py #... some other urls... url(r'^motor/', include('motorControll.urls')), motors - urls.py url(r'^$', views.index, name="index"), url(r'^overview/$', views.MotorMapping.as_view({'get': 'getAllData'})), url(r'^detail/$', views.index, name="index"), url(r'^detail/(?P<id>\d+)/$', views.MotorMapping.as_view({'get': 'getById'})), url(r'^detail/save/$', views.MotorMapping.as_view({'post': 'save'})), How can I ignor this call or run a redirect to the index page? I need the id, because the next step, after load the detail page is to load the details by this url http://localhost:8000/motor/detail/21 , it returns a JSON with all data. -
invalid parameter to prefetch_related()
I'm trying to do an inner join on these 3 tables using PersonScore but it can't find persontype. What am i doing wrong? models: class PersonScore(models.Model): id = models.IntegerField(primary_key=True) # AutoField? person = models.ForeignKey(‘Person’) class Person(models.Model): id = models.IntegerField(primary_key=True) # AutoField? name = models.CharField(max_length=255) class PersonType(models.Model): person = models.ForeignKey(‘Person’) type = models.CharField(max_length=255) code: PersonScore.objects.filter(person__name="Bob").prefetch_related("person__persontype") error: Cannot find 'persontype' on Person object, 'person__persontype' is an invalid parameter to prefetch_related() -
Getting Error On First Run With Buildbot
I'm following the docs trying to get Buildbot working for the first time and I keep getting the same error: 2017-08-04 13:58:45-0400 [-] while starting BuildMaster Traceback (most recent call last): File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/twisted/internet/defer.py", line 1442, in gotResult _inlineCallbacks(r, g, deferred) File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/twisted/internet/defer.py", line 1386, in _inlineCallbacks result = g.send(result) File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/buildbot/util/service.py", line 53, in reconfigServiceWithBuildbotConfig yield svc.reconfigServiceWithBuildbotConfig(new_config) File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/twisted/internet/defer.py", line 1532, in unwindGenerator return _inlineCallbacks(None, gen, Deferred()) --- <exception caught here> --- File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/twisted/internet/defer.py", line 1386, in _inlineCallbacks result = g.send(result) File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/buildbot/www/service.py", line 209, in reconfigServiceWithBuildbotConfig self.setupSite(new_config) File "/home/mike/tmp/bb-master/sandbox/lib/python2.7/site-packages/buildbot/www/service.py", line 274, in setupSite "could not find plugin %s; is it installed?" % (key,)) exceptions.RuntimeError: could not find plugin grid_view; is it installed? You can see in the last error message it says the grid_view plugin could not be found. I'm not sure if I need to do anything else not outlined in the docs. I'm assuming when installing Buildbot it would install the proper plugins needed. Has anyone came across this error when running Buildbot? Any ideas on how to get Buildbot running? Python version: 2.7.5 Buildbot version: 0.9.10 Twisted version: 17.5.0 Link to the docs I'm following. -
How do I change the font-size of a bootstrap-select drop-down menu?
I tried to set a separate css class to overide the style of the dropdown menu. However, it's not working. #form.py class fundForm(forms.Form): fund = forms.ChoiceField(choices=FUND, required=True, widget=forms.Select(attrs={'class': 'selectpicker .selectStyle'})) class META: model = fundList #html .selectStyle{ font-size: 5px } -
Setting up a sever on Google Cloud with Postgresql database?
I've been trying for about two weeks now to set up a server for a completed Django app on the google cloud shell. All of the documentation for gcloud is confusing and sends me to several different pages for one task and it is very hard to keep track of what to do. Sites like digitalocean, which is useful for Django program setup, doesn't work on gcloud. I haven't figured out a way to connect a postgres VM to my program through the cloud shell despite having the server running. I am very lost in setting this up. Could someone please help me set up my Django app? It runs perfectly on localhost but when trying to implement it into the google cloud nothing works. I've done the django-gcloud tutorial already and set up a simple site just by importing the code from google, which doesn't help because all it does is import a completed app and you just type in "gcloud app deploy" which doesn't explain how to set it up so that you can do that. My program uses python 3, DjangoRestFramework, and Celery. The database is Postgresql. My full module list is: Django-1.11.2 amqp-2.1.4 astroid-1.5.3 billiard-3.5.0.2 celery-4.0.2 … -
How to mock a Django model object (along with its methods)?
I'm trying to mock a chained Django model object in the following dummy method, # utils.py def foo_something_exist(): if Foo.objects.get(a='something').exist(): return 'exist' # test.py import unittest.mock import patch import utils . . . @patch('utils.Foo') def test_foo_something_exist_returns_none(self, mock_foo): mock_foo.objects.get.exists.return_value = False self.assertIsNone(utils.foo_something_exist()) . . . test_foo_something_exist() fails the test. I discovered that Foo.objects.get(a='something').exist() in utils.py was a MagicMock object (<MagicMock name='Member.objects.get().exists()' id='xxxxxx'>) instead of False, which contributed to the failure of this test function. And yes, I've also tried mock_foo.objects.return_value.get.return_value.exists.return_value = False, which was mentioned in a post. Pointers/hints for correctly mocking a model object (with its chained methods) is appreciate. Thank you in advance. -
Django or angularjs are adding a route on my urls on the <a> tags
im using a function to create urls in a block of text, overthought im just adding a simple route eg: www.google.com before I use the function the a tag on the page is a regular tag: www.google.com when I click the link it opens vmhost:8000/www.google.com -
Django is unable to load angular chunks
I am trying to integrating django and angular4 but in the console I am getting Error: Loading chunk 1 failed. I know what the problem is but I am unable to solve that. This is my app.routing.ts import { Routes } from '@angular/router'; import { AdminLayoutComponent } from './layouts/admin/admin-layout.component'; import { AuthLayoutComponent } from './layouts/auth/auth-layout.component'; export const AppRoutes: Routes = [{ path: '', component: AdminLayoutComponent, children: [{ path: '', loadChildren: './dashboard/dashboard.module#DashboardModule' }, { path: 'email', loadChildren: './email/email.module#EmailModule' }, { path: 'components', loadChildren: './components/components.module#ComponentsModule' }] }, { path: '', component: AuthLayoutComponent, children: [{ path: 'authentication', loadChildren: './authentication/authentication.module#AuthenticationModule' }, { path: 'error', loadChildren: './error/error.module#ErrorModule' }, { path: 'landing', loadChildren: './landing/landing.module#LandingModule' }] }, { path: '**', redirectTo: 'error/404' }]; It works without children but lazy load chunks are not loading in django. Any help would be appreciated. -
Django Forms - Multiple Chained Models
I have four models that are connected: StockItem, Location, LocationClass, LocationType: StockItem has a foreign key linking it to Location, and Location has foreign keys linking it to both LocationClass and LocationType. But StockItem does not have foreign keys linking it to LocationClass and LocationType. I am trying to use django-smart-selects (and similar options) on a search form (that searches the Stock Items). I am using ModelMultipleChoiceField fields for querying StockItems based on the Location, LocationClass, and LocationType (among other fields). What I want to do (and am struggling with) is the following: If I select "Park" in LocationType, I want the ModelMultipleChoiceFields for Location to narrow down to just the locations of the chosen LocationType so that the user does not have to scroll through hundreds of locations options before finding their desired location to submit the search form and narrow down results. However, since I do not have a direct foreign key in my Location model linking Location directly to LocationType, I'm not sure how to best approach this. Currently, the only relevant field in the StockItem model is 'location', which I defined as: location = models.ForeignKey('locatApp.Location') (I am using a cached list to get the search fields … -
Tango With Django population script - models not updating after calling save()
So, I've started taking the "Tango with Django" tutorial(no Python background) and it's really silly of me to ask for help, but I just can't figure out what's wrong. This is a really simple task and it bothers me because I can't figure out what the problem is. I am supposed to modify the script in a way that my Category model would have a certain number of likes and views for test purposes. The script looks like this: import os def populate(): python_cat = add_cat('Python',128,64) add_page(cat=python_cat, title="Official Python Tutorial", url="http://docs.python.org/2/tutorial/") add_page(cat=python_cat, title="How to Think like a Computer Scientist", url="http://www.greenteapress.com/thinkpython/") add_page(cat=python_cat, title="Learn Python in 10 Minutes", url="http://www.korokithakis.net/tutorials/python/") django_cat = add_cat("Django",64,32) add_page(cat=django_cat, title="Official Django Tutorial", url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/") add_page(cat=django_cat, title="Django Rocks", url="http://www.djangorocks.com/") add_page(cat=django_cat, title="How to Tango with Django", url="http://www.tangowithdjango.com/") frame_cat = add_cat("Other Frameworks",32,16) add_page(cat=frame_cat, title="Bottle", url="http://bottlepy.org/docs/dev/") add_page(cat=frame_cat, title="Flask", url="http://flask.pocoo.org") for c in Category.objects.all(): for p in Page.objects.filter(category=c): print ("- {0} - {1}".format(str(c), str(p))) def add_page(cat, title, url, views=0): p = Page.objects.get_or_create(category=cat, title=title)[0] p.url=url p.views=views p.save() return p def add_cat(name,views,likes): c = Category.objects.get_or_create(name=name)[0] c.views = views c.likes = likes c.save() return c if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rango.settings') import django django.setup() from rangoapp.models import Category, Page print("Starting Rango population script...") populate() I tested the … -
I can't create my first Django project, Helpppp me
I execute following codes on command line Django_admin startproject first And I met following error Traceback (most recent call last): File "/usr/local/bin/django-admin", line 7, in from django.core.management import execute_from_command_line ImportError: No module named django.core.management -
Django and postgres schema
I have a problem with using schema while running tests with django. All tables in my postgres database are in schema, let's name it 'schema'. In my settings.py i added: 'OPTIONS': { 'options': '-c search_path=schema', 'connect_timeout': 5, }, to tell django to use 'schema' schema. All production code is working perfectly. Problem is: When i added DB testing and run python manage.py test it resulted with django.db.utils.ProgrammingError: no schema has been selected to create in I tried to remove schema-line from settings.py and add 'schema.' at the beginning of every db_table name in models.py. It worked for tests, but now when i run my production code, it ends up with: django.db.utils.ProgrammingError: relation "schema.table" does not exist How can i tell manage.py to create db with schema, so i don't have to modify models.py or settings.py? Or how can i properly add usage of my schema in models.py ? -
Placement of Custom Code to Validate Form Fields in Django
Where should custom code to validate form fields in Django be placed? In forms.py? Also, is it acceptable to pass the request object to a method in forms.py? In particular, I have some code to validate a Google recaptcha. Currently, this code is in my Django view. Any advice would be appreciated. Thanks.