Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NameError name 'request' is not defined
got an error Django NameError name 'request' is not defined. my views.py class ShiftCreateView(CreateView): fields = ('name', 'timein', 'timeout', 'desc') model = models.Shift def form_valid(self, form): self.object = form.save(commit=False) self.object.timein = request.POST.get("timein", "") self.object.timeout = request.POST.get("timeout", "") self.object.save() return super(ModelFormMixin, self).form_valid(form) also, how can I modify the input?... example: input 07:21:34 change to 07:21:00 input 07:21 change to 07:21:00 wan't remove the second, also if second not inputted it will change to 00, for self.object.timein -
How to get recievers\senders adress? Gmail API
I'm trying to get user's email adress form the header. First I count how many emails with the label I need are there. Then I get their Id's and then I try to get metadata by message id and user id from googleapiclient import errors from quickstart import service def getTop(n): try: if (n == 1): label_ids = "INBOX" else: label_ids = "SENT" user_id = "me" topers = service.users().labels().get(userId = user_id,id = label_ids).execute() count = topers['messagesTotal'] topers = service.users().messages().list(userId = user_id, labelIds = label_ids).execute() arrId = [] for i in range(0,count): arrId.append(topers['messages'][i]['id'] ) print(arrId) msg_ids = [] for i in range(0,count): msg = service.users().messages().get(id = arrId[i],userId = user_id,format = "metadata",metadataHeaders = "To") msg_ids.append(msg) print(msg_ids) pass except errors.HttpError as error: print('An error occurred: %s' % error) First it returns message ids and then it should return adresses but in reality: https://ibb.co/hr0Mw7 -
How to run python script simutaneously when user input in Django REST api?
I am very new in Django REST API and Python. I have python script. and I created simple Django REST API for getting input from users. Now I want to do when user give input through Django REST API then after run my python script with it. so I want to integrate my python script with Django REST API. I tried to do googling but Not able to understand because in some forum they use subprocess and in some forum given REQUEST function. I am confuse and not able to understand. my view.py file as follows: from django.shortcuts import render from rest_framework import viewsets from . models import input_params from . serializers import input_paramsSerializer class inputViewSet(viewsets.ModelViewSet): queryset = input_params.objects.all() serializer_class = input_paramsSerializer url.py file from django.contrib import admin from django.conf.urls import url,include from base_search.views import inputViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'input',inputViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include(router.urls)) ] Question1 Now can anyone please tell me How can I connect my python script here? Question2: if I just connect my python script at endpoint so will it take automatically user input data from Django REST API and run my python script? If anyone have good example please let … -
ERROR: Uncaught SyntaxError: Unexpected token $
I receive the error: "Uncaught SyntaxError: Unexpected token %". Below is the component/templates/component/update.html template which is defined as: {% extends 'base.html' %} {% block content %} {% load static %} <script src="{% static 'component/js/component.js' %}"></script> <h2>Create new component</h2> {% include 'snippets/form-snippet.html' with form=form %} {% endblock %} I have the script saved at component/static/component/js/component.js. The file is found since in the console.log i can read: "GIVE ME SOME LOG". However I receive the error: "Uncaught SyntaxError: Unexpected token %". Apperently jQuery is not found but how to fix this? The component.js file is defined as follows: console.log("GIVE ME SOME LOG") $(document).ready(function(){ hideShow() }) $('#id_component_type').click(function(){ hideShow() }); function hideShow(){ if(document.getElementById('id_component_type').options[document.getElementById('id_component_type').selectedIndex].value == "k_v") { $('#id_length').parents('p:first').hide(); $('#id_k_v').parents('p:first').show(); }else { $('#id_length').parents('p:first').show(); $('#id_k_v').parents('p:first').hide(); } } -
When I use `pip3 install --upgrade pip ` get error
I want to upgrade the pip: $ pip3 install --upgrade pip But I get the bellow error: Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) - skipping -
How to configure docker to work with django and postgres?
I have a django project that has a postgresql database. All works fine on my local end but when i tried to docker-compose up it throws an error like this Starting 71a52ffe37d1_locallibrary_db_1 ... done Starting locallibrary_web_1 ... done Attaching to 71a52ffe37d1_locallibrary_db_1, locallibrary_web_1 71a52ffe37d1_locallibrary_db_1 | 2018-05-08 13:11:51.451 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 71a52ffe37d1_locallibrary_db_1 | 2018-05-08 13:11:51.451 UTC [1] LOG: listening on IPv6 address "::", port 5432 71a52ffe37d1_locallibrary_db_1 | 2018-05-08 13:11:51.463 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 71a52ffe37d1_locallibrary_db_1 | 2018-05-08 13:11:51.630 UTC [21] LOG: database system was shut down at 2018-05-08 12:59:50 UTC 71a52ffe37d1_locallibrary_db_1 | 2018-05-08 13:11:51.636 UTC [1] LOG: database system is ready to accept connections web_1 | /usr/local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. web_1 | """) web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect web_1 | … -
What is best solutions for seo django?
I have a web app that is RESTful APIs. How can I increase my website SEO? What is best solutions? -
Django AppRegistryNotReady with MongoDB models and Sql models
I'm using Django 1.11 with MongoDB and Sql, in MongoDB I have a document with results and when I try to retrieve the results from SQL saved in the MongoDB references, the next error is thrown (in view.py file): Traceback (most recent call last): ... File "/home/user/test/venv/lib/python3.5/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Seems like a circular recursion originated in the models, but with a double checking does not seems like that. I also tried this: import django django.setup() But leads to an infinite bug -
Different querysets in one view
I am trying to make the standard blog post web application using Django. I have multiple models in one applications. I want to display at a few posts from all the models to create an index, for which I will need to have multiple queryset inside my view for each model, which I don't know how to do. blog/models.py class topicone(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() def __str__(self): return self.title class topictwo(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() def __str__(self): return self.title class topicthree(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() def __str__(self): return self.title blog/urls.py urlpatterns = [ path('', views.indeview.as_view(), name="indexview"), path('<int:pk>', DetailView.as_view( model = topicone, template_name = "blogs/topicone.html" )), ] blog/views.py class indeview(ListView): model = topicone template_name = "tutorials/index.html" def get_queryset(self): return pythontuts.objects.all() views.py is quite useless as I am only using one model here. I tried writing a standalone view that didn't inherit from any other generic view so I could just create different contexts and pass multiple dictionaries in a view but that didn't seem to work. Here's how I tried to work that out blogone = topicone.objects.all() blogdict = { 'id': blogone } blogtwo = topictwo.objects.all() blog2dict = {'id': blogtwo} return render (request, 'blog/index.html', blogdict, … -
What is the preferred way to handle singular global variables for a django project
I am creating a django website and there are a few global variables that should be configurable by the owner through the admin interface. Some examples of these variables are a path to a document (resume, portfolio, ...), email address, social media links... These variables are unique (only 1 resume, 1 link to instagram...). Creating a model specifically for them seems a bit overkill, because there will only ever be 1 entry in the table corresponding to that model. I know there are a few apps that provide this type of functionality, but I was wondering how this can or should be done in vanilla django? -
Filter portfolio data from tab with jquery
Hi I have buy a Bootstrap theme but I can't show filtered data in different tabs from jquery. HTML <h4 class="text-center no-mb">Categories</h4> <ul class="nav nav-tabs nav-tabs-transparent indicator- primary nav-tabs-full nav-tabs-5" role="tablist"> <li class="nav-item"> <a class="nav-link active withoutripple no-pl no-pr filter" id="all" data-filter="all" href="#cat" aria-controls="cat" role="tab" data-toggle="tab">All</a> </li> <li class="nav-item"> <a class="nav-link withoutripple no-pl no-pr filter" data-filter=".category-1" href="#cat1" aria-controls="cat1" role="tab" data- toggle="tab">Filter1</a> </li> <li class="nav-item"> <a class="nav-link withoutripple no-pl no-pr filter" id="#cat2" data-filter=".category-2" href="#cat2" aria-controls="cat2" role="tab" data-toggle="tab">Filter 2</a> </li> <li class="nav-item"> <a class="nav-link withoutripple no-pl no-pr filter" data-filter=".category-3" href="#cat3" aria-controls="cat3" role="tab" data- toggle="tab">Filter3</a> </li> <li class="nav-item"> <a class="nav-link withoutripple no-pl no-pr filter" data-filter=".category-4" href="#cat4" aria-controls="cat4" role="tab" data- toggle="tab">Filter4</a> </li> </ul> JQUERY $(function() { var hash = window.location.hash; // take the www.example.com/#cat2 from home page $("ul.nav-tabs li").removeClass("active"); console.log(hash) var activeTab = $('ul.nav-tabs li a[href="' + hash + '"]'); console.log(activeTab); // activeTab.tab('show') -> error: "tab is not a function" activeTab.click(); activeTab.show(); activeTab.addClass("active"); }); The result is that the tab label is active but filter doesn't show filtered items but all the items. How can I solve? -
python __init__() missing 1 required positional argument: 'id' error tablib
I'm using Django 1.10, python 3.5.3 We are importing excel files using tablib package. Up until now everything worked fine for xls and xlsx. The Excel file was changed and added a data validation on a specific cell. I'm note sure if that's the reason, but now when trying to load the file I'm getting __init__() missing 1 required positional argument: 'id' This is the specific line of load: Dataset.load(request.data['file'].read(), 'xlsx') Seems like the error arrives from 'serialisable.py' -> from_tree() in 'openpyxl' package -
Django rest framework (DRF): Get the form as JSON
I am trying to Use Django rest frame work api end points. I am using reactjs as my frontend. I want to create an api end point which will get all the data required to create a user signup form but in JSON format. the following is my user signup form: class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ("email",) I want the output like below: { "title": "MyUserCreationForm", "non_field_errors": [], "label_suffix": ":", "is_bound": false, "prefix": null, "fields": { "email": { "title": "EmailField", "required": true, "label": "Email address", "initial": null, "help_text": "Please Enter valid Email Address", "error_messages": { "required": "This field is required." }, "widget": { "title": "TextInput", "is_hidden": false, "needs_multipart_form": false, "is_localized": false, "is_required": true, "attrs": { "maxlength": "254", "autofocus": true }, "input_type": "text" }, "max_length": 254, "min_length": null }, "password1": { "title": "CharField", "required": true, "label": "Password", "initial": null, "help_text": "<ul><li>Your password can&#39;t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can&#39;t be a commonly used password.</li><li>Your password can&#39;t be entirely numeric.</li></ul>", "error_messages": { "required": "This field is required." }, "widget": { "title": "PasswordInput", "is_hidden": false, "needs_multipart_form": false, "is_localized": false, "is_required": true, "attrs": {}, "input_type": "password" }, "max_length": null, … -
Django model aggregate sum and count at same time
So I have a query like SELECT sum(project_shares) as shares, count(*) as count FROM vv_projects Is there any syntax like below in django 2.0 Projects.objects.aggregrate(Sum('project_shares'),Count('*')) and output like {'project_shares_sum':9,'count':8} In django 2.0 count is used aggregate foreign key references so I am confused. If not I have add another orm query line to get the count. -
(Django) Running asynchronous server task continously in the background
I want to let a class run on my server, which contains a connected bluetooth socket and continously checks for incoming data, which can then by interpreted. In principle the class structure would look like this: Interpreter: -> connect (initializes the class and starts the loop) -> loop (runs continously in the background) -> disconnect (stops the loop) This class should be initiated at some point and then run continously in the background, from time to time a http request would perhaps need data from the attributes of the class, but it should run on its own. I don't know how to accomplish this and don't want to get a description on how to do it, but would like to know where I should start, like how this kind of process is called. -
django many_to_many field delet
I have two django models which I want to connect using a many to many relationship. See the below example: class A(models.Model): name = models.CharField(max_length=1000, unique=True) class B(models.Model): name = models.CharField(max_length=1000, unique=True) aa = models.ManyToManyField(A, related_name='bs', blank=True, null=True) What I am trying to figure out is what happens if I delete a record of A or of B? What I want to have happen is that the relations in the M2M are deleted, but the other object stays intact. Say an row in A is deleted, then the related rows in B should remain, only the connection through the m2m relationship should be deleted. I can't find it in the django documentation. -
Connect to Couchdb using Django rest framework 3.6.2 and python 3
Hi i am working on Django Rest framewrok. i have created few apis and storing data in sql lite. now i want to save data to couch db from the rest api calls basically crud application. i am not getting how to connect to couch db via django rest framework. please help me im stuck here not getting how to do crud in couch db using django rest api. Below is one of the api written in django for adding accconts. i want ton save this data in couch db. models.py class BankAccount(models.Model): SAVINGS = 'saving' CURRENT = 'current' TYPE = ( (SAVINGS,'Saving'), (CURRENT,'Current') ) type = models.CharField(max_length=20, choices=TYPE, default=SAVINGS) bank_name = models.CharField(max_length=200) account_number = models.IntegerField() balance = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): """returns the model as string.""" return self.bank_name def __str__(self): """returns the model as string.""" return self.type serializers.py class BankAccountSerializer(serializers.ModelSerializer): class Meta: model = BankAccount fields = '__all__' views.py class BankAccountView(APIView): def get_object(self, pk): try: return BankAccount.objects.get(pk=pk) except BankAccount.DoesNotExist: raise Http404 def get(self, request, format=None): accounts = BankAccount.objects.all() serializer = BankAccountSerializer(accounts, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = BankAccountSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, format=None): data = json.loads(request.body) pk = … -
How to start celery task when django finished startup
I've celery configuration with django. And i'm looking for a way to run task which is expected to be executed during the whole cycle of running application. Is this the case i use celery worker or there are some other options to start such long running task in parallel with django server? Also i want to be able to access database from task and monitor it with supervisord in case it fails to restart it. -
Efficiently save the same time for many objects (postgresql and generally)
I have a Django project with many objects (each of them has a row in a Postgresql table). Bulks of objects have the same time value. I wonder whether it is good to use same a time field for each of the many data objects (although hundreds of them has the same value), or to create a "context" object that will save the time, and to keep for each object a reference to (in the table - the id of) a context object. Working with ids (rather than times) is faster, although with context objects two queries should be used (one for the context, and the second for data objects with the reference to the context). Assuming that saving the same time many times is a waste of space (is it?), the second option is better. I'm not a DB expert, and will be glad to hear which option is better? What else should be considered? -
Change the python2.7 package to my required python3.5 package when use virtialenv.
When I create the virtualenv, if I do not add the --no-site-packages as param: virtualenv venv I can get the packages, in the venv/lib/ there are a python2.7 package: python2.7 under the python2.7 there are site-packages. But, I have a requirement, I want copy the python3.5 to the venv/lib/ how can I do this? -
Django application behaves strangely, sometimes works, sometimes doesn't
We are building a school information system using Python/Django. The production server runs Ubuntu, Apache2 with mod_wsgi. Recently strange things happen to our server. When we test our code locally everything works well. But after deployment the application returns sometimes 'Page not found' or 'Division by zero' errors. Why is this happen, from attack or server configuration, please help us! -
How to implement a simple checkbox in Django
I have Django = 1.11 In models.py class LabelTask(models.Model): name = models.CharField(max_length=1000) def __str__(self): return self.name And I have class Task(models.Model) in models.py. In class Task I've label_task = models.ManyToManyField(LabelTask) label_task - it, for example, round, red and heavy - that is, it may be one choice and not one or all choices. And I do not understand what I need to write in forms.py, what widget I need and how it looks. Thank you. -
Unittest sensitive_post_parameters decorator in django view
I have a view to create new users in my django project. I am applying the @sensitive_post_parameters decorator to that view to make sure the password isn't logged if there is an unhandled exception or something like that (as indicated in the comments in the source code https://docs.djangoproject.com/en/2.0/_modules/django/views/decorators/debug/). When I proceed to test the view, I would like to make sure that this protection of the sensitive information is still in place (that I didn't delete the decorator to the function by mistake or something). I am aware, since the decorator is applied to my function, I can't test it directly from the view tests. But, for example, with the @login_required decorator, I can test its effects with assertRedirects (as explained here How to test if a view is decorated with "login_required" (Django)). I have been searching for a way to do that, but I can't find one that works. I thought of something like this: def test_senstive_post_parameters(self): request = RequestFactory().post('create_user', data={}) my_sensitive_parameters = ['password'] self.assertEqual( request.sensitive_post_parameters, my_senstive_parameters ) but that gives me an AttributeError: 'WSGIRequest' object has no attribute 'sensitive_post_parameters' Any help would be appreciated. Even it is telling me I shouldn't be attempting to test this, though I … -
class has no attributed user
when i try to create a post, it will show me this error Exception Type: AttributeError at /home/ Exception Value: 'HomeView' object has no attribute 'user' and my view.py is class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) @login_required def post(self, request): if request.method == 'POST': form = HomeForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('home:home') else: return redirect(reverse('home:home')) else: form = HomeForm() args = {'form': form} return render(request, self.template_name, args) please help I've been missing for a long time. using this language. then help me with this error -
Can not find the virtualenv command after pip3 installed
I use the pip3 install the virtualenv in my CentOS7.2: [root@www abc]# pip3 install virtualenv Requirement already satisfied: virtualenv in /usr/local/Python3/lib/python3.5/site-packages (15.1.0) [root@www abc]# virtualenv --no-site-packages venv -bash: virtualenv: do not find the command But I can not use it, there do not find the command.