Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python subprocess Popen behaving differently on local and remote system
I am using django and sending a build to travis-ci which is failing the build on my tests. The line that is in question is in this function... from subprocess import Popen, PIPE def make_mp3(path, blob): process = Popen( ['lame', '-', '--comp', '40', path], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_data = process.communicate(input=blob.read()) return stdout_data the line that calls the function is here: make_mp3(mp3_path, request.FILES['audio_file']) on my local system the tests run fine and pass. I have been using this function for a while and it always behaves as expected. But when I send it to travis-ci for a build it gives me this traceback... ====================================================================== ERROR: test_post_upload_audio_word (define.tests.ViewTests) Testing the audio upload function for word audio ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/travis/build/deltaskelta/langalang/define/tests.py", line 827, in test_post_upload_audio_word 'audio_file': audio_file}) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 541, in post secure=secure, **extra) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 343, in post secure=secure, **extra) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 409, in generic return self.request(**r) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 494, in request six.reraise(*exc_info) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File β¦ -
javascript-POST request using ajax in Django issue
I am a beginner and self learned programmer and have written a code on my own. I am attempting to use Javascript post request using ajax and facing some continuous problem. There are lot of mistakes in code and want you guys to correct it with an explanation. Here is my base.js file: var user = { signup : function() { var firstname = document.signupform.first_name.value; var lastname = document.signupform.last_name.value; var username = document.signupform.username.value; var email = document.signupform.email.value; var password = document.signupform.password.value; var confirmpassword = document.signupform.confirmpassword.value; if (firstname == "") { alert("Please provide your first name!") document.signupform.first_name.focus(); } else if (username == "") { alert("Please provide the username!") document.signupform.username.focus(); } else if (email == "") { alert("Please provide your Email!") document.signupform.email.focus() ; } else if (password == "") { alert("Please enter a valid password") document.signupform.password.focus() ; } else if (password != confirmpassword) { alert("Passwords do not match."); document.signupform.confirmpassword.focus() ; } else { data = {"firstname":firstname, "lastname":lastname, "username":username, "email":email,"password":password}; this.postRequest(data); } return false }, postRequest:function(data,url,form) { $.ajax({ type: "POST", url: '', data: data, success: function(data){ if(data["success"]) { window.location.href = '{% url home %}' } else { alert(data["error"]) } } }); }, views.py: class UserFormView (TemplateView): template_name = "signup.html" #display signup blank form β¦ -
Type Error: 'module' object is not callable in django
i am trying to open a url but i am getting error TypeError: 'module' object is not callable: views.py file def register_user(request): args = {} args.update(csrf(request)) if request.method == 'POST': form = RegistrationForm(request.POST) args['form'] = form if form.is_valid(): form.save() # save user to database if form is valid username = form.cleaned_data['username'] email = form.cleaned_data['email'] salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt+email).hexdigest() key_expires = datetime.datetime.today() + datetime.timedelta(2) #Get user by username user=User.objects.get(username=username) # Create and save user profile new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires) new_profile.save() # Send email with activation key email_subject = 'Account confirmation' email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \ 48hours http://127.0.0.1:8000/confirm/%s" % (username, activation_key) send_mail(email_subject, email_body, 'myemail@example.com', [email], fail_silently=False) return render(request,'app/success',{}) else: args['form'] = RegistrationForm() return render_to_response('app/register.html', args, context_instance=RequestContext(request)) -
Service Worker JS File Location Query
I am trying to implement Push Notifications in my Python Django App. Project Structure: . βββ db.sqlite3 βββ manage.py βββ example β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ README.md βββ requirements.txt βββ static β βββ js β βββ sw.js β βββ push.js βββ templates βββ landing βββ homepage.html Now, Homepage.html file includes a script <script src="{% static 'js/push.js' %}"></script> Push.js includes: navigator.serviceWorker.register('../static/js/sw.js').then(function(serviceWorkerRegistration) { And let's say the this webApp is hosted on www.example.com. Now, I have two queries: 1) I can access the file at www.example.com/static/js/sw.js, But not on www.example.com/sw.js. If I move sw.js file at the root directory, and try www.example.com/sw.js then I get the following Error: Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: (and followed by a llist of urls mentioned in urls.py) Also, If i run 'python manage.py collectstatic' command then the file sw.js automatically gets moved to static/js/sw.js only. So, How can I make www.example.com/sw.js work ? 2) Can it be possible to host sw.js on Google Storage Bucket/AWS Bucket/somewhere else and fetch this file from there ? ( Or Can absolute path of the file hosted on remote server be used ) β¦ -
"AccessToken.user" must be a "User" instance
I am trying to figure out oAuth2 token based authentication since 3 days and no avail yet. I have written a code for user authentication. However, I am getting an error of ValueError at /api/customer/login/ Cannot assign "{'username': 'sanskars'}": "AccessToken.user" must be a "User" instance. What might be the soultion for this? And why the following error is raised? views.py class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): access_token = request.GET.get('access_token') data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data if new_data: app = Application.objects.get(name="appname") try: print('trying to fetch old token if exists') old_token = AccessToken.objects.get(user=new_data, appliction=app) print('old_token',old_token) except: pass else: old_token.delete() new_token = generate_token() print('new_token',new_token) AccessToken.objects.create(user=new_data, application=app, expires=datetime.now() + timedelta(days=365),token=new_token) print('aceess',AccessToken) return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserLoginSerializer(ModelSerializer): username = CharField() # email = EmailField(label='Email Address') class Meta: model = User fields = [ 'username', 'password', ] extra_kwargs = {"password":{"write_only": True} } Also one confusion is there do i need to generate token while registering user? -
how to save form data to database in django without forms
I am new to Django, I want to save form data to database(Postgre). I have mentioned my views.py file below, I want to save data from views to the database without using forms. Please tell me whether I can do or not. If I can then how I can do this. Thanks in advance for the help. my views.py def blog_list(request): actions = Action.objects.all() employees = Employee.objects.all() return render(request, 'blog/blog_list.html', { 'employees':employees,'actions':actions}) def blog_attendance(request, employee, action): if request.method == "POST": Employee = request.POST.get('employee', None) Action = request.POST.get('action', None) post = Employee.objects.filter(employee_name=Employee) post_Action = Action.objects.filter(action_name= Action) if post_Action == Action: post.entryTime = timezone.now() if post_Action == Action: post.breakIn = timezone.now() if post_Action == Action: post.breakOut = timezone.now() if post_Action == Action: post.exitTime = timezone.now() my models.py class Employee(models.Model): employee_id = models.AutoField(primary_key=True) employee_name = models.CharField(max_length=100) class Action(models.Model): action_name = models.CharField(max_length= 100) class Attendance(models.Model): employee_id = models.ForeignKey(Employee) action_id = models.ForeignKey(Action) action_time = models.CharField(max_length=100) app/urls.py urlpatterns = [ url(r'', views.blog_list, name='blog_list'), url(r'blog', views.blog_attendance, name='blog_attendance'), ] my blog_list.html <div class="col-sm-offset-4 col-sm-6"> <form method="post" action="blog_attendance">{% csrf_token %} <div class="form-group"> <label for="employee">Select Employee Name:</label> <select class="form-control" data-live-search="true" data-style="btn-info" name="employee" > <option value=none>--------------------------------------------------------------</option> {% for employee in employees %} <option value={{ employee.employee_name }}>{{ employee.employee_name }}</option> {% endfor %} β¦ -
Recurring billing with Stripe - will Subscriptions suffice?
My application allows a customer to purchase credits for later in-app use. I want to enable customers to buy credits throughout the month, and only get billed at the end of the month. Should I be using a Stripe Subscription at an amount that equals the price of one credit, and change the quantity according to the number of credits the customer purchased? (After a successful invoice - I'll reset the subscription quantity to 0) Is there a better solution? Perhaps some clever method of using Stripe Checkout? -
MultiValueDictKeyError in django if condition
I have if condition in djano view, In this if condition firstly i have to check if variable is isset or not empty and in second condition i have to check the value in this variable. if ( request.GET['customActionType'] != '' and request.GET['customActionType'] == 'group_action') : records['customActionStatus'] = 'OK' records['customActionMessage'] = 'Group action successfully has been completed. Well done!' But when i am using these variables in if condition its giving me error MultiValueDictKeyError at /admin/help "'customActionType'" -
NoReverseMatch in Django 1.10
Here is my url.py from django.conf.urls import url from django.contrib import admin from app import views, auth urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name = 'index'), url(r'^login/', auth.login, name = 'login'), url(r'^logout/', auth.logout, name = 'logout'), ] When i'm using in template <li><a href="{% url 'admin' %}">Administration</a></li> get error NoReverseMatch at / Reverse for 'admin' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] so can any one tell me how to solve this? Thank you very much. -
Django Test Driven Development (TDD) directory structure best practice.
What is the best directory structure for TDD in Django? Let's say I have multiple app in a project. -
Geoserver not starting on time
After running paver start -b it takes a while then shows this error: The logs are available at /home/AD/mapavia/geonode/geoserver/jetty.log GeoServer never started properly or timed out.It may still be running in the background. It runs on my other VMs so I'm thinking of more of a set-up issue? I really don't know. Any ideas? I also don't know what things I need to add to help answer my question. -
Django project not opening in PyCharm due to strange error with \.idea\workspace.xml?
I'm getting this error when trying to open my project on PyCharm community edition. The thing is, the project was opening fine on PyCharm until (literally 30 mins ago) a blue screen error hit ("dumping physical memory into disk, etc) and my windows7 x64bit PC just restarted. After restarting, PyCharm is throwing this error. Weird part is, I've checked the XML file on my Notepade++ and there are no open tags that need to be closed (let alone line 204). In fact, Notepadd++ search returns only 3 instances of but 70 instances of . And all instances of are lines 300+ (305,308,313). \.idea\workspace.xml': Error on line 204: The element type "state" must be terminated by the matching end-tag "</state>" I really cant work on this project on Notepad, please help me with getting this back up on PyCharm. Thanks!! -
Using zipped queryset many times in template
I have a model that is only a string : class Data(models.Model): string = models.CharField(max_length=200); There are 2 registered instances of the model in my database. It is rendered by this view, which zips the queryset which another list: def index(request): data = Data.objects.all(); data2 = []; for x in data: data2.append(0); return render(request, 'testApp/index.html', {"data": zip(data, data2)}) and here's the template code: {% for element, e in data %} {{ element.string }} {{ e }} <br/> {% endfor %} {% for element, e in data %} {{ element.string }} {{ e }} <br/> {% endfor %} This template iterates over the data twice, printing out the elements in the zipped list. Here's my output: hello there 0 i am a string 0 I am expecting 4 lines of output, because the 2 instances are looped over twice. However it's only printing them out once. What am I doing wrong? -
azure blob storage SAS usage in Django
I am currently doing a project in django. I would like only the users to be able to see their respective photos that are private to them. Unaware of security issues by setting blobs container permission to 'blob'(public read access), I have made all these photos available to the public to see. Not good! I learned about SAS in azure, and while there are some examples and good explanations, I am still confused as to how to design the program to use SAS. As of now, I am storing the blob storage urls of personal photos in the database. However, it seems like if I want to use the SAS, I have to make modification to the url of the photos every time the SAS is revoked/updated. Any advice on how I should design the codes? The example I see is : from azure.storage.blob import ( BlockBlobService, ContainerPermissions ) from datetime import datetime, timedelta account_name ="xxxx" account_key ="xxxxxx=" CONTAINER_NAME='samplecontainer' block_blob_service = BlockBlobService(account_name=account_name, account_key=account_key) sas_url = block_blob_service.generate_container_shared_access_signature( CONTAINER_NAME, ContainerPermissions.WRITE, datetime.utcnow() + timedelta(hours=1), ) I have storage.py In my models.py, from myapp.storage import OverwriteStorage def get_profile_picture_path(instance, filename): return os.path.join('customers', instance.username, 'profile', filename) class User_Info(models.Model) : picture = models.ImageField(upload_to=get_profile_picture_path, storage=OverwriteStorage(), null=True) In myapp.storage.py β¦ -
Django + SQLite + ForeignKey('self') = Failed Migration
In Django 1.9 using SQLite as the database backend, I am getting an error when trying to apply migrations after modifying a model to use multi-table inheritance instead of the OneToOneField relationship it was previously using. Particularly, the problem seems to be due to including a ForeignKey('self') in the model. models.py Here is the app from which an initial migration is successfully made and applied: from django.db import models from django.contrib.auth.models import User class Customer(models.Model): account = models.OneToOneField(User) parent = models.ForeignKey('self', null=True) models.py (modified) The app is then modified to inherit from the User model rather than linking to it: from django.db import models from django.contrib.auth.models import User class Customer(User): parent = models.ForeignKey('self', null=True) At this point a ./manage.py makemigrations <app> succeeds but then applying the migration fails with: Error Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards β¦ -
Django. Remove object from queryset
I need to do something like this: quito = queryset.get(lugar="Quito") queryset.pop(quito) But I get the error: 'QuerySet' object has no attribute 'pop' How can I solve this? -
Save A Matplotlib Figure to A File Along with Displaying it on The Browser Django
I have the following code in views.py for django project: response = HttpResponse(content_type ="image/png") file_saved = plt.savefig(response, format='png') return response In html: <form action="{% url "graph" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="files" multiple/> <input type="submit" value="Upload" /> </form> When I run server, it display the graph a new window. I want to do a couple of things, I want to save the figure into a file and also display it in the same browser without the need to go to another window. Thanks a lot in advance -
Finding all posts without tags in Django Postgres ArrayField
Just like what my title says, I want to see all my posts without any tags. However none of the following ORM is working: x = PostTagging.obejcts.filter(tags=[]) x = PostTagging.objects.filter(tags__len=0) All I get as a return is: <QuerySet []> Here is my model: class PostTagging(models.Model): title = models.CharField(max_length=50) tags = ArrayField(models.CharField(max_length=200), blank=True, null=True) def __unicode__(self): return self.title Here is my ORM for creating the blank tag: PostTagging.objects.create(title='Fifth Post') -
Configure django with mongodb and tastypie
I'm completely lost. I'm working with the restaurant example dataset in the official mongodb documentation and am having hard time finding a tutorial or explanation on how to connect my local mongo database to the api. I've looked through the django-tastypie-mongoengine documentation but they don't explain it at all. Here's the relevant part of my settings.py file: import mongoengine client = mongoengine.connect('test', host="localhost:27017") db = client.test My api.py file: from tastypie import authorization from tastypie.resources import ModelResource from tastypie_mongoengine import resources from proapp.settings import db from api_app import documents class RestaurantResource(resources.MongoEngineResource): class Meta: #queryset = documents.Restaurant.objects.all() queryset = db.restaurants.find() resource_name = 'restaurants' allowed_methods = ('get', 'post', 'put', 'delete') authorization = authorization.Authorization() Do I also need a documents.py file where I specify a model?: from mongoengine import * class Restaurant(Document): pass -
Django. Media Files not found
Ok, I have a Django 1.10 project. The relevant settings look like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = BASE_DIR + "/media/" MEDIA_URL = '/media/' I'm working locally, I can upload images correctly. But when I try to access the image on a template using {{ image.image.url }}, I get a 404. In the terminal I can see this: [06/Sep/2016 18:13:43] "GET /media/folder/uploaded_image.jpg HTTP/1.1" 404 4900 But if I look into my folder, the file is there, correctly uploaded by django. -
Specify number of significant digits for Django DecimalField
The Django documentation is clear that DecimalFields are a fixed-precision decimal number, based on the Python decimal module. If I have pre-existing data with 12 significant digits, how should I adequately model this? For example, here's a sample of the data of interest: shape_leng | shape_area --------------+-------------- 1530.79895768 | 90408.0667370 1936.60719682 | 182948.426626 232.229916910 | 1961.07387818 298.135367400 | 1206.32979471 7492.74283181 | 351026.396309 2284.47421526 | 240449.624361 1190.40843206 | 85766.7212220 579.035061001 | 17493.1577514 2532.91949894 | 343607.358136 3332.89318722 | 709775.074538 3259.11802943 | 378845.260875 3482.11473711 | 727006.254061 Some entries only have 6 decimals, while others have as many as 9 or 10. Since this is only a sample from the dataset, conceivably some could have an even greater range of values. Regardless, each entry has 12 digits and a decimal point. In my first pass, I set the models to be: shape_leng = models.DecimalField(max_digits=25, decimal_places=12, blank=True, null=True) shape_area = models.DecimalField(max_digits=25, decimal_places=12, blank=True, null=True) The downside is that I now am allowing for up to 25 digits, even though I know the true max_digits can only be 12 or 13. Is there a better way to represent this? Some kind of variable-precision numeric type that only requires a scientific-style, significant digits type of precision? -
A good python source code Scrambler
i'm searching for something that could be used in order to scramble my python source code, making it unreadable. I've tried OPY and pyminifier, but with django none of them works properly (module xxx import error) So, what are the alternatives? Some online tools, do the job, making it a good scrambling and producing a working output, but they won't publish the source code of the script... Any idea? Thanks -
Use and (&) in queryset only when the parameters extists Django
I don't know if there's a quick way to do this, but what I want to do is a search according to six parameters, where 5 of them come from Select Inputs, and the other one from an Input text, the search needs to be more specific when more options are selected. Is there a way to do this with lookups? Or I need to make an if for every combination of parameters? If I have to write all the if's, what is the more efficient way? Because if I'll have to do 2^6 if statements to cover all the combinations, that will be a little bit slow. Consider that the parameters doesn't have an specific order, so any combination is possible. I was thinking in Q objects but I don't know if they work for that, I have only used them for OR satements, I know that they can be used for and statements too, but I don't know if they are different than using comma. Probably something like this: result = Product.objects.filter(Q(field1=param1)&Q(field2=param2)&Q(field3=param3)&Q(field4=param4)&Q(field5=param5)&Q(field6=param6)) -
Best way to find out when old nginx configuration dropped all requests
I'm writing a 0dt deploy script for django. When a deploy is made, it creates a new django server with the most recent code version, writes a new nginx config pointing to the right socket and reload nginx. How do I find out when the old nginx workers replied all connections so I can drop the old django server? Is looking at the workers pid the best option? I can't use nginx status url because the old config stops receiving connections. Additionaly, there's another problem. Django is my backend, nginx is also proxying to a node server to serve the client. Is it possible to look at the active connections of a single upstream? Otherwise I will have to wait all connections to finish on the frontend too. -
How to use Django Models in Javascript with AngularJS
I'm working with django and AngularJS and I want to use my objects I create in Django in my javascript file. in my models.py (django) I make my object: from django.db import models class Cashflow(models.Model): index = models.FloatField(); value = models.FloatField(); date = models.DateField(); In my js file I want to use it like: app = angular.module("coco",[]); app.controller('cocoCtrl',['$scope',function($scope){ $scope.newCashflow = new Cashflow() $scope.save = function(cashflow){ $scope.newCashflow.index = cashflow.index; $scope.newCashflow.value = cashflow.value; $scope.newCashflow.date = cashflow.date; .... but that doesn't work.. Do I forget something? I get no errors or logs but just nothing happens