Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get base64 string from file which uploaded in django?
Thit is import import base64 This: ":b2a_base64() argument 1 must be convertible to a buffer, not InMemoryUploadedFile" Raised by this: base64.b64encode(request.FILES['my_file']) -
Javascript fetch api didn't get response after 'POST' data to Django server
I am building a poll app based on django and react.When I use fetch api to POST data to my django server,I return some detail information so that I can do something else.I am using fetch api to handle all GET and POST method on my front end.This is my form class. export default class VoteForm extends React.Component{ constructor(props){ super(props); this.state = {subjects:[],choosen:"",new:false,message:''}; this.handleSelect = this.handleSelect.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleNewOption = this.handleNewOption.bind(this); } componentWillReceiveProps(props){ this.setState({subjects:props.subjects}); this.setState({choosen:props.subjects[0]}); } handleSelect(event){ if(event.target.value=="customize new option"){ this.setState({new:true}); }else{ this.setState({choosen:event.target.value,new:false}); } } handleNewOption(event){ console.log(event.target.value); this.setState({choosen:event.target.value}); } handleSubmit(){ let json = { pk:this.props.pk, subject:this.state.choosen, }; let csrftoken = Cookies.get('csrftoken'); let header = { "method":'POST', "body" :JSON.stringify(json), "credentials": 'include', "headers":{ "X-CSRFToken": csrftoken, "Accept": "application/json", "Content-Type": "application/json", } }; //This is where it gets wrong.Both alerts didn't work.It only prompted the small window a few times after I quickly clicked the mouse several times.And response wasn't consoled either. fetch('/voteapp/addvoteforsubject/ ',header) .then(function(response){ alert("get response"); return response.json(); }) .then(function(response){ //console.log(response); alert(response.detail); }) .catch(function(error){ console.log(error); }); } render(){ let Options = this.state.subjects.map((opt,index)=>(<option key={index}>{ opt }</option>)); let new_input; let submit; if(this.state.new){ new_input = (<input type="text" className="form-control" placeholder="type new option" onChange={this.handleNewOption}></input>); submit = ( <button className="btn btn-secondary btn-block" onClick={this.handleSubmit}>Submit</button>); }else{ submit = ( <button … -
Django [WinError 5] IIS
I have a problem with Django 1.11 on Windows IIS. On localhost it works, but on IIS not. Any ideas? Error [WinError 5] Access denied http://take.ms/3O0rl views.py from django.shortcuts import render from django.utils import timezone from . models import Order import sqlite3 import time import datetime import xml.etree.ElementTree as et import urllib.request as ur def get_order(request): web_data = ur.urlopen('http://www.xxxx.com/pl/pl/xml/index/id/xxxx/password/xxxxx/no_tagging/1') str_data = web_data.read() xml_data = et.fromstring(str_data) order_list = xml_data.findall("order") conn = sqlite3.connect('db.sqlite3') c = conn.cursor() for order in order_list: order_id = order.find("bestellungid").text add_date = order.find("datum").text amount = order.find("anzahl").text price = order.find("a_preis_a").text desc = order.find("a_bezeichnung1").text sap = order.find("a_int_artikelid").text customer_name = order.find("h_name1").text customer_street = order.find("h_anschrift").text customer_code = order.find("h_plz").text customer_city = order.find("h_ort").text customer_phone = order.find("h_telefon").text payment = 'Pobranie' status = 'Nie zrealizowane' c.execute("INSERT OR IGNORE INTO tyre24_order (order_id, add_date, amount, price, desc, sap, customer_name, customer_street, customer_code, customer_city, customer_phone, payment, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (order_id, add_date, amount, price, desc, sap, customer_name, customer_street, customer_code, customer_city, customer_phone, payment, status)) conn.commit() c.close() conn.close() return render(request, 'get_tyre.html') -
Django tables2 rendering empty column but creating rows
i am trying to generate tables using Django tables2 but itis creating rows with empty column import django_tables2 as tables import itertools from myapp.models import country_details class country_detailstable(tables.Table): state = tables.Column() district= tables.Column() block = tables.Column() class Meta: attrs = {'id':'datatable','class': 'table table-striped table-bordered','role':'grid', 'aria-describedby':'datatable_info', 'th':{'class':'sorting_asc', 'tabindex':'0', 'aria-controls':'datatable', 'rowspan':'1' ,'colspan':'1', 'aria-sort':'ascending', 'aria-label':'State: activate to sort column descending'}, 'th':{'class':'sorting', 'tabindex':'0', 'aria-controls':'datatable', 'rowspan':'1' ,'colspan':'1', 'aria-label':'District: activate to sort column descending'}, 'th':{'class':'sorting', 'tabindex':'0', 'aria-controls':'datatable', 'rowspan':'1' ,'colspan':'1', 'aria-label':'Block: activate to sort column descending'}} #'td':{'class':'sorting_1'}} #fields = ('state_name','district_name','block_name') -
django-formtools load initial values for modelformset
I am trying to load an initial values for ModelFormSet within SessionWizardView, I tried loading initial values for ModelFormSet without the SessionWizardView and everything is working but with it, it's giving me this error: dictionary update sequence element #0 has length 1; 2 is required Here is my code class AgreementView(SessionWizardView): formset = modelformset_factory(model=Agreement, form=CreateAgreementsFormSet) form_list = [formset] template_name = 'app_name/template.html' def get_form_initial(self, step): initial = self.initial_dict.get(step, {}) if step == '0': initial.update([{'agreement' '4'}, {'agreement' '4'}, {'agreement' '4'}]) return self.initial_dict.get(step, initial) -
clean coding to manage project configuration?
For a Saas Project that I am working on (Angular/Django), we have noticed that we have many client segments. Since it's not DRY to clone our plateforme to have separate version for each segment, we have decided to create a configuration object for each project which enable us to customise the product quickly to adapt to client needs. Problem : The problem we are facing on front is that code starts to be spaghetti since we need to execute each piece of code according to this configuration object. Now we have switch and if everywhere which makes code hard to read and to maintain. Is theire any good practices to handle such a situation ? -
How to set only the hour for a django DateTimeField using update
I have a long list of entries that have a field date=models.DateTimeField(default=timezone.now) This field use to be a DateField only and now i changed it to datetime. After the migration the existing entries have the default hour set to midgnig (00). I would like to update that for all entries to be to 9 AM. I would like something like this: Entry.objects.all().update(date__hour=9) but this does not work as it raises and exception: django.core.exceptions.FieldDoesNotExist: Entry has no field named 'date__hour' Any suggestions? Thanks -
Node process with dedicated memory in Python
I'm developing with Apache and Django an web application application where users interacts with a data model (C++ implementation wrapped into Python). To avoid load / save data in a file or database after each user operation, I prefer keep data model in memory as long as the user is connected to the app. Until now, data models are stored into a variable attached to web service. As Python running under Apache has sometimes strange behavior, I'd prefer execute user operation into separated python process, today on same server, maybe tomorrow on a different node. I'm under the impression that Distributed computing library (dispy, dask distributed) does not enable to keep memory attached to a node. Does anyone have a solution / idea about what libraries could I use ? -
For.. in loop not adding attributes to Django object
I'm trying to create a new database object for the following Django class: class MenuItems(models.Model): """Main class for food & drink menu items""" category = models.ForeignKey(MenuCategories, on_delete=models.CASCADE) name = models.CharField(max_length=50) price = models.DecimalField(max_digits=10, decimal_places=1) calories = models.IntegerField(null=True) proteins = models.DecimalField(max_digits=10, decimal_places=1, null=True) carbs = models.DecimalField(max_digits=10, decimal_places=1, null=True) sugar = models.DecimalField(max_digits=10, decimal_places=1, null=True) fat = models.DecimalField(max_digits=10, decimal_places=1, null=True) saturated_fat = models.DecimalField(max_digits=10, decimal_places=1, null=True) sodium = models.DecimalField(max_digits=10, decimal_places=1, null=True) I start by fetching the category object using a custom function, this has been tested and works successfully. As you are able to see in the class definition, the only required fields are 'category', 'name' and 'price'. I send the following dictionary to the function which creates the database object: details = { 'category': category, 'name': 'Pizza Hawaii', 'price': 12, 'entered_details': { 'calories': 764, 'proteins': 30.4, 'carbs': 19.3, 'sugar': 16.7, 'fat': 29.6, 'saturated_fat': 9.6, 'sodium': 1560, } } This is the code which should add all the entered values and most importantly, the optional values only if they are provided, to the object: item = MenuItems.objects.create( category=details['category'], name=details['name'], price=details['price'], ) item.save() for detail, value in details['entered_details'].items(): item.detail = value item.save() When I try to call an optional value, such as 'calories' using print(item.calories) … -
handle `post_save` signal in celery
I have a rather long running task that needs to be executed after inserting or updating an specific model. I decided to use post_save signal instead of overriding save method to reduce coupling. Since Django signals are not asynchronous I had to do the long running job as a Celery task (which we already have in our stack). A simplified version of my signal handling function is as follows: @receiver(post_save, sender=MyModel) def my_model_post_save(sender, instance, **kwargs): handle_save_task.apply_async(args=(instance.pk,)) Also, because the job is done asynchronously I passed the primary key of the object instead of the instance itself. @app.task(queue='elastic') def handle_save_task(instance_pk): try: instance = MyModel.objects.get(pk=instance_pk) except ObjectDoesNotExist: # Abort logger.warning("Saved object was deleted before this task get a chance to be executed [id = %d]" % instance_pk) else: # Do my things with instance The actual problem is that when the celery task is executed it can't access the newly saved instance. Just like if it was executed prior to saving! (wasn't the signal called post_save? What an irony) By "executed before saving" I mean if it is a new instance that's being inserted to DB, in the celery task I get an DoesNotExist exception and in cases where instance was already … -
Django Error --SyntaxError: invalid syntax
It seems that i am stuck. I need your help in order to fix this error. I think the regex on the URL is rotten. Any help will be much appreciated. This is the error: File "/Users/cohen/Documents/project/sanctions/batches/urls.py", line 2, in from . import views File "/Users/cohen/Documents/project/sanctions/batches/views.py", line 23 def detail_businessname(request): ^ SyntaxError: invalid syntax These are my models: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Batches(models.Model): BatchNumber = models.IntegerField(null=True) FileName= models.CharField(max_length=250) UploadedDate= models.DateField(max_length=250) UploadedBy = models.CharField(max_length=250) NumberOfRows= models.IntegerField(null=True) Hits= models.IntegerField(null=True) Status= models.CharField(max_length=250) class Meta: verbose_name_plural = "Batches" def __str__(self): return self.FileName + '- ' + str(self.Hits) + '- ' + str(self.NumberOfRows) + '- ' + self.Status class BusinessName(models.Model): AccountingCode = models.CharField(max_length=50) RefID = models.CharField(max_length=50, default="") FullName = models.CharField(max_length=250) Aliases = models.CharField(max_length=250) Address = models.CharField(max_length=500) City= models.CharField(max_length=50) ZipCode= models.IntegerField(null=True) State = models.CharField(max_length=250) Country= models.CharField(max_length=250) TypeOfSanction= models.CharField(max_length=250) Monitoring= models.CharField(max_length=50) BatchNumber= models.IntegerField(null=True) # tr pus automat FileName= models.CharField(max_length=250) # tr pus automat1 UploadDate = models.DateField(max_length=250) # tr pus automat UploadBy= models.CharField(max_length=250) # tr pus automat Decision= models.CharField(max_length=250) # tr pus Ulterior Status= models.CharField(max_length=250) # tr pus automat EngineDecision= models.CharField(max_length=250) # tr pus automat WhoAdjudicated= models.CharField(max_length=250) DateOfAdjudication= models.CharField(max_length=250) SdnType = models.CharField(max_length=250) #Entity or Individual class Meta: verbose_name_plural … -
Insert newline in Django CharField form
I would like to know if there is a solution in order to make multiple newlines in my Django Charfield Form. I have a field Description and I would like to write something inside like : Hello, My name is John. I am 23 years old. Is it possible to help me ? Unfortunately, up to now I have : Hello, My name is John. I am 23 years old. Is it possible to help me ? My models looks like : class Ticket(models.Model): ... Description = models.CharField(max_length=250, verbose_name='Description') How I could do that ? -
Uploading angular2-posted-image to S3 with django and django-rest-framework
I am getting the following multipart/form data with POST method from frontend driven by angular 2. email = "help@help.com" password = "i'm-hopeless" auth_image_url = "please-help-newbie.png" I'm trying to get the user to post auth_image on signup, which should be saved on s3 bucket with the image's url saved on db. The thing is the auth_image_url is not getting the correct url nor is it being saved on S3 bucket. However, I can confirm using django's admin, above request is processed and user(="help@help.com") is created with correct password, but auth_image_url contains None. The funny thing is, I'm able to save the image from admin menu, by updating the 'auth_image_url' and saving on UserAdmin. This way the image is uploaded correctly to the intended path on S3 bucket. After 2 days of googling and debugging, I finally give up and await helplessly for the help of Near-God stackoverflowers. :( Ipdbing the code suggest that the request.data in the following form: <QueryDict: {'email': ['help@help.com'], 'password': ['i'm-hopeless'], 'auth_image_url': [<InMemoryUploadedFile: please-help-newbie.png (image/png)>]}> in my views.py is not processed through the serializers.validate() method, because the self.inital_data is mapped with correct query_dict but the validated_data['auth_img_url'] dict contains None value, after some validation process I don't understand. But … -
Can't serve static files on Django + Apache / Windows
I need to deploy my Django 1.11 project on a windows machine using Apache + mod_wsgi. I followed some tutorials and managed to get everything working except for static and media files. I've already launched the "collectstatic" command for deployment and django replicated the static and media folder where the settings.py file told it to be. this is the inside of the C:\Apache24\htdocs folder C:. └───AWD ├───.idea │ └───inspectionProfiles ├───AWD ├───AWD_Zanasi │ ├───configs │ ├───migrations │ ├───static │ │ └───AWD_Zanasi │ │ ├───css │ │ │ └───plugins │ │ ├───font-awesome │ │ │ ├───css │ │ │ ├───fonts │ │ │ ├───less │ │ │ └───scss │ │ ├───font-awesome.bak │ │ │ ├───css │ │ │ ├───fonts │ │ │ ├───less │ │ │ └───scss │ │ ├───fonts │ │ └───js │ │ └───plugins │ │ ├───flot │ │ └───morris │ ├───templates │ │ ├───AWD_Zanasi │ │ │ └───projects │ │ └───registration │ └───templatetags ├───media │ └───user_admin │ ├───project │ │ └───out │ ├───sd │ │ └───out │ └───we │ └───out └───static ├───admin │ ├───css │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor │ ├───jquery │ └───xregexp └───AWD_Zanasi ├───css │ └───plugins ├───font-awesome │ ├───css │ … -
How can i display the form data in table format on webpage using Python Django 1.11 and bootstrap design?
I am also using bootstrap for designing purpose. I don't have made any models yet. I just had designed the UI form which is having "Submit" button. I want to submit the data entered in the form and display those data in tabular format either redirected on same page or new one is not an issue. Please help me out! :( Thanks in advance. -
Got "Method Not Allowed" error calling Django SOAP web server
I have written a SOAP web server with Django using this tutorial; I used the exact code disscussed in the tutorial and its linked tutorials. This is my urls.py BTW: from django.conf.urls import url from django.contrib import admin from views import hello_world_service urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello_world/', hello_world_service), url(r'^hello_world/service.wsdl', hello_world_service), ] To call the method 'say_hello' I wrote multiple clients using different libraries: Implementation with suds: from suds.client import Client as SudsClient url = 'http://127.0.0.1:5000/hello_world' client = SudsClient(url=url, cache=None) This is error traceback in the client side: Traceback(most recent call last): File "client.py", line 14, in < module > client = SudsClient(url=url, cache=None) File "build/bdist.linux-x86_64/egg/suds/client.py", line 112, in __init__ File "build/bdist.linux-x86_64/egg/suds/reader.py", line 152, in open File "build/bdist.linux-x86_64/egg/suds/wsdl.py", line 136, in __init__ File "build/bdist.linux-x86_64/egg/suds/reader.py", line 79, in open File "build/bdist.linux-x86_64/egg/suds/reader.py", line 95, in download File "build/bdist.linux-x86_64/egg/suds/transport/https.py", line 60, in open File "build/bdist.linux-x86_64/egg/suds/transport/http.py", line 64, in open suds.transport.TransportError: HTTP Error 405: Method Not Allowed And this is what I get in the server console: [24/Jul/2017 08:17:14] "GET /hello_world HTTP/1.1" 301 0 [24/Jul/2017 08:17:14] "GET /hello_world/ HTTP/1.1" 405 0 Another Implementation with suds: I found it here. from Tkinter import * from suds.client import * class SoapClass: def __init__(self, master): self.client = … -
How to get superuser details in Django?
I'm new to Django. I have a simple issue: I need to have the superuser email of the website to send him an email from the admin panel (actually it is for testing if the email is well formated before sending it to registred users). To get all users, I type: users = User.objects.all() How to get the superuser(s)? superusers = ... -
Python IMAPClient fetch() method optimization for large data
I am writing an email client using IMAPClient. My goal now is to render the list of messages in my INBOX. The number of messages amount to around 4 thousand. The problem is that it takes ages to fetch these letters like this: server = IMAPClient(HOST, use_uid=True, ssl=True) server.login(USERNAME, PASSWORD) server.select_folder('INBOX') messages = server.search(['NOT DELETED']) response = server.fetch(messages, ['RFC822', 'BODY[TEXT]']) # TAKES AGES TO FINISH It seem intuitive that I should ask for, say, the first 20 messages, and then if the user scrolls down, ask for the next chunk of 20 messages. In other words, I should somehow paginate the fetch command, or make it lazy. But IMAPClient seems to be silent on this , though it seems like a major issue. Any ideas ? -
django when select format time column
django model JobError(id int pk, create_time datetime[2017-07-24 00:00:14]) sql below: SELECT time_format,count(id) as total from (SELECT id, date_format(create_time, '%Y-%m-%d %H:%i') AS time_format FROM monitor_job_error WHERE create_time > '2017-7-24')as tab GROUP BY time_format I want use django orm now, how can i do when selct create_time do date_format. JobError.objects.filter(create_time__gte=(datetime.now()-relativedelta(hours=15))).order_by('create_time').values('create_time').annotate(total=Count('id')) guys, please help. thanks!:) -
Design models: search by singleton models in django
I have a model TranslationService, which has some fields and methods which should be overriden by every new service. I have three services: Google, Azure, Bing, which are the only ones in system (we have only one Google service and one Azure service etc.). I need to perform action like this: TranslationService.objects.filter(service_name=service_name). But if i make TranslationService abstract, i can't iterate over abst class, cause it wasn't created in DB. If I make inheritance I should implement logic of overriding methods in code like model and then create GoogleService via console. Is this the only way or I can reduce creating object via console. How can I design my models for performing search among translation_services? class TranslationService(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) service_name = models.CharField(max_length=40) base_url = models.CharField(max_length=255) api_version = models.FloatField() def get_step_translation(self, pk, lang, lesson): pass def create_step_translation(self, pk, lang, type): pass class GoogleTranslator(TranslationService): base_url = "https://google.com" service_name = "Google" api_version = 1.5 def get_step_translation(self, pk, lang, lesson, **kwargs): ... some logic def create_step_translation(self, pk, lang, type): ... some logic -
Django 1.10 server to server websockets
Thanks to the huge update 1.10, Django now supports async websockets. Awesome! I've used the websockets to connect a client to the Django server. Now I have a use case where the server needs to initialize a socket connection to another server. Question: Is it possible for a Django backend to initialize a websocket connection to another server? If yes, how can is this done? -
Render inline formset with ForeignKey in Django
I have two models Model1 and Model2, where Model2 contains a Foreignkey to some other model (Say Model3). I am using django inline formset to add and edit information related to Model1. Below is the Formset that I have created, the md_attributes in the fields is the ForeignKey field to Model3. inline_form_set = inlineformset_factory(Model1, Model2, fields =('md_attributes', 'val',), max_num=0, can_delete=False, extra=0) The template to render the formset is {{ formset.management_form }} {% for form in formset %} {{ form.id }} {{ form.md_attributes}}: {{ form.val }} <br><br> {% endfor %} <input class="btn" type="submit" name="submit" value="Save"><br><br> <input class="btn" formaction="{% url 'projects:admin_projects_info' project_name %}" type="submit" name="submit" value="Cancel"> With the above template code, the formset is rendered as Foreignkey choices(Choice Field) and a Textinput field. But what I try to achieve is to render the foreign key choices as static labels in the formset like below Choice1 : Some Value, Choice2 : Othe Value I tried creating a list of choices and then use it in the for loop (template), but with that my post request is creating an error. I also think that's not an efficient way to solve this problem. Any valuable input is highly appreciated. Thanks -
TypeError: metaclass conflict: the metaclass of a derived. Django 1.8, python 2.7
I'm facing a very weird exception about the meta-class. I'm using python 2.7 and django 1.8 framework. But sometimes this exception appears. I still cannot track where the problem actually happened because it mysteriously disappeared later then. The problem is come from the resource.py in django-framework, function filter_response: return self.serialize(obj) I just want to hear your advise on how this error may happen, and how it disappear even I didn't change anything. Is there any solution for this. Thank you. -
keep li active while using pagination in django templates?
I am java script to keep my li in ul active on sidebar-nav.But it gets deactivated everytime I switch to page 2 as I am using pagination: my ul li code is here:- <li> <a href="#" class="dropmenu"> <i class="fa fa-newspaper-o fa-lg margin_right5"></i> <span>News Management</span> </a> <ul> <li class=" "><a href="{% url 'cms:news-list' %}" class="submenu"><span class="">News List</span></a></li> <li class=" "><a href="{% url 'cms:news-reported' %}" class="submenu"><span class="">Reported News</span></a></li> </ul> </li> what I tried:- <li> <a href="#" class="dropmenu"> <i class="fa fa-newspaper-o fa-lg margin_right5"></i> <span>News Management</span> </a> <ul> <li class="{% if request.path =='/news/list'%} active {% endif%} "><a href="{% url 'cms:news-list' %}" class="submenu"><span class="">News List</span></a></li> <li class=" "><a href="{% url 'cms:news-reported' %}" class="submenu"><span class="">Reported News</span></a></li> </ul> </li> but it is not working in case of pagination. -
Python tempfile [Errno 66] Directory not empty [duplicate]
This question already has an answer here: How to delete a file or folder? 5 answers How do I remove/delete a folder that is not empty with Python? 12 answers I need to process some file generated from db objects and after required process need to delete that directory with files.I have decided to use python templefile package. I have give it a try but stuck on Direcotry not Empty [ Error 66 ]. In views.py def writeFiles(request, name): tmpdir = tempfile.mkdtemp() instance = request.user.instances.get(name=name) print(instance) print(instance.name) code = instance.serverFile jsonFile = instance.jsonPackageFile docker = """ FROM node # Create app directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/ap # Install app dependencies COPY package.json /usr/src/app/ RUN npm install # Bundle app source COPY . /usr/src/app EXPOSE 8080 CMD [ "node", "server" ]""" # Ensure the file is read/write by the creator only saved_umask = os.umask(0o077) server = 'server.js' json = 'package.json' path = os.path.join(tmpdir) print(path) try: with open(path + '/dockerfile', "w") as dockerfile: dockerfile.write(docker) with open(path + '/server.js', "w") as server: server.write(code) with open(path + 'package.json', "w") as json: json.write(jsonFile) print(os.path.join(tmpdir, json)) except IOError as e: print('IOError:', e) else: os.remove(path) finally: os.umask(saved_umask) os.rmdir(tmpdir)