Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
> Unexpected token '<' [duplicate]
This question already has an answer here: unexpected token < in first line of html 2 answers In my project I get the bellow error in browser: Unexpected token '<' But the code seems no error. -
Getting User Information from Django Python Social Auth in the view
First time working with python-social-auth and Django but having trouble figuring out exactly how much information about the user's social account is available to me. When I access the extra_data of the UserSocialAuth object I can get the uid, and the access_token. To get additional details am I to feed those through the social company's (ex facebook) API? I can see that for some social auths like facebook Django's user object is magically populated with the first and last names from the social profile, but for others like LinkedIn that doesn't work. How do i find out which information is available for each social auth without manually probing each one? I'm just trying to get as much "Profile" data from the user and am worried going through the API is the "long way" of achieving this. I have actually read through the documentation but it may be too advanced for me; im not sure how to use the data that is acquired by the pipeline from the view. I'm not even sure if that sentence makes sense! -
change the status being shown when either one of the button has been selected in a table Django
May i know why is my status remain unchanged when either "approve" or "deny" button has been selected for that particular row. How can i pass the value that i change in views.py back to my html file in order to print out the status ? Should i declare the Action field in models.py since action is just 2 buttons with name of approve and deny? .html file <form method="POST" action=""> {% csrf_token %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th> Student ID </th> <th> Student Name </th> <th> Start Date </th> <th> End Date </th> <th> Action </th> <th> Status </th> </tr> {% for item in query_results %} <tr align="center"> <td> {{item.studentID}} </td> <td> {{item.studentName}} </td> <td> {{item.startDate|date:'d-m-Y'}} </td> <td> {{item.endDate|date:'d-m-Y'}} </td> <td> <input type="submit" name="approve" id="approve" value="approve" > <input type="submit" name="deny" id="deny" value="deny" > </td> <td> {% if not item.action %} Pending {% endif %} </td> </tr> {% endfor %} </table> </form> when i try to print query_results in console, i can't see that the status has been changed views.py def superltimesheet(request): query_results = Timesheet.objects.all() data={'query_results':query_results} supervisor = SuperLTimesheet() if request.POST.get('approve'): supervisor.status = "approved" supervisor.save() return redirect('/hrfinance/superltimesheet/') elif request.POST.get('deny'): supervisor.status = "denied" supervisor.save() return redirect('/hrfinance/superltimesheet/') return … -
How django receive post file from android
I use Django 1.11 and Python 3.5. I have a question about Django receive post file. I found when android post multipart/form-data file, my Django request.POST and request.FILES is null. Please help me how to receive post file. -
Django share requests.session() between views
I make 2-3 calls to an API URL per view and using requests.session() cuts down the connection time by a significant amount. Is there a way to keep the session open between views to avoid the initial setup time? -
django migrate error: django.db.utils.ProgrammingError: must be owner of relation gallery_image
I've done some changes to a site on the local version, pushed models to the server and did a makemigrations (revampenv) sammy@samuel-pc:~/revamp$ python manage.py makemigrations gallery Migrations for 'gallery': 0032_auto_20170829_0058.py: - Create model Area - Create model Color - Create model ThumbnailCache - Add field unique_key_string to image - Alter field example on image - Alter field timeline on image worked fine then I tried to migrate and I get this error (revampenv) sammy@samuel-pc:~/revamp$ python manage.py migrate Operations to perform: Apply all migrations: account, sessions, admin, auth, thumbnail, contenttypes, gallery Running migrations: Rendering model states... DONE Applying gallery.0032_auto_20170829_0058...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, … -
Cronned Django command output not posted in tee from bash script
I'm trying to have a bash script that controled by cron to be ran every day and I would like to grep some lines from the python (Django) output and post it with slacktee to my slack channel. But I am only catching some warnings from the script, not my own prints (something to do with std::out and std::err)? But I can't seem to be able to debug it. #!/bin/bash printf "\nStarting the products update command\n" DATE=`date +%Y-%m-%d` source mypath/bin/activate cd some/path/_production/_server ./manage.py nn_products_update > logs/product_updates.log tail --lines=1000 logs/product_updates.log | grep INFO | grep $DATE So for each day, I'm trying to grep messages like these: [INFO][NEURAL_RECO_UPDATE][2017-08-28 22:15:04] Products update... But it doesn't get printed in the tee channel. Moreover, the file gets overwritten everyday and not appended - how to change that, please? The tail command works ok when ran in the shell by itself. How is it possible? (sorry for asking two, but I believe they are somehow related, just cant find an answer) This is just in case the cron entry. 20 20 * * * /bin/bash /path/to/server/_production/bin/runReco.sh 2>&1 | slacktee.sh -c 'my_watch' Many thanks -
How to pass several views return statements to one template in Django?
Currently I have one template file that displays some graph results based on one Django view, however, I would like to display in this same template another set of results from another function view. These are the details: first function view - This works OK, sending values to the second function view and rendering the results into the template. @api_view(['GET','POST',]) def tickets_results_test(request): if request.method == "GET": # ...do stuff... return render(request, template_name, {'form': form}) elif request.method == "POST": template_name = 'personal_website/tickets_per_day_results.html' year = request.POST.get('select_year', None) week = request.POST.get('select_week', None) receive_send_year_week(year,week) ... rest of the code ... data = { "label_number_days": label_number_days, "days_of_data": count_of_days, } my_data = {'my_data': json.dumps(data)} return render(request, template_name, my_data) second function view - I want to return these results into the template file. def receive_send_year_week(year,week): return year, week template file - I want to show the results from the second function view below the You are currently reviewing: {% extends "personal_website/header.html" %} <script> {% block jquery %} var days_of_data = data.days_of_data function setChart(){ ....do stuff to generate graphs... .... } {% endblock %} </script> {% block content %} <div class='row'> <p>You are currently reviewing:</p> </div> <div class="col-sm-10" url-endpoint='{% url "tickets_per_day_results" %}'> <div> <canvas id="tickets_per_day" width="850" height="600"></canvas> </div> … -
Django TypeError: authenticate() takes exactly 0 arguments (3 given)
Django version 1.10.7 I'm getting TypeError: authenticate() takes exactly 0 arguments (3 given) Importing the authenticate() like this: from django.contrib.auth import authenticate, login Calling authenticate() like this : authenticate(request, username=request.POST['username'] ,password=request.POST['password']) -
How to do unit testing of REST API's of a Python Django project
I'm new to Python and Django. Please help me with info/examples of unit testing the REST API's of a django project. Can we do that using Pytest? -
Web programming: Python PowerShell errors
I'm at the beginning of learning to code in Python (and second or third time using PowerShell but first time it appears to me so I wish help). PS E:\website> python manage.py shell python : Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 At line:1 char:1 + python manage.py shell + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Python 3.6.2 (v...ntel)] on win32:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) -
404 error for popup modal form in django
I am getting 404 error for a popup form, I am trying to open on clicking a text link. accounts/urls.py url("_/user-popup/(?P<key>\w+)/$", views.user_popup_form, name="user_popup_form"), url("_/user-popup/(?P<key>\w+)/(?P<pk>[^/]+)/$", views.user_popup_form, name="user_popup_form"), accounts/views.py-- POPUP_FORMS = { "profile": { "form": forms.UserProfileForm, "templates": { ".nav_user_name": "user/nav_user_name.html", ".profile_info": "user/profile_info.html", ".about_text": "user/about_text.html", } } # etc. } def user_popup_form(request, key, pk=None): """ Handle any form with a "user" field pointing back to the logged in user. Otherwise return a HttpResponseForbidden response. """ if (not request.user.is_authenticated) or (not key in POPUP_FORMS): raise HttpResponseForbidden() content = {} instance = POPUP_FORMS[key]['form']._meta.model.objects.filter(user=request.user) if pk: instance = instance.filter(pk=Hasher.decode(pk)[0]) else: if not isinstance(POPUP_FORMS[key]['form']._meta.model.user.field, OneToOneField): instance = None instance = instance[0] if instance else None if request.POST or request.FILES: form = POPUP_FORMS[key]['form'](request.POST, request.FILES, instance=instance, initial={"user": request.user}) success = form.is_valid() if success: instance = form.save(commit=False) instance.user = request.user try: instance.save() except IntegrityError: success = False form.errors['__all__'] = ["Form data not unique - have you already added one of these?"] except Exception as e: success = False form.errors['__all__'] = [e] else: models.User.objects.update() request.user.refresh_from_db() POPUP_FORMS[key]['form']._meta.model.objects.update() for name, template in POPUP_FORMS[key]['templates'].items(): content[name] = render_to_string(template, {"profile": request.user.profile}, request) else: form = POPUP_FORMS[key]['form'](instance=instance, initial={"user": request.user}) success = False return JsonResponse({ "form": Template("{% load crispy_forms_tags %}{% crispy form %}").render(Context({"request": request, "form": form})), "title": capfirst(key), … -
Converting Tuple inside of an array into a dictionary in Python
I have been trying to solve this problem but I cannot get it right :( I am querying mySQL database in Django, and my results comes back as a tuple inside of an array. Please see dummy data below; query_results = [ (500, datetime.date(2017, 1, 1)), (302, datetime.date(2017, 1, 2)), (550, datetime.date(2017, 1, 3)), (180, datetime.date(2017, 1, 4)), (645, datetime.date(2017, 1, 5)), (465, datetime.date(2017, 1,6)) ] 500, 302, 550 etc... are my records. The next element are the date of those records. I would like to append them into a dictionary using a loop, but I always get an error of: TypeError: list indices must be integers, not tuple. Can anyone please give me some advise on how to append these into something like this: myDict = { "record": "", "date": "" } All help is greatly appreciated! -
How to custom Ckeditor image uploader
So guys i'am using Ckeditor in my django project but i notice on the image/file uploader modal some useless tabs and fields the question is how can i remove them for the user experience and thanks in advance -
Django m2m signal, retrieving which element was added to the m2m field
This is my m2m signal def new_pet_added_to_hooman(instance, **kwrags): for pet in instance.pets.all(): pet.become_jelly() And I'm connecting it by using signals.m2m_changed.connect This is triggered by hooman.add(pet). But this will also make my "new" pet jelly. Ideally I want to set all pets EXCEPT for the recently added one to jelly, and then perform some other stuff to the newly added pet def new_pet_added_to_hooman(instance, **kwrags): for pet in instance.pets.exclude(id=new_pet): pet.become_jelly() new_pet.pamper() Something like this. Is it possible to retrieve which entry triggered the signal? i.e. Which new pet -
django - static css file 404 error not loading
I'm trying to figure out the static files part of building a django website. My static css file "base.css" is not loading in any way by my website and I can't figure out why. settings.py STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) template base.html {% load static %} ... <link rel='stylesheet' type='text/css' href='{% static "css/base.css" %}' /> ... I have a 'static' folder on the same level as my django app, with base.css as a file there. cms --blog --cms --static ----css ------base.css --db.sqlite3 --manage.py When I use the inspect tool in chrome, on the console tab it says that the file is not found (404 error). What am I missing here? Why is it not loading? -
Google App Engine (GAE) Improperly Configured Database
I have a working Django project that will deploy using Heroku. I am having trouble getting the app to deploy on GAE. When I run it locally, I get an error referring to an Improperly Configured database backend. Any help would be appreciated. Error: ... raise ImproperlyConfigured(error_msg) ImproperlyConfigured: 'postgresql' isn't an available database backend. Try using django.db.backends.XXX, where XXX is one of: 'dummy', 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3' <br> Error was: No module named postgresql.base ... app.yaml runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: main.app libraries: - name: django version: "latest" beta_settings: cloud_sql_instances: <cloudsql-connection-string> settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxx', 'USER': '*****', 'PASSWORD': '******', 'HOST': 'xx.xx.xx.xx', 'PORT': '5432', } } If I change the Engine to 'ENGINE': 'django.db.backends.postgresql_psycopg2' I get the error: ImportError: No module named psycopg2.extensions pip freeze returns: Django==1.11.4 psycopg2==2.7.3.1 pytz==2017.2 -
Remove hardcoded values from settings
Code Snippet LIFECYCLE_TYPES = { 'viaf:personal': "986a7cc9-c0c1-4720-b344-853f08c136ab", # E21 Person 'viaf:corporate': "3fc436d0-26e7-472c-94de-0b712b66b3f3", # E40 Legal Body 'viaf:geographic': "dfc95f97-f128-42ae-b54c-ee40333eae8c", # E53 Place } Problem Currently these types are hardcoded into the settings.py file in my django project. I want to keep these types configurable while not having them hardcoded into my settings file. They are used only for development purposes and do need to be changed frequently. I do not want to make them available to regular users of my site. Any ideas on how I could do this? I was thinking possibly some sort of CLI tool. -
block UI or MSG doesn't work in Safari
I have a Django project in which the input is a text and two dates. When I click on "See Metrics", validate() fires up which validates if all fields are filled. If the validation returns "true then I want to give a "Please wait" message to my users where Python script finds the results. I used MSG plugin (also the blockUI plugin previously). The functionality works fine in Chrome and Firefox but I am not able to get the desired results in safari. When I press "See Metrics" I don't see any message but after I press back button(of browser) then I see the message on the index page. Please help. Here is the code for my index page <meta charset="UTF-8" /> <title>ARM Datastream Usage Metrics Tool</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% load static %} <!-- All the style sheets --> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/metricsToolcss.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery.msg.css' %}" /> <!-- All the JS Libraries --> <script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script> <script type = "text/javascript" src = … -
How to assert django uses certain template in pytest
In the unittest style, I can test that a page uses a particular template by calling assertTemplateUsed. This is useful, for example, when Django inserts values through a template, so that I can't just test string equality. How should I write the equivalent statement in pytest? I've been looking in pytest-django but don't see how to do it. -
How to pass JWT token through header in react native to django rest api?
enter code hereI am passing token(already i known from console) in header as in below code and want data from that localhost after that user get authenticated but on my android emulator it showing error Cannot convert undefined or null to object Login.js componentDidMount() { return fetch('http://10.42.0.1:8000/stocks/', { method: "GET", headers: { 'Authorization': `Bearer ${"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwMzk0ODYyMH0.l4VLMLXcSZ7nOmKmjblLKFr0lTSpgYeFks_JeYiO7cU"}` } }) ... } In views.py class Stocks(APIView): permissions_classes = [IsAuthenticated] authentication_classes= (TokenAuthentication,) def get(self,request): stocks=stock.objects.all() serailizer=serial(stocks,many=True) return Response(serailizer.data) here the token is not reaching at the server and hence permission is not granted. we are using Django rest jwt token. Thank You -
User.objects.create() does nothing. (Django)
I have a view that should run User.objects.create() for the user registration. User.objects.create(name="request.POST['name']", username="request.POST['username']", password="request.POST['password']") It obviously passes the conditionals into this code because it runs the redirect I put after it. But When testing the registration, it just doesn't create a new entry in the database. What's wrong with it? -
django multi-tenancy and wildcard subdomains
I want to offer client.domain.com for every client on the site. In practice, client.domain.com is equivalent to www.domain.com/client/ (which I know how to handle in urls but isn't what I want). Can I use django-subdomains to allow this sort of wildcarding without defining SUBDOMAIN_URLCONFS since I don't want to try and enumerate for all clients. I'm currently using Apache. I don't want to create a new virtual host for each client as well. Is there a generic way to make client.mydomain.com work? Appreciate all pointers to executing #1 and #2. Thanks. -
How to reuse a Django template?
Currently, I have almost two exact same templates and they use the same Django form, but there is only 1 parameter that changes in these two forms which is the action method, that is, Django form class DropDownMenu(forms.Form): week = forms.ChoiceField(choices=[(x,x) for x in range(1,53)] year = forms.ChoiceField(choices=[(x,x) for x in range(2015,2030)] template 1 <form id="search_dates" method="POST" action="/tickets_per_day/"> <div class="row"> <div style="display:inline-block"> <h6>Select year</h6> <select name="select_year"> <option value={{form.year}}></option> </select> </div> <button type="submit">Search</button> </div> </form> template 2 <form id="search_dates" method="POST" action="/quantitative_analysis/"> <div class="row"> <div style="display:inline-block"> <h6>Select year</h6> <select name="select_year"> <option value={{form.year}}></option> </select> </div> <button type="submit">Search</button> </div> </form> The only thing that varies is the action method, so I would like to know if it is possible to re-use one template that varies only in the action method. If it is possible, can you help me with the code? I checked this question django - how to reuse a template for nearly identical models? but I am not using any model here with my templates. -
django templates Unclosed tag on line 10: 'if'. Looking for one of: endif
I am getting the following error message in my django template: Unclosed tag on line 10: 'if'. Looking for one of: endif. I use endif on line 20 to close the if category. if pages is closed on line 16. Not sure if it is a syntax issue? <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <div> {% if category %} {{ category.name }} <ul> {% if pages %} {% for page in pages %} <li> {{ page.title }} </li> {% endfor %} </ul> {% else %} <strong>No Pages</strong> {% endif %} {% else %} <strong>The specified category does not exist!</strong> <% endif %} </div> </body>