Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SalesforceMalformedRequest Error while querying salesforce through Django
I am using simple-salesforce & django. I am performing simple query on Account object of Salesforce. sf1 = Salesforce(connection parameters) sf8 = sf1.query("SELECT Id FROM Account WHERE Name = testname") Here testname is variable which holds firstname + lastname combination. I am getting the below error. Exception Type: SalesforceMalformedRequest Exception Value:Malformed request https://cs90.salesforce.com/services/data/v38.0/query/?q=SELECT+Id+FROM+Account+WHERE+Name+%3D+testname. Response content: [{'message': '\nSELECT Id FROM Account WHERE Name = testname\n ^\nERROR at Row:1:Column:36\nBind variables only allowed in Apex code', 'errorCode': 'MALFORMED_QUERY'}] Any workaround possible? -
How to make HttpResponse print the new line?
def index(request): review = Review.objects.all() output = "\n".join([each_review.review_text for each_review in review]) return HttpResponse(output) The output which I get is "This book 1 is very great This book 2 is very great This book 3 is very great This book 4 is very great This book 5 is very great This something is very great" But it doesn't print the new line between them. How to make that happen just with HttpResponse? -
i have override the django Authuser with my model. now i want to change the password and not able to save the password in my new model
Here is my code models.py class ApplicationUser(models.Model): user_id = models.AutoField(primary_key=True) user_f_name = models.CharField(max_length=50, blank=True, null=True) usre_l_name = models.CharField(max_length=50, blank=True, null=True) user_parrent = models.IntegerField() isactive = models.IntegerField(db_column='isActive') # Field name made lowercase. user_designation = models.CharField(max_length=30, blank=True, null=True) user_skill = models.CharField(max_length=150, blank=True, null=True) user_doj = models.DateField(blank=True, null=True) user_login_name = models.CharField(max_length=50, blank=True, null=True, unique = True) user_login_password = models.CharField(max_length=50, blank=True, null=True) user_role = models.IntegerField(blank=True, null=True) profile_pitcher = models.CharField(max_length=200, blank=True, null=True) created_date = models.CharField(max_length=8, blank=True, null=True) user_last_updated = models.DateTimeField(blank=True, null=True) usertype = models.CharField(db_column='userType', max_length=50, blank=True, null=True) # Field name made lowercase. applicationmanagerid = models.IntegerField(db_column='applicationManagerID', blank=True, null=True) # Field name made lowercase. last_login = models.DateTimeField(blank=True, null=True) user_phone = models.CharField(max_length=50, blank=True, null=True) objects = UserManager() # LAST_LOGIN_FIELD = 'last_login_date' USERNAME_FIELD = 'user_login_name' REQUIRED_FIELDS = ('user',) class Meta: managed = False db_table = 'application_user' def is_authenticated(self): return True views.py def password_change(request,user_id): server1 = get_object_or_404(ApplicationUser, pk=user_id) if request.method == "POST": form = PasswordChangeForm(request.POST) if form.is_valid(): #try: #user1 = get_object_or_404(ApplicationUser, user_login_name = server1.user_login_name, user_login_password=form.cleaned_data['oldPassword']) user1 = ApplicationUser.objects.get(user_login_name = server1.user_login_name, user_login_password=form.cleaned_data['oldPassword']) print(form.cleaned_data['new_password']) if user1 is not None: user = ApplicationUser.objects.using('default').get(pk = user_id) #user.user_login_password ="prer" #user.set_password(form.cleaned_data['new_password']) user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' auth_login(request, user) variables = RequestContext(request, {'updatepassword':PasswordChangeForm,'context2': "Your Password has been updated"}) return render(request, 'authentication\change_password.html', variables) # except: # variables = RequestContext(request, … -
How to restore default permissions in django?
I deleted all permission, and I want to restore it. Is it possible? Before in admin.py I added: from django.contrib.auth.models import Permission admin.site.register(Permission) -
Multiple Service Workers for Django application
At Django website I have several applications. For each application I need separate ServiceWorker. Let's say, when user goes to https://mysite/app/1 sw1.js is loaded, when to https://mysite/app/2 sw2.js and so on. All the service workers files are located at Amazon S3 bucket. I can register service worker on the index page of each application in a normal way. However, the scope of the service worker is defined based on sw.js path which is placed in S3. To change the scope I have to either place the sw.js to the root of each application what is impossible or to return extended http header 'Service-Worker-Allowed' what is restricted by S3 One of the solution is probably to use CloudFront/S3 with Lambda@Edge to return correct header but it looks too complex. Is there any simpler solutions to define the correct scope of sw? -
Django - get dict from TextField
I want to store a dict in Django. a very basic solution would be this: class foo(models.Model): bar = models.TextField() fooInstance.bar = json.dumps(my_dict) but I wanted to be able to access it directly and not constantly use json, so I did the following: class foo(models.Model): _bar = models.TextField() @property def bar(self): import json return json.loads(self._bar) @bar.setter def bar(self, new_bar): import json self._bar = json.dumps(new_bar) fooInstance.bar = my_dict and this works for the most part, only that I can't do one thing: fooInstance.bar['key'] = 'value' this expression goes through, no error. but the value is not being set. does anybody has any ideas on how this could be done? Any help is appreciated. -
Django How to add a logout successful message using the django.contrib.auth?
I am not using all-auth I am using the standard authentication system and url's provided by django.contrib.auth. I have also ensured that when logging out the user is automatically redirected to the login page LOGOUT_REDIRECT_URL = "login" I would like to add a message so the user knows they have been logged out like: from django.contrib import messages messages.add_message(request, messages.INFO, 'You have been logged out.') Would I be able to achieve this without making my own view to logout. Could I use signals? -
Django all-auth login redirect URL
I'm using django-allauth to create google login. At present I'm using the following in my settings.py LOGIN_REDIRECT_URL = /relative/path/ Even though my website is working on https, but the google login redirects it to http. What am I missing here? It works fine when I write the complete path in LOGIN_REDIRECT_URL. -
Why is having '/' gives Page not found (404) error
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$/',index), ] why does url(r'^$/',index), give page not found error(?) but if I remove / then it works fine. But same issue is not present for admin. -
Django issue : UnicodeEncodeError
I'm getting this common error in my code : Exception Type: UnicodeEncodeError Exception Value:'ascii' codec can't encode character u'\xe9' in position 6: ordinal not in range(128) Why ? Because I'm handling firstnames with french accents. This is my code : if 'rechercheGED' in request.GET: query_social_number = request.GET.get('q1social') sort_params = {} Individu_Recherche.set_if_not_none(sort_params, 'NumeroIdentification__iexact', query_social_number) query_lastname_list = Individu_Recherche.Recherche_Get(Individu, sort_params) lastname = query_lastname_list.Nom firstname = query_lastname_list.Prenom NIU = query_lastname_list.NumeroIdentification title = str(lastname + "_" + firstname + "_" + NIU) The issue comes from : firstname = query_lastname_list.Prenom Because in my case the firstname is Jérôme I tried some things : 1) insert at the beginning : #-*- coding: utf-8 -*- from __future__ import unicode_literals 2) Use .encode('utf-8') and .decode('utf-8') But up to now, impossible remove this error and handle data with accents. Do you have any idea ? -
Create Dynamic Table using Response data in reactJS
My question is, i want to print table in reactJS. I have already use axios to get data from django views and i got response. But, I don't know who to set this data in table format. I have used Table of react-bootstrap. And i am very new in ReactJS. My Code Snippet is: change(){ axios.get('http://127.0.0.1:8000/users/') .then(function (response) { console.log("in user",response.data[0].id); this.setState({ id: response.data[0].id, username: response.data[0].username, email: response.data[0].email, }); }) .catch(function (error) { console.log(error); }); } But Now how to use this id,username and email in "tbody" tag? Please Guide me. Thanks. -
Create autonomous TOC from a restructuredtext Document
I am writing a blog in Django and I want to compose my posts with restructuredtext. I am using django-markup to convert the text to HTML which works perfectly fine. Additionally, I want to create a table of content out of that text (my blog post). For this purpose I have created a template tag. My template looks like this: [...] {{ blog.content|rst_toc }} <hr /> {{ blog.content|apply_markup:article.markup }} [...] tags.py: import docutils from docutils import core register.filter def rst_toc(text): doctree = core.publish_doctree(text) for section in doctree.traverse(docutils.nodes.section): title = section.next_node(docutils.nodes.Titular) if title: print(title) return 'TOC' The main problems here is that this snippet is missing the document title. Any thoughts on this would be appreciated especially to the fact that I am publishing the doctree twice. In |rst_toc and |apply_markup:article. -
In django where to specify application related settings
At present my application related variables like external server IP / default pattern etc.. These variables are specific to my application. It includes my external server username and password. Now how can I have a single common place so that I can externalise this from my application. The options which I thought are below: Have one conf.ini file and use configparser and read this during the start of the django app But I am not sure from where I should have method to read this so that it will be done in the startup. Other option is to save this in a py file itself and import this file in my modules Please suggests me the good and standard approach for above issue. -
Django is showing CSS style in base template, but not in other files that they derive from
in Django 1.11 I have base template with navbar and copyright sections that show on every page. That base template loads static files including CSS file. The problem begin when I try to use the same css file to style other html files that open in the same time. I tried to inspect css file in browser and classes that are used by other files doesn't show in browser. Path to css file is relative. I don't know why Django doesn't load that last class from style.css Here is the code of 'base.html' file: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <title>Dadilja.hr</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="{% static "css/style.css" %}"> </head> <body> ... {% block content %} {% endblock %} ... </body> </html> This is html file that I try to style with the same css file. Problematic class is "profilna": {% extends "accounts/base.html" %} {% block content %} {% for dadilja in dadilja_list %} <div class="container"> <div class="col-md-2"> <a href="{{ dadilja.id }}"> <img src="{{ dadilja.slika_profila.url }}" alt="{{ dadilja.ime }} {{ dadilja.prezime }}" class="profilna"> </a> </div> <div class="col-md-10 profilna"> {{ dadilja.ime }} {{ dadilja.prezime }} {{ dadilja.mjesto }} </div> <br><br> </div> {% endfor … -
Django Add fieldset legend to ModelForm
I have a model: models.py class Doc(models.Model): series = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) number = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) name = models.CharField(max_length=150, help_text="3") citizenship = models.ManyToManyField(Citizenship, help_text="4") forms.py class DocForm(ModelForm): class Meta: model = Doc fields = '__all__' How do i add 2 legends for these fields? 1 for series and number and 1 for name and citizenship? template {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}" class="control-label col-md-3">{{ field.label }} {% if field.field.required %}<span class="required"> * </span> {% endif %} </label> <div class="col-md-4"> {{ field }} {% if field.errors %} {% for error in field.errors %} <span id="{{ field.id_for_label }}-error" class="help-block help-block-error">{{ error }}</span> {% endfor %} {% endif %} </div> </div> {% endfor %} -
django printing a table to pdf using weasyprint
Morning, I've created a table for a document template and when a user is attempting to save the document after making amendments to text it saves as a pdf but will not apply the table border i'm currently trying to use weasyprint and this is my css: body { font-family: "Calibri", Calibri, Helvetica, Arial, "Lucida Grande", sans-serif !important; font-size: 11pt; border: 10px; table-border-color-dark: black; } I've tried adding it as table in the css but still no luck i would add my template but am unsure on how to display html on stack overflow as the help doesn't describe very well. This is part of the code i'm using to write to pdf. Code: pdf_file = HTML(string=form.cleaned_data.get('contents')).write_pdf( stylesheets=[ CSS(staticfiles_storage.path('stylesheets/site/pdf.css')) ] ) -
Google container Engine django deployment is raising error
I have set up my Django project to deploy on the container engine based on documentation https://cloud.google.com/python/django/container-engine. After creating kubernetes resources with kubectl create -f project.yaml I try to get the status of the pods with kubectl get pods Each of the pod has status **CrashLoopBackOff** Can you please suggest on debugging this error? -
What are the drawbacks of template tags in django?
It is more of a discussion as I just to know what are the drawbacks of template tags if there are any.I use a lot of template tags in my projects because it solves hell lot of problems.But I do have one query regarding template tags is that does it makes the application slow? Should I avoid using it or there are no drawbacks of template tags? -
Generating the Django route
Tell me, please, why the route is not generated correctly? viewSet: class MyViewSet(BaseViewSet, CreateModelMixin): http_method_names = ['post'] queryset = User.objects serializer_class = MySerializer permission_classes = (AllowAny,) @detail_route(methods=['get'], permission_classes=[IsAuthenticated], url_name='my') def my(self, request, version, pk=None): serializer = MyInfoSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls: users_router = DefaultRouter() users_router.register(r'users', MyViewSet) When you try to navigate to the specified address (http://127.0.0.1:8000/api/v1/users/my/), page 404 appears. Routes are formed like: ^api/ ^(?P<version>(v1))/ ^ ^users/$ [name='user-list'] ^api/ ^(?P<version>(v1))/ ^ ^users\.(?P<format>[a-z0-9]+)/?$ [name='user-list'] ^api/ ^(?P<version>(v1))/ ^ ^users/(?P<pk>[^/.]+)/my/$ [name='user-my'] ^api/ ^(?P<version>(v1))/ ^ ^users/(?P<pk>[^/.]+)/my\.(?P<format>[a-z0-9]+)/?$ [name='user-my'] -
How to solve Jenkins Build trouble?
I have a Django project on BitBucket, so I was going to use Jenkins for CI, but the build keeps failing! Here is the script: cd $WORKSPACE virtualenv -q env . ./env/bin/activate cd requirements pip install -r base.txt cd .. cd manage python test_manage.py test --settings=test_site Here is the result(Jenkins console): ImportError: No module named test_site Build step 'Execute shell' marked build as failure [Cobertura] Publishing Cobertura coverage report... Finished: FAILURE How can I solve this problem ? -
How to increase RAM usage of Celery
I was using 8 GB ram machine, when i ran celery task in that system that particular task able to complete in 45mins Now i have switched to a machine of 40 GB ram, but still i am able to complete the same task in 35 mins. I hope celery is not able to make use of the 40 GB ram properly, how can i customize ram usage of Celery. Please help me with this problem. Thanks! -
How to add DateTimeField in django without microsecond
I'm writing django application in django 1.8 and mysql 5.7. Below is the model which I written class People(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() create_time = models.DateTimeField() class Meta: db_table = "people" Above models create table like below. mysql> desc people; +-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(20) | NO | | NULL | | | age | int(11) | NO | | NULL | | | create_time | datetime(6) | NO | | NULL | | +-------------+-------------+------+-----+---------+----------------+ Here Django create datetime field with microsecond datetime(6) But I want datetime field without microsecond datetime I have other application, which also using same database and that datetime field with microsecond raising issue for me. -
django pass model fields to BetterForm
I am trying to use BetterForms to group the fields and add a legend to each group. For example i have this model: models.py class Doc(models.Model): series = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) number = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) name = models.CharField(max_length=150, help_text="3") citizenship = models.ManyToManyField(Citizenship, help_text="4") forms.py class DocForm(BetterForm): name = forms.CharField(max_length=150, help_text="3") class Meta: model = Doc fieldsets = [ ('main', {'fields': ['name', 'citizenship'], 'legend': 'I. PERSONAL DATA'}), ('main1', {'fields': ['series', 'number'], 'legend': 'II. PROFESSIONAL IDENTIFICATION'})] I have many more fields than i've written here. Is there a possibility to pass the model fields as in ModelForm instead of writing each field in the form again? -
Django manage.py runserver unhandled exception in thread error
In django when I am trying to run manage.py runserver its giving an unhandled exception in thread error. I am using 'ENGINE': 'django.db.backends.sqlite3' Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\MY\Desktop\myproject\firstproject\firstproject\urls.py", line 18, in url(r'^admin/', admin.site.urls), NameError: name 'url' is not defined -
Django Rest Framework authtoken not migrating in MySql but migrating in SQLite
Django Rest Framework authtoken not migrating in MySql but migrating in SQLite Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\django\base.py", line 177, in _execute_wrapper return method(query, args) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1091 (42000): Can't DROP 'user_id'; check that column/key exists During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Guest01\Envs\qcrb\Lib\site-packages\django\tokentutor\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet) django.db.utils.ProgrammingError: Can't DROP 'user_id'; check that column/key exists