Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django write in database when form is submit
i want to use html form to be able to send back information to my view.py, the goal is to get the data, use it as arguments in a call to a stored procedure. def mouvementCreation(request): idMI = 0 especes = TbEspece.objects.order_by('id') #Get Mouvement informations #Connection to 'erp-site' DB cursor = connections['erp-site'].cursor() try: #Get Produits list from Espece query = "{CALL SP_webGET_PRODUIT_FROM_ESPECE(%s,%s,%s,%s,%s)}" arguments = (2016, 'C', 0, 10, 'A',) cursor.execute(query, arguments) produits = dictfetchall(cursor) #Get Transporters list cursor.execute("{CALL SP_webGET_TRANSPORT}") transporters = dictfetchall(cursor) #Get Livreur list cursor.execute("{CALL SP_webGET_LIVREUR}") livreurs = dictfetchall(cursor) finally: cursor.close() cursor = connections['site'].cursor() try: #Get Circuit list cursor.execute("{CALL SP_webGET_CIRCUIT_FOR_MVT}") circuits = dictfetchall(cursor) #Get Source list cursor.execute("{CALL SP_webGET_SOURCE_FOR_MVT}") mvtsources = dictfetchall(cursor) #Get Dest list cursor.execute("{CALL SP_webGET_DEST_FOR_MVT}") destinations = dictfetchall(cursor) #Get PontBascule list cursor.execute("{CALL SP_webGET_PBASCULE}") pontBascules = dictfetchall(cursor) finally: cursor.close() reg_normes = TbRegauxnormes.objects.all() ordreexecs = TbOrdreexecution.objects.all() form = mouvementForm(request.POST or None) if form.is_valid(): pont = form.cleaned_data['pont'] dateheure = form.cleaned_data['dateheure'] poid = form.cleaned_data['poid'] dsd = form.cleaned_data['dsd'] typepesee = form.cleaned_data['typepesee'] #Connection to 'erp-site' DB cursor = connections['pontbascule'].cursor() try: #Get Produits list from Espece query = "{CALL SP_ADD_MANUAL_PESEE(%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s)}" arguments = (pont, '11', dateheure, poid, dsd,typepesee, '','','','','','','','','','','','','','','','') cursor.execute(query, arguments) finally: cursor.close() return render(request, 'mouvementCreation.html', {'form': form, 'especes' : especes, 'produits' … -
ImageField not uploading my pic in template
I have a problem with uploading an image to my template. Code below, project-tree screen too. If you will need anything to help me, write pls. project-tree screen (model) Here comes particular model with which I got the problem. class WorkingPlace(models.Model): company_name = models.CharField(max_length=100, default='') logo = models.ImageField(upload_to='img') location = models.CharField(max_length=200) from_date = models.DateField(blank=True, null=True) till_date = models.DateField(blank=True, null=True, default='now') def __str__(self): return self.company_name (view) def main_view(request): form = ContactMe(request.POST or None) if form.is_valid(): form.save() print('saved') return HttpResponseRedirect('CV/base.html') else: form = ContactMe() print('unsaved') hobbies_and_interests = HobbiesAndInterest.objects.all() personal_features = PersonalFeature.objects.all() skills = Skill.objects.all() letter = Letter.objects.get(id=1) working_places = WorkingPlace.objects.all() activities = Activity.objects.all() return render(request, 'CV/base.html', { 'form': form, 'hobbies_and_interests': hobbies_and_interests, 'personal_features': personal_features, 'skills': skills, 'letter': letter, 'working_places': working_places, 'activities': activities }) (settings) Static and Media settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "CV/../CV/../static"), ] STATIC_ROOT = 'WebCVDjangoI' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', "media") (template) Problem part of the template. {% for place in working_places %} <div class="row work-block"> <div class="col-md-1"> <i class="fa fa-bookmark" aria-hidden="true" style="font-size: 3em;"></i> </div> <div class="col-md-11 flex-around"> <img src="{{ place.logo.url }}" class="img-respomsive visible-lg-block visible-md-block visible-sm-block" style="width: 30%"> {{ place.logo.url }} <!--Mobile--> <img src="{{ place.logo }}" class="img-respomsive visible-xs-block" style="width: 50%"> <!--end--> <div style="width: 30%" class="text-center visible-lg-block … -
Importing data from multiple related tables in mySQL to SQLite3 or postgreSQL
I'm updating from an ancient language to Django. I want to keep the data from the old project into the new. But old project is mySQL. And I'm currently using SQLite3 in dev mode. But read that postgreSQL is most capable. So first question is: Is it better to set up postgreSQL while in development. Or is it an easy transition to postgreSQL from SQLite3? And for the data in the old project. I am bumping up the table structure from the old mySQL structure. Since it got many relation db's. And this is handled internally with foreignkey and manytomany in SQLite3 (same in postgreSQL I guess). So I'm thinking about how to transfer the data. It's not really much data. Maybe 3-5.000 rows. Problem is that I don't want to have same table structure. So a import would be a terrible idea. I want to have the sweet functionality provided by SQLite3/postgreSQL. One idea I had was to join all the data and create a nested json for each post. And then define into what table so the relations are kept. But this is just my guessing. So I'm asking you if there is a proper way to do … -
Uploading Files in django-admin
I am making a project in django where only the admin will be having the permission to upload files. How can i modify the admin page so that option to upload files is only visible to admin? currently it is looking something like this.. But i want an upload files option also below add choice actionenter image description here -
Cannot "open" notification that is received when the app is in background
i have a problem when i want to process notification that is received when the app is in the background. I do receive the notification, when i click on the notification, the app opens however the FCM.on method is not executed at all, it seems it does not handle the callback. When the app is in the foreground everything is working fine, and it process the notification without any problems. This is the code in react-native FCM.on(FCMEvent.Notification, notif => { switch(notif.fcm.action){ case 'fcm.ACTION.HANDLEMESSAGE': var data = { thread: notif.pk, message: JSON.parse(notif.message) } this.props.dispatch(fcmMSG(data)); this.props.dispatch(addNotification(notif.pk, notif.job_id)); break; case "fcm.ACTION.HANDLEAPPLICATION": axios.get(newServerURL + "/jobs/companyJobDetails/" + notif.recruitJobId + "/") .then((response) => { var jobMainRecruits = response.data; const {navigator} = this.refs; navigator.push({ jobMainRecruits, }); }) .catch((error) => { console.log("ERROR") }); break; default: } }); EDIT: this is my code in the backend push_service = FCMNotification(api_key=FCM_API_KEY) registration_id = token.token message_title = jobInfo.title message_body = "New application" message_icon = 'ic_launcher' sound = 'Default' color = '#362F64' click_action='fcm.ACTION.NEWJOBAPPLICATION' data_message = {'recruitJobId': self.request.data['job'], 'message_title': message_title, 'message_body': message_body} result = push_service.notify_single_device(click_action=click_action, registration_id=registration_id, message_title=message_title, message_body=message_body, message_icon=message_icon, sound=sound, data_message=data_message, color=color) Thanks for help in advance. -
Date format changes on UpdateView in Django
I have a form to create an object where the date input format is 'dd/mm/yyyy', when I submit the form, it is saved without any problem, but when I edit this object, the date shows as 'yyyy-mm-dd'. settings.py DATE_INPUT_FORMATS = ('%d/%m/%Y') forms.py class MyForm(forms.ModelForm): created_date = forms.DateField(input_formats=['%d/%m/%Y',], widget=forms.DateInput(attrs={'class':'datepicker form-control', 'placeholder':'Select a date'}), required=False) models.py created_date = models.DateField(blank=True, null=True, verbose_name="Created on") views.py class MyEdit(SuccessMessageMixin, UpdateView): model = MyModel form_class = MyForm template_name_suffix = '_edit' success_message = '...' and in my template I use $(".datepicker").datepicker({ format: 'dd/mm/yyyy', autoclose: true, changeYear: true, changeMonth: true }); -
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']