Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Mobile application and django
Is there in github or somewhere else a template for a mobile application (with a server) in which a user can submit something, and other users can subscribe for observing it? -
Annotating Django querysets with ForeignKey Counts subject to conditions
Here is a simplified version of my models: class Airport(models.Model): iata = models.CharField() name = models.CharField() latitude = models.FloatField() longitude = models.FloatField() class Flight(models.Model): origin = models.ForeignKey('Airport', related_name='origins') destination = models.ForeignKey('Airport', related_name='destinations') owner = models.ForeignKey(User) Given a User, I would like to create a list of all the Airport objects that appear in either the origin or destination fields of the Flight objects he owns, each annotated with the corresponding number of Flight objects. For example, suppose a user has been on 3 flights: LAX-LHR, LHR-CDG, and CDG-JFK. Then I would like a query which returns the following object: [LHR, id__count=2}, {CDG, id__count=2}, {LAX, id__count=1}, {JFK, id__count=1}] In the above, the three letter codes stand for Airport objects or all their fields. Generally, there may be thousands of Users and tens of thousands of Airports and Flights, so I am seeking something more efficient than the obvious solution with for loops and if statements, preferably in a single database query. My current progress is this query: Airport.objects.filter( Q(origins__owner=user) | Q(destinations__owner=user) ) .distinct() .annotate( id__count=Count('origins', distinct=True) + Count('destinations', distinct=True) ).order_by('-id__count') This works perfectly with only one user, because the initial filter only keeps those airports which appear somewhere in his flights. … -
Stripe with Django - make form clean() method return value that isn't a form field
I am integrating Stripe payment processing into my Django app, and I can't figure out the 'correct' way to verify the customer's card information and insert a row into my Users table that contains the user's Stripe Customer ID. Ideally, I'd love to do something along the lines of the following, in which my CheckoutForm verifies card details and raises a form ValidationError if they are incorrect. However, using this solution, I can't figure a way to get the customer.id that's generated out of the clean() function. forms.py class CheckoutForm(forms.Form): email = forms.EmailField(label='E-mail address', max_length=128, widget=forms.EmailInput(attrs={'class': 'form-control'})) stripe_token = forms.CharField(label='Stripe token', widget=forms.HiddenInput) def clean(self): cleaned_data = super().clean() stripe_token = cleaned_data.get('stripe_token') email = cleaned_data.get('email') try: customer = stripe.Customer.create( email=email, source=stripe_token, ) // I can now get a customer.id from this 'customer' variable, which I want to insert into my database except: raise forms.ValidationError("It looks like your card details are incorrect!") views.py # If the form is valid... if form.is_valid(): # Create a new user user = get_user_model().objects.create_user(email=form.cleaned_data['email'], stripe_customer_id=<<<I want the customer.id generated in my form's clean() method to go here>>>) user.save() The only other solution I can think of is to run the stripe.Customer.create() function in views.py after the form is … -
Generic "Please correct the error below." Django Admin
I've found some Django tickets talking about this issue, but I can't get it to work. Basically, I have a parent model which has 3 inlines (Each having a foreign key to the same field according to the parent model). Something like this, class ModelA(models.Model): somefield = models.TextField(unique=true,null=true) ... class ModelB(models.Model): somefield = models.ForeignKey('ModelA', to_field='somefield'...) ... class ModelC(models.Model): somefield = models.ForeignKey('ModelA', to_field='somefield'...) ... class ModelD(models.Model): somefield = models.ForeignKey('ModelA', to_field='somefield'...) ... I can make any changes to the parent models and/or to inlines except for the field that is a Foreign key to others child models. In the Admin I get the "Please correct the error below." even though no error appears on my form. I'm looking for possible solutions since my problem won't be easily reproducible. -
repo2 is a library for repo1
In the moment, I have two github repositories, i.e. repo1 and repo2. Both are two django projects created by our team. In requirements.pipin ~/work_projects/repo1, I have the line -e git+ssh://git@gitlab.com/repo2.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=repo2 Hence, repo2 becomes a library used by repo1 in ~/.virtualenvs/venv/src (repo1's virtual environment). In the moment, I need to modify both repositories at the same time. So my main focus in the moment is each time I modify repo2, I need to test out the results on repo1. I want to look at the impact of repo2 on repo1 once modified. I don't want to push my changes on github and reinstall repo2 on repo1 each time I want to see those changes. How could I make it works easily, workaround? -
django simple history - how to create history when the object is not created in admin
I'm using django-simple-history==1.9.0 package with django 1.8. When I create an object outside the admin and then look at the history of the object in the admin page, it shows a message This object doesn't have a change history. It probably wasn't added via this admin site. I tried setting the user for that object: user = User.objects.get(username='john') Poll.objects.get(id=536).history.update(history_user=user) but that did not solve the problem. Poll.objects.get(id=536).history.all().count() returns 1 so there is a history generated. Any ideas how to make it show the history or how to create an additional history? I also tried update_change_reason but that did not work at all.