Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Constantly need to reset django local settings module
I have made two settings files, one for local testing and one for production (heroku). Every time I pull and start working locally I need to run the following two commands for it to work: export DJANGO_SETTINGS_MODULE= DJANGO_SETTINGS_MODULE=projectName.settings_local Without doing so I get the error that the local settings module cannot be found. This error appeared after I tried to have both settings files in a settings folder, which I did not get to work so I put them back in the original place. Does anyone have an idea how I can fix this? -
Get vimeo video info (Python) --- Different responses on Developers API and POSTMAN
When I make authorized call to Developer API to get video info for a specific video then I get response: { ... "files": [ ... ... { "quality": "hd", "type": "video/mp4", "width": 1280, "height": 720, "link": "LINK", "created_time": "Time", "fps": value, "size": size, "md5": "value", "link_secure": "link_source" }, ... ... ], "download": [ ... ... { "quality": "source", "type": "source", "width": 1920, "height": 1080, "expires": "time", "link": "link", "created_time": "time", "fps": value, "size": size, "md5": "value" }, ... ... ] } I am using Pyvimeo==0.3.2 and Pyvimeo==1.0.0 for Vimeo. But when I hit "https://api.vimeo.com/videos/{vimeo_id}" (with Client_id and Authorization) from my server or from POSTMAN then I get only: { ... "download": [ ... { "quality": "source", "type": "source", "width": 1920, "height": 1080, "expires": "time", "link": "link", "created_time": "time", "fps": value, "size": size, "md5": "value" }, ... ] ... } There is not key "files" in API response. Why I am not getting "files" key in video response ? There is no any such update in API docs. -
run python script for xml validation in admin.py
Please help, how to run python script in admin.py in django I have xml validation script to validation xml and xsd file, and I want to run the script in admin.py with action in admin.py -
django.db.utils.ProgrammingError: (1146, "Table 'customer.theapp_post' doesn't exist")
I used two databases:one is default sqlite3 and another mysql. I just created a model Post under models.py under app named 'theapp'. I just also created routers.py under the app. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'customer': { 'NAME': 'customer', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': 'haha', } } This is my routers.py in app called 'theapp' class CustomerRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'theapp': return 'customer' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'theapp': return 'customer' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ if obj1._meta.app_label == 'theapp' or \ obj2._meta.app_label == 'theapp': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'theapp': return db == 'customer' return None This is my models.py under the app named 'theapps' from django.db import models from … -
Django redux form customisation
how can I add placeholder to django redux form? I have no app in my project, only using redux authentication.I want to remove all the labels and instructions and just palceholder I want -
ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt'
I create a project use django, and the upload it to heroku. It can run successfully in local environment, and functions can also work well. I upload successfully without any problems, but when I visit it in heroku(https://APP_NAME.herokuapp.com/), it have some issues like this: InvalidTemplateLibrary at / Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt' Request Method: GET Request URL: https://mighty-harbor-16554.herokuapp.com/ Django Version: 2.0.2 Exception Type: InvalidTemplateLibrary Exception Value: Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt' Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py in get_package_libraries, line 125 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Sun, 25 Feb 2018 02:19:09 +0000 I tried to use django-bootstrap4, but it also have deployment problems with django-bootstrap3. How can I do? Thanks a lot. -
Django: can I omit ".save(commit=False)" in this case?
Here's the snippet from a view function for ModelForm in Django: if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() Would substituting this code with the following one have the same effect?: if form.is_valid(): form.topic = topic form.save() If so, what is the use of creating new_entry object like in the first example? -
Django call url from another application in same project
Sorry for my english. I have app call_from_this and app i_use_this in same project. I need in application i_use_this form view call url from application call_from_this. For example: simple example structure project: -call_from_this --urls --views --.... -i_use_this --urls --views --... in my app i_use_this Views: class TestCall(generics.GenericAPIView): def get(self, request): url = 'http://' + request.get_host() '/test_call/' response = requests.get(url=url) return HttpResponse(response, content_type='application/json') in my app call_from_this urls urlpatterns = [ re_path('test_call/', cache_page(CACHE_TIME_UPDATE(views.BalanceReport.as_view())), ] its work, but i have problem: I use cache, and if i call same url from my app i_use_this Views and then from app call_from_this Views create two chache, not one. -
Unexpected chars in the html side
My html is like this. <div style="display:none" maxpostid="{{maxpostid}}" maxcommentid="{{maxcommentid}}"></div> and passing the context like below. context = {'maxpostid':postid, 'maxcommentid': commentid} return render(request, 'sample.html', context) It shows output like below. <div style="display:none" maxpostid="{u&#39;id__max&#39;: 14}" maxcommentid="{u&#39;id__max&#39;: 42}"></div> There are some unwanted chars coming, Am I doing anything wrong? -
404 when redirected to redirect_uri with a state and code
I am trying to build a django application that will use the YouTube Data API v3. Part of code in views.py YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope=YOUTUBE_READONLY_SCOPE) FLOW.redirect_uri = "http://127.0.0.1:8000/accounts/google/login/callback/" @login_required def index(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: I am being redirected to this. After logging in. It redirects me to - I am following this link from google. I have all the values set in Google Cloud Platform as well. Any sample code will be helpful. -
Delete objects with checkboxes
I want to delete objects in a list which are marked with checkboxes. I have read through other post and tried to understand it, but I seem to be missing something. views.py def phase1(request, id): ... if request.POST.get('delete'): Descriptor.objects.filter(id__in=request.POST.getlist('item')).delete() return render(request, 'szenario/phase1.html', context) template phase1.html <ul> {% for Descriptor in projectdescriptors %} <li> <tr class="item"> <input type="checkbox" name="item" value="{{Descriptor.name}}"> </tr> {{Descriptor.name}} </li> {% endfor %} <form method="post"> {% csrf_token %} <h1><input type="submit" name="delete" value="Delete selected descriptors" /></h1> </form> </ul Pressing the button reloads the page, but the selected entries are still there. What am i doing wrong? Any help is appreciated. Note: I aim on using AJAX and signals as soon as i understand how to use them, but for now i just wanted to make a simple solution to focus on other tasks. -
how to add markers and center map in signup form django-map-widget
using django-map-widget to render a google map so that user can pick his location on the map. it works fine, but... I would like to trigger the map in two ways (dynamically via javascript): 1. trigger to re-center map on x,y 2. trigger to add a marker to map on x,y I tried so many ways, but i can't solve this. Here are just a few of my attempts: var locationRio = {lat: -22.915, lng: -43.197}; var marker = new google.maps.Marker({ position: locationRio, title: 'Hello World!' }); marker.setMap($("#location-map-elem").map); and var locationRio = {lat: -22.915, lng: -43.197}; var marker = new google.maps.Marker({ position: locationRio, map: $("#location-map-elem").map, title: 'Hello World!' }); You can see and play with the form here Thanks in advance :) -
Maintain git with different settings.py for development and production
I have a Bitbucket repo which interacts with my remote server to push production code for my live Django website. However I want to interact with my Bitbucket repo from my local desktop repo - where I want to test development code before pushing to my Bitbucket which is my production. The only file I don't want to push from my local repo is settings.py as it's different for production and development. I can't add it to .gitignore as I still need it to be pushed from my bitbucket repo to my remote server. Any idea what I should do? -
importing the csv file to database in django
I am trying to update my model using the CSV file. In my model I am having one field Foreign key I have to update only that i got few errors like value error How should I update my Foreign key using CSV import Thanks -
How to filter for my requirement?
I have a requirement: in my filter, I want to filter like bellow: messages = Message.objects.filter(to_user=user or from_user=user).all() I mean if the to_user==user or from_user==user all be queried out. I found the bellow related post: How to use OR filter condition in queryset? But this is one params, you see this is different between my requirement scenario. -
How to properly submit only one form in table of ModelForms in Django?
I need to create a table of forms for creating and updating users based on my custom User model. It must look something like this: Form is presented as particular row in table. Save button saves submits form, Delete removes form and the model instance from database, Add button appends new blank form to end of <tbody> but to save new form we need to click Save button. Now I'm stuck and don't know how to properly implement logic above. I need each form to be updated and submitted independently. I looked up for solutions based on ModelFormSet but it submits all forms and does not allow to update only one particular row of data. How we can create prepopulated ModelFormSet where each row of form data can be submitted regardless of other forms in table? Like this: <form action="" method="post"> <tr> <td>1</td> <td> <input type="text" name="username" value="admin" maxlength="255" class="login-input" id="id_username" /></td> <td> <input type="text" name="password" value="" maxlength="128" class="password-input" id="id_password" /></td> <td> <input type="text" name="email" maxlength="255" class="email-input" id="id_email" /></td> <td> <input type="checkbox" name="active" class="checkbox-input" id="id_active" checked /></td> <td> <input type="checkbox" name="staff" class="checkbox-input" id="id_staff" checked /></td> <td> <input type="checkbox" name="reboot_field" class="checkbox-input" id="id_reboot_field" checked /></td> <td><button type="submit" form="form1">Save</button></td> <td><button form="form1" >Delete</button></td> <tr> … -
Calling Zapier trigger from Django Code
Is there any way I can call the "Zapier trigger" from my Django Code, Basically, I am having a Django form where the user will enter several email-id and when the user clicks on send button then I want to send this form data to Zapier in order to do the next action like writing in google spreadsheet or sending email to everyone. -
Django bulk_create not working
I am trying to pass a dict to bulk_create, but it is not working. If someone has used this prior, I would appreciate advice. Django Model: class Servers(models.Model): name = models.CharField(('name'), max_length=128) location = models.OneToOneField('locations.Location', on_delete=models.CASCADE) ip_address = models.CharField(('ip_address'), max_length=128) date = models.DateField(auto_now=True) A print of my dict: { 'Florida': { 'name' : 'server-a', 'location':'Miami', 'ip_address':'172.16.16.1', }, 'Colorado': { 'name' : 'server-b', 'location':'Denver', 'ip_address':'172.16.24.1', }, My function: def add_to_db(data_dict): Servers.objects.bulk_create(Servers(**d) for d in data_dict.values()) My error: ValueError: Cannot assign "'Florida'": "Server.location" must be a "Location" instance. -
Clean email field when new user is registering in Django?
As I know, standard new user process registration is validate email field only for exists and equals for E-mail Schemas. But users may be write e-mail address like this: JOHN_DOE@MAIL.COM (via Caps Lock) and save it to DB. It's would be dangerous, because other user can register account for these email, but in lowercase: john_doe@mail.com or similar, but still that email address! So, question now is "how to clean up email address when user is registering?". My ideas: set email to lowercase before save to DB check if it exist/unique in DB (in lowercase view, of course) only after, send to user success of error messages -
How do I filter and sum up values of a field with that is inputted multiple times in Django using querysets
I am using query sets with django_rest framework and I'm trying to filter deductions according to employee_id then sum them up per employee_id so far I have this : class DeductionView(APIView): queryset = Deduction.objects.all() serializer_class = DeductionSerializer def get(self, request): get_deduction = Deduction.objects.filter(employee_id) .values(' deduct_inst_amount').annotate(net_deduction=Sum('deduct_inst_amount')) -
Django Rest FrameWork Secure Open API
I am developing a Django Rest API which is being used by some apps from mobile or web. The communication between APP and webserver must be in REST and the APIs must be private, and only my apps should able to call them for successful results i.e. other people shouldn't be able to send requests from browsers or such. My problem is that there are no user ids and passwords in my app so the solution is either using HMAC (as stated in this post) or using Django-Rest-Framework-API-Key. my problem is I have no experience in implementing HMAC myself and I can't find a library or package for Django to do so. is there such thing? and I am not sure if Django-Rest-Framework-API-Key will do what I want? thanks in advance. -
build client to client to client chat through server
I'm going to build a Chat with Django (i need this for user profile) that i can access with android and iOS and web platforms. this tutorial could help me a little to understand Socket server, but this is just for a room and uses multi-threading (i have no idea if it makes trouble for many users because when i'm buying VPS, they say that, it handles just one thread! i have no idea what does it mean!) and he doesn't explain how to make client to client chat! actually i had an idea (send user destination id for the server and server can find the socket on the clients dict and sends the message to him) but i think its not safe! i need the best practice -
Ean-128 python barcode generator
Is there any python library to generate ean128 barcode. I tried 'python-barcode' , but in that library there is no option for ean128. -
Getting 502 error when I try to send email, server setup by django, postgres, nginx, gunicorn
I am following this tutorial from digital ocean How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04 Everything is working fine except when I try to send email using gmail it throws 502 bad gateway. nginx log file shows 94 upstream prematurely closed connection while reading response header from upstream Any help will be appreciated. -
How to change LetsEncrypt certbot domain?
I'm running my Django application on Digital Ocean with Ubuntu 16.04/Nginx/Gunicorn. I issued a (SSL?) certificate by running the following command: sudo certbot --authenticator webroot --webroot-path /home/user/app --installer nginx -d aaa.com -d www.aaa.com however I now want to change my domain from aaa.com to bbb.com. How do I keep my certificate for my new domain? When I ran the command to issue the certificate, I assume it created various files such as the directory .well-known - and also added code in my Nginx conf. So do I simply run the same command again, with the new domain in? sudo certbot --authenticator webroot --webroot-path /home/user/app --installer nginx -d bbb.com -d www.bbb.com or do I just change the current code and replace it with the new domain? E.g. my Nginx conf looks like this: ssl_certificate /etc/letsencrypt/live/aaa.com/fullchain.pem; # managed by Ce$ ssl_certificate_key /etc/letsencrypt/live/aaa.com/privkey.pem; # managed by $ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot I've already changed: server { listen 80; server_name 172.128.67.232 bbb.com www.bbb.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/app; } to my new domain bbb.com. Advice appreciated.