Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Admin InlineForm add links to Detail Page of the Inline Model and add custom javascript
In Admin for InlineForm there is a link that goes to the website, be default the text is (View on site). I want to add a similar link that goes to that model(that is inline) Detail Edit Page. Insert a JavaScript script in one of the Edit/Details Model Page in Admin How can this be done ? -
d3 chart not responsive inside split container
I want to make this d3 js library chart responsive inside split pane. I use split.js for split pane and container. see this example Any helpful reply can be appreciated. Thanks in Advance <!DOCTYPE html> <html lang="en"> <head> <title>Split.js</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css"> <style> html, body { height: 100%; } body { padding: 8px; background-color: #F6F6F6; box-sizing: border-box; } .split { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; overflow-y: auto; overflow-x: hidden; } .content { border: 1px solid #C0C0C0; box-shadow: inset 0 1px 2px #e4e4e4; background-color: #fff; } .gutter { /*background-color: transparent;*/ background-color: #00000017; background-repeat: no-repeat; background-position: 50%; } .gutter.gutter-horizontal { cursor: col-resize; background-image: url('vertical.png'); } .gutter.gutter-vertical { cursor: row-resize; background-image: url('horizontal.png'); } .split.split-horizontal, .gutter.gutter-horizontal { height: 100%; float: left; } </style> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <div id="c" class="split content"> <div id="a" class="split split-horizontal"> <div id="chart-div" style="width:50vw;height:80vh;border:1px solid blue;"></div> </div> <div id="b" class="split split-horizontal"> <textarea row="8" style="height: 90%; width: 100%;"></textarea> </div> </div> <div id="d" class="split content"> <!-- <textarea row="8" style="height: 90%; width: 100%;"></textarea> --> </div> </body> <script src="split.js"></script> <script> Split(['#a', '#b'], { direction: 'horizontal', gutterSize: 8, sizes: [50, 50], cursor: 'col-resize' }) Split(['#c', '#d'], { direction: 'vertical', sizes: [50, 50], gutterSize: 8, cursor: 'row-resize' }) Split(['#e', '#f'], { direction: 'vertical', sizes: … -
Temporal Database with Django Rest Framework using perform_update
We are trying to implement a temporal database so that we are able to track changes made All our models have the following fields vt = models.DateTimeField(db_column='VT', default=datetime(3000, 12, 31, 23, 00, 00, 000000)) # Value To vflag = models.IntegerField(db_column='VFlag', default=1) # Version Flag 1 = Current, 0 = Old When using the Django rest framework I’ve tried to modify the perform_update in my viewset to duplicate the existing record, make the updates and then set temporal fields appropriately. It works when I have 1 record and the first update However once I try and make a second update it fails and create a duplicate of the changes and overrides the very first record. Original Record Currency = AUD, VFlag = 1, VT = time1 Perform update - success Currency = USD, VFlag = 1, VT = time2 Currency = AUD, VFlag = 0, VT = time1 Next perform update currently produces - fails Currency = GBP, VFlag = 1, VT = time3 Currency = GBP, VFlag = 1, VT = time3 Currency = USD , VFlag = 0, VF = time2 Expected update output Currency = GBP, VFlag = 1, VT = time3 Currency = USD, VFlag = 0, … -
Django and Flask on same nginx server
I currently have a Djago app running on my main site when I visit mysite.com. However, I'd like mysite.com/flaskapp to run a separate Flask application. I'm able to set up two nginx site-enabled config files and run each app on a different port but, for various reasons, I'd like to run them all on the same port (if possible). When I configure my flaskapp/ location in my nginx server file I get a 404 error. Here's my supervisor config file: [program:MYSITE] command=/var/www/html/MYSITE/prodenv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/MYSITE.sock MYSITE.wsgi directory=/var/www/html/MYSITE/public_html autostart=true autorestart=true stderr_logfile=/var/log/MYSITE.err.log stdout_logfile=/var/log/MYSITE.out.log [program:FLASKAPP] directory=/var/www/html/MYSITE/public_html/FLASKAPP/api command=/var/www/html/MYSITE/public_html/FLASKAPP/venv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock FLASKAPP:app autostart=true autorestart=true stderr_logfile=/var/log/FLASKAPP.err.log stdout_logfile=/var/log/FLASKAPP.out.log And my nginx site-enabled file: server { listen 80; listen [::]:80; server_name MYSITE; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/html/MYSITE/public_html; expires 30d; } location / { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/MYSITE.sock; } location /FLASKAPP/ { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock; } } I wrote a function to check the request url @app.errorhandler(404) def page_not_found(error): return 'This route does not exist {}'.format(request.url), 404 Which returns: This route does not exist http://MYSITE/FLASKAPP The Flask app is clearly working, but the routing is screwed up. How can I fix this? -
remove multiple cross sign when using python autocompelete light in django
I have implemented django-autocomplete-light with django 1.5. But in that i have face one issue like when i set default value of form, this library display multiple cross sign for single record. In that i have used choiceWidget. Here I attached image of issue. Here Some of code : event_form = event_form_class(initial={'klant': klant}) forms.py (in that event_form_class define ) self.fields['klant'].widget = autocomplete_light.ChoiceWidget('KlantAutocomplete') in template i have used following line: {{ event_form.klant }} -
Where can I write the after query logic in RetrieveAPIView?
Where can I write the after query logic in RetrieveAPIView? In my models.py I have a Message class: class Message(models.Model): """ message """ message_num = models.CharField(default=getMessageNum, max_length=16) title = models.CharField(max_length=64) content = models.CharField(max_length=1024) is_read = models.DateTimeField(null=True, blank=True) create_user = models.ForeignKey(User, related_name="created_messages") receive_user = models.ManyToManyField(User, related_name="received_messages") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.title In the views.py: # the message list class UserMessageListAPIView(ListAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages # the message detail class UserMessageRetrieveAPIView(RetrieveAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages You see, in the UserMessageRetrieveAPIView I can retrieve the message instance. How can I do the logic to set the message's is_read ? Where I can set it? -
django HTML ajax did not alert?
I finally get the report successfully, but the ajax-alert did not show, just nothing shows in my website. why this happened? how to re-write hte code ? here is my code: ajax: function get_report(dataname){ $.ajax({ url:"/file_parse/", type:"POST", contentType: "application/json", async: true, data:JSON.stringify({ 'button':'button2', 'data':dataname }), //提交参数 success:function (data) { if(data.status == 'success'){ alert('OK') } } }) } <td> {% csrf_token %} <input type="button" id="btn2" class="btn btn-info btn-xs" name="{{item.sn}}" value="report" onclick="get_report(this.name)"> </td> views: if button_name == 'button2': ...... report.save return HttpResponse("{'status':'success'}", content_type='application/json') -
django test cases can't get past the @login_required decorator on a view function
I've scoured stackoverflow and tried several different solutions, but my test code always goes to the login redirect. This is what I have: class LoggedInSetup(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username="lolwutboi", password="whatisthepassword") self.client.login(username='lolwutboi', password='whatisthepassword') number_of_submissions = 13 for sub in range(number_of_submissions): Submission.objects.create(title='Amazing', description='This is the body of the post', author=str(self.user), pub_date=timezone.now()) class LoggedInTestCases(LoggedInSetup): def test_logged_in_post_reachable(self): self.client.login(username='lolwutboi', password='whatisthepassword') resp = self.client.get('submission_post') self.assertEqual(resp.status_code, 200) -
What steps should I follow on creating Django based Facebook app?
I noticed that a lot of code snippets found on the internet are outdated or deprecated, that's why I want to ask somebody experienced about what library or SDK should I use to quickly and painless create an web application that will retrieve some facebook user data (by consent), process it and output a result ? I am familiar with Django, that's why I want to do that in python/django. Also I will be thankful if some snippets / examples provided. Basically, it would help me a lot in my process of understanding how it works. -
Django seems to be ignoring my CSRF token header
I am updating a project from Django 1.8 to Django 1.11. This project was in a functional (production-ready) state prior to me beginning upgrade work - so I suspect that there's a Django / Django REST Framework code change that I've been caught up in. I have a REST / JSON API exposed via Django REST Framework, and am interfacing with this API via JavaScript. Using 'unsafe' HTTP verbs against the API (e.g. POST) is resulting in a 403 Forbidden response: {"detail":"CSRF Failed: CSRF token missing or incorrect."} I can clearly see (in Chrome developer tools) I am passing a CSRF token via a HTTP header: HTTP_X_CSRFTOKEN:dTOkbfkOn1cumhbF64nHSvLbdC4k95vNgRVZ0WleUDLKl5Iuo95flMkKyKFvFIPp Which corroborates with my CSRF_HEADER_NAME setting: In [3]: settings.CSRF_HEADER_NAME Out[3]: 'HTTP_X_CSRFTOKEN' (I am setting this by passing the CSRF token to JavaScript in a template file, which I haven't included because this doesn't seem to be the broken part (I can see the CSRF token header)). Is anyone aware of a Django / DRF change that could've affected me? -
How to Embed Code and Images in a Blog Post
I'm trying to teach myself Django, by creating a personal blog. At the moment I have a Post class in my models, that stores the body as a TextField. Similar to class Post(models.Model): title = models.CharField(max_length=150) body = models.TextField() author = models.ForeignKey(Author, related_name='blog_posts') published = models.DateTimeField(default=timezone.now) slut = models.SlugField(max_length=100, unique_for_date='publish') Which does 90% of what I want. What I want to be able to do though, is include things in the body of the post that aren't text. Specifically images, and code snippets. How can I achieve that? Is there a data type that I can use? Or some other way? -
Posting json data to django rest create api view?
I have a form: class ProductFormView(FormView): form_class = ProductForm template_name = 'forms/ajax.html' success_url = '/form-success/' model looks as: class Product(models.Model): name=models.charfield() category=models.Foreignkey(Category) ... class Category(models.Model): type=models.Foreignkey(Type) created=.. .... and ajax.html: $(document).ready(function(){ var $myForm = $('.my-ajax-form') $myForm.submit(function(event){ event.preventDefault() var $formData = $(this).serialize() $.ajax({ method: "POST", url: 'api/create', data: $formData, success: handleFormSuccess, error: handleFormError, }) }) function handleFormSuccess(data){ console.log(data) } function handleFormError(jqXHR, textStatus, errorThrown){ console.log(jqXHR) console.log(textStatus) console.log(errorThrown) } }) To send the product category through the form onto api I used the view to obtain the object through context data.Its not working ..How can we send the object of category through ajax? -
Testing multiple file upload to a model viewset using APIClient's post in Django Rest Framework
I'm new to Test Driven Development and was trying to test an endpoint like so: url = '/v3/edm-list/extract/' c = APIClient() c.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) with open(test_email_list_path, 'rb') as eml, open(test_exclude_list_path, 'rb') as exl: data = { 'tickers': tickers, 'email_list': eml, 'exlude_list': exl, 'exclude_keywords': exclude_keywords, 'simular_user_num': similar_user_num } response = c.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) Using APIClient's post, I'm sending a post request to my model viewset: class EDMListViewSet(viewsets.ModelViewSet): queryset = EDMList.objects.all() serializer_class = EDMListSerializer With the model: class EDMList(models.Model): tickers = models.CharField(max_length=512) email_list = models.FileField(upload_to='edm_list/consolidated_emails') exclude_list = models.FileField(upload_to='edm_list/excluded_emails') exclude_keywords = models.CharField(max_length=512) similar_user_num = models.IntegerField() And serializer: class EDMListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EDMList fields = ('tickers', 'email_list', 'exclude_list', 'exclude_keywords', 'similar_user_num') Now whenever I run my tests, it returns: Traceback (most recent call last): self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 But whenever I open the browsable API, and post there, I runs correctly. I'm guessing the problem is how I use the client's post, but I have no idea what I'm doing wrong. -
how to simplify this code in django views?
total = { 'count': 0, 'price': 0 } for goods in estimate.goods_list.all(): total['count'] += goods.count total['price'] += goods.count * goods.goods.price return render(request, 'estimate/detail.html', {'estimate':estimate, 'total': total}) in django views, how to simplify this codes? can i delete the for block? -
functional test in django cant find an element by id
I want to get the content of a table in a html file through browser.find_element_by_id(), but I always get the same error, even when I have tried different options. I don't know whether the error is in the html, the urls, the views or the tests files. This is the error I get: ====================================================================== ERROR: test_multiple_users_can_start_lists_at_different_urls (functional_tests.tests.NewVisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/hugo/Code/AttractoraProject/AttractoraDjango/functional_tests/tests.py", line 71, in test_multiple_users_can_start_lists_at_different_urls self.wait_for_row_in_list_table('1: Buy peacock feathers') File "/home/hugo/Code/AttractoraProject/AttractoraDjango/functional_tests/tests.py", line 27, in wait_for_row_in_list_table raise e File "/home/hugo/Code/AttractoraProject/AttractoraDjango/functional_tests/tests.py", line 21, in wait_for_row_in_list_table table=self.browser.find_element_by_id('id_list_table') File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 341, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 855, in find_element 'value': value})['value'] File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute self.error_handler.check_response(response) File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="id_list_table"] This is the urls.py file: from django.conf.urls import url from django.contrib import admin from Attractora import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home_page, name='home'), url(r'^Attractora/new$', views.new_list, name='new_list'), url(r'^Attractora/the-only-list-in-the-world/$', views.view_list, name='view_list'), ] This is the views.py file: from django.shortcuts import redirect, render from Attractora.models import Item # Create your views here. def home_page(request): return render(request, 'home.html') def view_list(request): items=Item.objects.all() return render(request, 'list.html', {'items':items}) def new_list(request): Item.objects.create(text=request.POST['item_text']) return redirect('/Attractora/the-only-list-in-the-world/') This is the … -
CSS disappears when 'DEBUG' Django is turned False
I'm working with Django and I'm using a AdminLTE framework for the estilização, but, when I turn the DEBUG to False, the page shows with pure html. DEBUG = True: DEBUG = False: -
parse python datetime object in javascript within django app
I'm passing the following variable to a template: from django.utils import timezone dt = timezone.now() print(type(dt)) # <class 'datetime.datetime'> Everything works fine if I use it in my HTML directly: {{ dt | date:'D d M Y' }} which renders to Thu 14 Dec 2017. However when I try to access the variable in my javascript I get an error: <script> {{ dt | safe }} </script> Uncaught SyntaxError: missing ) after argument list Furthermore, I get a slightly different error when I try to render a list of datetime objects: dt_list = [timezone.now() for _ in range(3)] and within my js: <script> console.log({{ dt_list | safe }}) </script> Uncaught SyntaxError: Unexpected token < So my question is how can I convert a python datetime object to something I can use in JS? -
Rendering internally linked markdown files in django
I want to link to markdown pages in a markdown page served by django. For example, in a markdown page index.md, I have a link [link label](path/page1.md) But when I click the link, I don't get the rendered page (as I intended). In stead I get the option to download the file. The markdown page index.md is rendered as expected. Is there a solution? -
Is there a Pythonic way to handle object chains that could contain None?
My Django codebase has foreign key references that are a few objects deep and it feels like a code smell to have to check for truthiness at each level. Is there a way to check for this kind of thing in a more pythonic way with less boilerplate? Take this simplified example: if page.banner.image: # ... If page.banner is optional and it doesn't exist it will return None and throw an exception saying, rightly, that NoneType doesn't have an image attribute. The obvious fix is if page.banner and page.banner.image: # ... But this will get repetitive and verbose. I suppose you could use getattr() to do something like I'm after but it's even uglier: if getattr(getattr(page, 'banner', None), 'image', None): # ... Is there a concise way to do this without all these conditional clauses? -
Routing with Polymer and Django
I am trying to set up an app using Polymer/Django. I have one template that basically exists to instantiate my base component (admin-panel), which works rather swell. The trouble is that now the that I use inside my component doesn't pick up any changes! What gives? Here's my template: <head> <link rel="import" href="{% static 'index.html' %}"/> <script src="{% static 'bower_components/webcomponentsjs/custom-elements-es5-adapter.js' %}"></script> <!-- Load webcomponents-loader.js to check and load any polyfills your browser needs --> <script src="{% static 'bower_components/webcomponentsjs/webcomponents-loader.js' %}"></script> <link rel="import" href="{% static 'src/admin-panel.html' %}"/> </head> <body> <admin-panel></admin-panel> </body> My Django urlpatterns all resolve to the above template: urlpatterns = [ url(r'^(?!api).*$', views.index, name='index'), ] And here's the part of my admin-panel component: <app-location route="{{route}}" url-space-regex="^[[rootPath]]"> </app-location> <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{routeData}}" tail="{{query}}"> </app-route> <app-drawer-layout fullbleed narrow="{{narrow}}"> <!-- Main content --> <app-header-layout has-scrolling-region> ... stuff ... <iron-pages selected="[[page]]" attr-for-selected="name" fallback-selection="not-found-page" role="main"> <landing-page name="landing-page"></landing-page> <organization-detail-page name="organization-detail-page" route="[[query]]"> </organization-detail-page> <not-found-page name="not-found-page"></not-found-page> </iron-pages> </app-header-layout> </app-drawer-layout> Anyone else used app-route with django templates? What did you do? -
Annotating an annotation in Django
I would like to perform an aggregation by group, and then count the distinct results of that aggregation. For example, this would apply to making a histogram of total sales across a company: Product.objects.values('salesperson')\ .annotate(total_sales = Sum('quantity_sold'))\ .values('total_sales')\ .annotate(count = Count('total_sales')) This would ideally result in a list of counts of total_sales (over salespeople) like (0, 10) (1, 24) (3, 55) ... But I get an error like: FieldError: Cannot compute Count('total_sales'): 'total_sales' is an aggregate This seems to be because I can't perform the second aggregation after the first. I can probably do this outside of SQL, but it would be nice if there was a clean solution inside SQL. -
Django/Nginx server says Android app's POST requests are connecting, but they aren't
I am trying to send JSON from an Android app to a Django/Nginx/UWSGI server and return an HttpResponse to the app. The Android code worked perfectly when I ran it on a Django server without Nginx or UWSGI, but it did not work when I tried to use it with Nginx/UWSGI installed. My app logs a java.io.FileNotFoundException: https://www.placeholder.com/my_url error when I try to POST the JSON, but my server's /var/log/nginx/access.log shows the POST request as successfully connecting. Moreover, nothing shows up in /var/log/nginx/error.log;. I suspect something on my server is preventing the POST request from being completed. I modified my keepalive_timeout and keepalive_requests in nginx.conf but it made no difference. I also tried adding a configuration recommended here to my sites-enabled/sites-available files. For reference, here are the uncommented parts of my nginx.conf file: # nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; # (original) keepalive_timeout 65; keepalive_timeout 1000; # keepalive_requests added to file keepalive_requests 100000; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } Plus the content … -
Insert a variable into url string - Django App
I am developing a Django App and I need to insert a variable into a url string defined in the front-end (javascript) to get a json file from a user's folder: '{% static "users/ userName /file.json" %}' I would like to have userName as a variable. I tried different syntaxes but no luck so far. Do you know any solution for this? Thank you very much for your help ! -
Django models for non user-created tables
I am working on a project using veekun's pokedex sqlite database, and using it in a django project. They have many tables including encounter rates, pokemons, types, etc. Most of these the user will not need to interact with (really only needs to read from database, not create, update, or delete). Is it worth it to create models based off the database either manually or through inspectdb? Will I see any performance boost? I am new to django so I may be misunderstanding the purpose of models here. -
allowing different users to edit fields of a matrix
what i want to achieve: i have a page with a matrix that can be edited by a single mainuser and viewed by several basicusers. the mainuser can allow each basicuser to edit a certain amount of rows. -> Each basicuser can edit their assigned rows and the mainuser can oversee everything and accept everything when finished The solution that first came to mind was creating matrices according to this matrix model in django and adding permissions viewing and editing to each cell object. The mainuser has a permission cell_distribution which displays additional buttons that allow him to grant basicusers editing permission for cells/rows and move forward once the matrix is completely filled. Is this the best way to achieve what i want or are there easier ways? (e.g. with packages like django-matrix-field or django-numpy)