Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django LogoutView only to logout and redirect?
I tried to use Django LogouView just to redirect to the root url, adding next_page = "/", but instead, when the logout url is accessed, it tries to render the default template and says the template was not found (because I did not, since I do not intend to use it). I solved my problem with a view that uses logout and redirect functions, but I wanted to understand why LogoutView does not behave the way it wants. -
`HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer
I am trying to add url hyperlink, but I don't know why its not working, I have searched this in google but I did not get the solution. I am new to Django. These are my codes, I tried doing this using django-rest-framework docs. But it gives me error like this every time. HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer. serializers.py from rest_framework import serializers from posts.models import Post,Category class PostListSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="post-detail") class Meta: model = Post fields = ('url','id','title', 'body','category' ,'updated', 'timestamp') class PostDetailSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id','title', 'body','category' ,'updated', 'timestamp') class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id','title', 'updated_at', 'created_at') models.py from django.db import models # Create your models here. class Category(models.Model): title = models.CharField(max_length = 120, verbose_name="Title" ) updated_at = models.DateTimeField(auto_now_add=True, verbose_name="Updated at") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=120) body = models.TextField() category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def __str__(self): return self.title urls.py from django.urls import path, include from posts.api.views … -
django first in sequence for manytomanyfield
person.groups.add(group1)#->I want to get this as first person.groups.add(group2) person.groups.add(group3) When I iterate groups, it returns predictable result. for group in person.groups.all(): #->group1 comes first etc... When I use .first() on m2m field, it returns unpredictable result. When I use by index ie: [0], it returns predictable result. person.groups.all()[0]#->correct predictable result What is the reason for this? -
Override django admin authentication
I'm using django 2.1.5. I want to override the django admin authentication process, the objective is to allow user with is_staff=False to be able to login. So, i'm trying to override the AdminSite and followed this docs (https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#overriding-default-admin-site). This is the code so far: my_app/forms.py from django.contrib.admin.forms import AdminAuthenticationForm class CustomAdminAuthenticationForm(AdminAuthenticationForm): def confirm_login_allowed(self, user): super().confirm_login_allowed(user) # i removed is_staff checking here my_app/admin.py class MyAdminSite(admin.AdminSite): login_form = CustomAdminAuthenticationForm def has_permission(self, request): return request.user.is_active # i also removed request.user.is_staff here my_app/apps.py from django.contrib.admin.apps import AdminConfig class MyAdminConfig(AdminConfig): default_site = 'my_app.admin.MyAdminSite' root/settings.py INSTALLED_APPS = [ 'my_app.apps.MyAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app', ] When i tried to runserver, there is an error: ImportError: Module "my_app.admin" does not define a "MyAdminSite" attribute/class I think i have point the default_site in my_app/apps.py correctly. How can i fix this? Is there any other way to complete my objective other than overriding the AdminSite? Thank you. -
Apache Error reading from remote server - Uploading large file
I'am trying to send large file ( ~ 300Mo ) between a node server and a django server. File under 300Mo is send well, but when it's more than 300Mo, this error happening : Proxy Error The proxy server received an invalid response from an upstream server. The proxy server could not handle the request POST /dashboard/patient/fileAdd. Reason: Error reading from remote server here is my httpd.conf, i already tried many command : <VirtualHost ***URL***> ProxyPreserveHost On ProxyPass "/" "http://localhost:23000/" connectiontimeout=1600 acquire=3000 retry=0 timeout$ ProxyPassReverse "/" "http://localhost:23000/" SetEnv proxy-sendchunks 1 SetEnv proxy-initial-not-pooled ProxyBadHeader Ignore ProxyTimeout 1600 LimitRequestBody 0 -
How to set file field to None: attribute has no file associated with it
I have a model that is supposed to keep a reference to a file with an ability to be expired such that the file is removed and the corresponding field must be turn to None: class FileRecord(models.Model): file = models.FileField(upload_to='files', null=True, blank=True) In my code I try to set file to None removing the file before: record.file.delete(save=False) record.file = None record.save() print(record) # error happens here! That leads to the error: ValueError: The 'file' attribute has no file associated with it. How to set the field file to None and to save it correctly? I have Django version 2.1.7 and Python version 3.6. -
embed an external video in a popup
I'm creating a website with django. I have three videos for each product that I want to show in a popup lightbox that I have created. The videos are hosted in a video hosting website that gives me the following code for embedding their videos: <div id="15508242266959758"> <script type="text/JavaScript" src="https://www.aparat.com/embed/bgUL5?data[rnddiv]=15508242266959758&data[responsive]=yes"> </script> </div> Here is The code I have: <script> {% for course in course_list %} var {{course.id}}_lect = '{{ course.lecturar.teaserHTML|safe }}'; var {{course.id}}_course = '{{ course.teaserHTML|safe }}'; var {{course.id}}_sample = '{{ course.sampleLectureHTML|safe }}'; {% endfor %} function popitup(teaser){ $("#popup-content").prepend(teaser); } </script> Here is one of those buttons that should open the video: <button type="button" class="teaser-btn" id="popup_lect_{{course.id}}" onclick='popitup({{course.id}}_lect)'> Here is the html for popup: <div id="popup"> <div id="popup-content"> <button type="button" class="close"><strong>&times;</strong></button> </div> </div> And some script that I have for the popup: $(document).ready(function(){ $(".teaser-btn").click(function(){ $("#popup").fadeToggle(500); }); $(".close").click(function(){ $("#popup").hide(); $("#popup>div:first-child").remove(); }); }); </script> But clearly this doesn't work because I have </script> as an string inside an script tag which closes the tag. Here is what the UX should be: there are so many buttons in the page. each corresponding to a different video. when the user clicks on one of these buttons. a popup comes up and when the use clicks … -
Connecting Flutter with Python database
What documentation or examples are available for connecting a flutter app interface with a backend mySQL database built with Python (flask or Django)? -
where is the error in my ajax script that return NoneType to the views.py
i have ajax script that send selected option from a dropdown list to the django function using GET method, i am sending the data in json format the problem once i select an option from the dropdown list it display the below error: File "C:\Users\LT GM\Desktop\test2ForImportExport\test2\testpro\views.py", line 30, in getdetails answer = str(country_name[1:-1]) TypeError: 'NoneType' object is not subscriptable home2.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; alert(country_name); $.ajax({ type:"GET", url:'/getdetails', data:JSON.stringify(data), success:function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }, }); }); }); </script> </head> <body> <select name="selectcountries" id="selectcountries"> {% for item in countries %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </select> <select name ="selectcities" id="selectcities"> </select> <select name ="selectroads" id="selectroads"> </select> </body> </html> views.py def home2(request): countries = country.objects.all() print(countries) return render(request, 'home2.html',{'countries': countries}) def getdetails(request): if request.method == 'GET' and request.is_ajax(): country_name = request.GET.get('cnt', None) print ("ajax country_name ", country_name) result_set = [] all_cities = [] answer = str(country_name[1:-1]) print('answer = ' ,answer) selected_country = country.objects.get(name=answer) print ("selected country … -
Improperly Configured urls.py during Django deployment (Django 2.1)
This is my first time deploying Django. My app runs fine locally, but when I deploy, I get this error: ImproperlyConfigured at /admin/ The included URLconf module 'search.urls' from '/home/imeaytbc/myproject/search/urls.py' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. My urls.py file is exactly the same as the one run on my computer: from django.urls import path from . import views app_name = 'search' urlpatterns = [path('', views.query_search, name='query_search'), path('article/<int:ArticleID>/', views.article_detail, name='article_detail')] Is there anything I need to change in regards to deployment? All the changes I made to my files regarding deployment are about static and media file directories. What else do I need to change for deployment? As far as I am aware, I have uploaded all files to the hosting server and the app shouldn't be missing any file. -
How to use pytest `request.config` inside the django.test.TestCase class setUp function
I am using pytest in my django project. I used pytest.config previously to get conftest.py values into the setUp function but it is deprecated since version 4.1. In the docs they suggest to use request fixture to get configs but I couldn't find a proper way get configs inside to the TestCase class using request fixture. Following code sample is the working code which uses the pytest.config. Any way to get configs without getting PytestDeprecationWarning will be helpful. import pytest from django.conf import settings from django.test import TestCase from django.test.utils import override_settings @override_settings(USE_SUBDOMAIN=False, PRODUCTION_DOMAIN='example.com') class TestSample(TestCase): fixtures = ['test_data'] def setUp(self): url_base = '{scheme}://{domain}/docs/pip{{version}}'.format( scheme=pytest.config.option.url_scheme, domain=settings.PRODUCTION_DOMAIN, ) -
Django linkedin authentication programming error
When I try to authenticate with linkedin in my django app, it passes the first stage where it asks me to give permission to linkedin to access my data, but fails to authenticate after that and displays this error. I have searched through the net and I have not seen anything on WSGIRequest. -
Celery parse JSON output from subprocess
I have a celery periodic_task: @periodic_task(run_every=(crontab(minute='*/1')), name="Check BTC Deposit", ignore_result=True) def check_btc_deposit(): users = User.objects.all() for user in users: check_addr = subprocess.Popen(['electrum' + ' ' + 'getaddressbalance' + ' ' + user.acc_btc_addr], shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() print(check_addr) That checks for Bitcoin deposit and returns the following JSON output, each new date-line e.g. "[2019-02-22 14:52:00,441: WARNING/ForkPoolWorker-15]" is a address that has been checked: [2019-02-22 14:52:00,441: WARNING/ForkPoolWorker-15] { "confirmed": "0", "unconfirmed": "0" } [2019-02-22 14:52:00,806: WARNING/ForkPoolWorker-15] { "confirmed": "0.057917", "unconfirmed": "0" } now i want to save each change to the database for each user associated address. models.py: class UserDepositBTC(): user_addr = models.ForeignKey(User, on_delete=models.CASCADE) confirmed = models.IntegerField(default=0) unconfirmed = models.IntegerField(default=0) deposit_date = models.DateField(auto_now_add=True, null=True) How to accomplish this at the celery task? As you can imagine this is some kind of wrapper around electrum BTC wallet to create sub-wallets for each user from a MPK (Master-Public-Key). Thanks and BR -
Unable to handle websocket and xhr request simultaneously using Nginx+uwsgi+django
I'm trying to use Nginx+uwsgi+django to establish a website where one of the task needs websocket. The system works well in django server (python manage.py runserver). However, when I make it on the AWS using Nginx+uwsgi, sth goes wrong. Though I modify the settings of Nginx+uwsgi, I find that the server is unable to handle websocket and xhr request simultaneously The specific problems are as follows: 1) if I start uwsgi using "uwsgi --socket :8001 --module project.wsgi --http-websockets", the websocket is able to be established but the message in django's "request.websocket" is always none and the uwsgi log shows "warning: async call without async mode". 2) Next, I try to use async mode in uwsgi by "uwsgi --socket :8001 --module project.wsgi --http-websockets --async 10 --ugreen". In this case, the websocket works well but the other xhr requests are blocked and cannot be handled by the server until the websocket ends. For example, if one client is running the task with websocket, other clients cannot even log into the web. Could you help me with this problem? Thanks in advance! -
Django, CSS, dynamically displaying list of items
So decided to dip my toes in Django and CSS... I have a Django view that returns a list of data which I want to display one at a time on the html output. I have a working solution which: Loops through the list and generates all the divs and tables, only displaying the first ("display:block") and hides ("display:none") the rest. A javascript function is called to cycle over the list hiding the current and showing the next item. Though this actually works, it feels rather clunky. Part of this clunkyness originates from the fact that the data is scattered over a part of the structural CSS grid. This is the grid layout: .container { display: grid; width: 100%; height: 100%; grid-template-areas: "nav header header header" "nav thumbs foto_header right" "nav thumbs main right" "nav thumbs foto_footer right" "nav footer footer footer"; grid-template-columns: 200px 160px 800px 1fr; grid-template-rows: 40px 60px 1fr 1fr 80px; } .container > div { border: 1px dashed #888; } .nav { grid-area: nav; } .header { grid-area: header; } .thumbs { grid-area: thumbs; } .foto_header { grid-area: foto_header; } .right { grid-area: right; } .main { grid-area: main; } .foto_footer { grid-area: foto_footer; } .footer { … -
Storing an object with related model results in IntegrityError: null value violates not null constraint
I am having the following problem with using Django and Tastypie. Strangely for about a year or so the following worked flawlessly. Now when I am trying to edit the Car on an Owner and store the Owner I get the error: django.db.utils.IntegrityError: null value in column "car_id" violates not-null constraint DETAIL: Failing row contains (55, test, 53, null). I know that I can alter the field car on the model Wheel to nullable but I definitely want to keep this relation defined. Strangely when I changed the field to nullable for testing, the id gets set in my database. Then when I am doing another edit the database entry isn't updated but instead a new entry gets created. This entry again contains the right id but the old entry loses it and the field is blank. This is what table wheel looks like after editing it on the Car object two times: postgres=# TABLE wheel; id | value | wheel_type_id | car_id ---+-------+---------------+-------- 53 | abc | 53 | 54 | def | 53 | 11 (2 rows) Models: class Owner(models.Model): id = models.AutoField(primary_key=True) class Car(models.Model): owner = models.OneToOneField('Owner', null=True, related_name='car', on_delete=models.CASCADE) ready = models.BooleanField(default=False) class Wheel(models.Model): car = … -
Django admin with CMS functionality
The Django admin interface is pretty basic, useful for occasional administration only. Once dealing with larger numbers of more complex objects, it becomes unwieldy. To give one example, foreign objects by default appear in a small multi select box with their title only as the label. Many developers add the required admin functionality through their own forms, but these stand separate to the admin interface and often have to reinvent the wheel with the same CMS like behaviour each time. Are there any packages that extend the admin interface with rich functionality, without going over to a complete CMS solution like Django CMS? -
HTTPS protocol not working with django and nginx on ec2 instance
I have been trying to auto transfer all requests to https protocol using nginx in django in ec2 instance but i am unable to do so.. here is my nginx file.. please suggest me the problem. nginx file server{ listen 80: server_name priyamarya.com www.priyamarya.com; listen 443 ssl; listen [::]:443 ssl; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/project/aryapriyam/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/project/aryapriyam/project.sock; } } i have also added this in settings.py settings.py SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT =True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True i have also set my hostedzone A type record set to the alias provided by elb load balancer. i have tried a lot of things like returning the https://sitename , and creating a different server block for both protocols but than it starts a loop in between requests. this is why i am posting the code from which i initially started. i have searched a lot but nothing is helping in regards of nginx and django both, please help.. i want all my forms request also to go through https only. -
Apache2 shows different Django version?
I installed Django 2.1.7 and mod-wsgi for Python3 (Ubuntu 18.04 LTS). Afterwards I added following configuration parameters to the apache2.conf file of the apache2 server: WSGIScriptAlias / /var/www/html/mysite/mysite/wsgi.py WSGIPythonPath /var/www/html/mysite WSGIPythonHome /usr/ <Directory /var/www/html/mysite/> <Files wsgi.py> Require all granted </Files> </Directory> The mysite Django project is just a default sample project. When I am accessing www..com/test it returns following error message: ImportError at /admin cannot import name 'path' Request Method: GET Request URL: http://<sitename>.com/test Django Version: 1.11.11 Exception Type: ImportError Exception Value: cannot import name 'path' Exception Location: /var/www/html/mysite/mysite/urls.py in <module>, line 17 Python Executable: /usr/bin/python3 Python Version: 3.6.7 Python Path: ['/var/www/html/mysite', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] But if I execute " python3 -m django --version " it shows me the correct installed version (2.1.7). I also checked if maybe another (old) Django version is installed on the server but could not find anything. So why does Apache or Django says version 1.11.11 and what would the solution look like? -
How do I put my Django SQLite database contents into a Heroku PostGreSQL database?
I am totally new to hosting/deploying applications. After watching this video, he started a new database from scratch rather than converting his Django SQLite database. I have lots of data that I want on the deployed site so I'd like some advice as to how to do that with Django and Heroku. I have seen there are some SQLite -> PostGreSQL conversion questions on here but none seemed to show a step by step guide using Django and Heroku, only issues they're having. I just want to make sure I do it right. -
Django test folder structure
I am trying to follow best practices which I often find in GitHub repositories: I would like to have a /src and a /test folder at the top level in a project. (random example https://github.com/bitcoin/bitcoin). I am not sure how to configure Django to accept that though. In particular, Django is expecting tests to be inside the project folder, but ideally, these tests should be outside of /src/django_project and inside /test. Any suggestions are greatly appreciated. Thank you so much! project_root |-- src | |-- project_name | |-- app_name | | |-- views.py | | |-- serializers.py | | |-- etc... | |-- manage.py |-- test |-- project_name |-- test_feature1.py |-- test_feature2.py -
Vue.js - Redirect to user detail after form submit with a dinamically generated parameter
The backend was built with a Django REST api. The frontend uses VueJS. Basically, the system is an agenda of people and what I want to achieve is, after you submit the form to create a person, you will be redirected to this person details page. I understand that this should be pretty easy but I don't know how to obtain the ID of the person just created because it's automatically generated by Django. This is what I have: personNew.vue <template> <b-form @submit.prevent="onSubmit"> <b-form-group id="nameInput" label="Name" label-for="name"> <b-form-input id="nameInput" type="text" v-model="form.name" required ></b-form-input> </b-form-group> <b-form-group id="emailInput" label="Email" label-for="email"> <b-form-input id="emailInput" type="text" v-model="form.email" required ></b-form-input> </b-form-group> <b-button type="submit">Create</b-button> </b-form> </template> <script> import { setPerson } from '@/api' export default { name: 'PersonNew', data () { return { title: 'New Person', form: { name: '', email: '', }, } }, methods: { onSubmit: function () { setPerson(this.form) .then((response) => { this.$router.push('/') }) .catch(error => { console.log(error) }) } } </script> api.js export function setPerson (form) { return getApi() .then(function (api) { return api.post(`people/`, form) }) } I guess I need to do this.$router.push('/people/' + ID-OF-PERSON?) But how do I obtain this ID? -
How To Change Radio Button Value In django
BarChart LineChart ColumnChart -
Python check for confirmation(s) in a celery script
i currently integrating bitcoin payments into my shop, it's a little conecpt im writing on and i want to use electrum to work with my shop. therefor i'm generating a unique BTC addresses for each user to deposit onto. To make the deposit workflow complete i need to check for the confirmation onto a specific address like this: def check_btc_deposit(): users = User.objects.all() for user in users: check_addr = subprocess.Popen(['electrum' + ' ' + 'getaddressbalance' + ' ' + user.acc_btc_addr], shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() which return something like this: { "confirmed": "0.055", "unconfirmed": "0.11" } Now i want to save these information to my Database, how can i parse the json from the console output here? Thanks and BR :D -
Django + Ajax Post : 403 Forbidden after user login
I am having problem for ajax posts to my django ecommerce site after user login. The failing scenario is as follows: 1-) User comes to site and adds products to shopping cart without any problem. Adding product to cart is an ajax call and the code is as follows: function addItemToCart(item_pk, quantity) { var item_quantity; if (!quantity) { item_quantity = 1; } else { item_quantity = quantity; } $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Csrf-Token', csrftoken); } }); $.ajax({ type: 'POST', url: '/api/cart/add-item/', data: { item: item_pk, quantity: item_quantity } success: function(data, textStatus, jQxhr) { updateCart(); }, error: function(jqXhr, textStatus, errorThrown) { console.log(jqXhr, textStatus, errorThrown); } }); } The above code works perfectly and user can add several products to the cart. 2-) After that the user logs in to the site to make the payment, but before he make the payment he wanted to add another product to the cart, but the code fails. 3-) The error message is as follows: "CSRF Failed: CSRF token missing or incorrect." When I checked the request I see that the ajax call already set the csrf token. The only thing I figured out is that django has refreshed the token after user login. But …