Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing request in django template tag
I tried to access the request in my custom template tag function. But it is not working. views.py def candidate(request): ....... ....... return render(request, template, context) templatetags @register.filter(takes_context=True) def make_url(doc_url, context): request = context["request"] protocol = "https://" if request.is_secure() else "http://" host = request.get_host() new_url = "%s%s%s" %(protocol, host, new_url) return new_url template.html <iframe src="{{ candidate.resume_file.url | make_url }}" frameborder="0"></iframe> -
Why does the following code display 'null' instead of a value in my ajax form?
I am trying to display the error message in the footer section of my ajax form but i get 'null' instead of a value what is wrong ? here is my code so far: html : <div class="modal-footer"> <div id="error_message"></div> <button type="submit" class="btn btn-default" id="submit" disabled>Submit</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div role="modal-footer"> view.py: from django.shortcuts import render from librarysystem.models import Users from django.http import JsonResponse def index(request): template = 'librarysystem/Elib.html' return render(request,template) def validateForm(request): tagId = request.GET.get('id',None) data = { 'isTaken' : tagId, 'value': request.GET.get(tagId,None), } return JsonResponse(data) ajax code: function validateForm() { tagId = this.id; $.ajax({ url: "/librarysystem/validate/", data: { tagId: this.value, 'id': tagId, }, dataType: 'json', success: function(data){ $('#error_message').html(data.value + ' = value').css('color','red'); } }) ; } $(document).ready(function() { $("#username, #emailid, #password, #retrypassword").keyup(validateForm); }); -
How to enable users on Django sites to customize UI design through drag and drop (similar to Wix)?
I have built a few sites using Python Django. Recently, a client came in with the expectation to drag-and-drop UI elements to customize the front-end design down the road, much in a Wix.com-like fashion. My initial guess is that to achieve that in Django, one needs to code some thing like a CSS/HTML code generator. I wonder if there are other more practical ways to achieve this? -
Graphing in Django from PSQL database
I have a psql database with time series data and was wondering if anyone had any tutorials that showed how to graph queries in Django. I'm not sure if I am just supposed to execute queries in the model and then display in the view, or what the best order to do them is. Any advice or direction would be much appreciated -
How to get row with most number of foreign keys in django?
I have a writer model/table and an Articles model like: class Writer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) pic = models.URLField() start_date = models.DateField('date of start', blank=True, null=True) about = models.TextField(max_length=300) class Article(models.Model): writer = models.ForeignKey(Writer) name = models.CharField(max_length=100) content = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField(auto_now=False, auto_now_add=True) One Article can have only on Writer but One Write can have many Articles.I can get all the writers with Writer.objects.all() But I want to Writer with most Articles how can I do that? -
No module named 'new_app' Django 1.8 error
I am deploying new django new_app with the command django-admin.py startapp new_app, add it to installed apps in settings.py . Then after makemigrations and migrate commands everything is fine. Now I need to copy files from GitHub and replace default new_app folder with them. I delete everything from new_app folder exept default migrations (is this right?) and delete migrations from the relevant cloned GitHub folder and copy everything else to new_app folder. So, the only thing left dafault is migrations. After those actions makemirgations command responds with the following traceback: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/django/django_project/denv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/django/django_project/denv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/home/django/django_project/denv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/django/django_project/denv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/django/django_project/denv/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named `new_app` -
createsuperuser django openshift v3
How can I do some managing works such as createsuperuser ,makemigrations, migrate ect in OpenShift-NextGen for a Django Application ? (Step-by-Step) In OpenShift-V2, I did the same by login to shell by rhc ssh app_name and run the command python $OPENSHIFT_REPO_DIR/wsgi/myproject/manage.py createsuperuser (Reference) -
Django gets updated while installing django-fcm . How to install django-fcm without updating django
My django version is 1.8.3. And I read it supports django-fcm. I tried installing django-fcm in my virtual environment using pip install django-fcm sadly running this command replaced my existing django version to 1.10 and djangorestframework from 3.2.2 to 3.5.2 Here is the log pip install django-fcm Requirement already satisfied: django-fcm in /home/sudheer/virtualenvs/mediaone/lib/python2.7/site-packages Collecting djangorestframework>=3.3.2 (from django-fcm) Using cached djangorestframework-3.5.3-py2.py3-none-any.whl Collecting django>=1.9 (from django-fcm) Using cached Django-1.10.4-py2.py3-none-any.whl Collecting pytz>=2015.7 (from django-fcm) Using cached pytz-2016.10-py2.py3-none-any.whl Collecting requests>=2.9.1 (from django-fcm) Using cached requests-2.12.4-py2.py3-none-any.whl Installing collected packages: djangorestframework, django, pytz, requests Found existing installation: djangorestframework 3.2.2 Uninstalling djangorestframework-3.2.2: Successfully uninstalled djangorestframework-3.2.2 Found existing installation: Django 1.8.3 Uninstalling Django-1.8.3: Successfully uninstalled Django-1.8.3 Found existing installation: pytz 2015.4 Uninstalling pytz-2015.4: Successfully uninstalled pytz-2015.4 Found existing installation: requests 2.7.0 Uninstalling requests-2.7.0: Successfully uninstalled requests-2.7.0 Successfully installed django-1.10.4 djangorestframework-3.5.3 pytz-2016.10 requests-2.12.4 Is there any way to prevent this from happening. I just want to install django-fcm -
Django: order a queryset elements in roundrobin fassion based on a forign key value
I have to models related by forignkey. and I want to select the elements from one model based and I should give representation to each value of the other model class Abc(models.Model): name = models.CharField(max_length=100) description = models.TextField() xyz = models.ForeignKey(Xyz, related_name="abcs") class Xyz(models.Model): name = models.CharField(max_length=100) description = models.TextField() Say we have three Xyz objects with names 'a','b' and 'c' and six Abc objects with name 'p' (p-->a) , 'q' (q-->a) , 'r' (r-->b), 's' (s-->b) , 't' (t-->c) and 'u' (u-->c) If I want to select Abc objects and arrange them in roundrobin fassion based on the Xyz values, what will be the best method? expected result [p,r,t,q,s,u] -
Django with Braintree
I currently want to build a simple payment system using Braintree where I generate a entry into my local database for each transaction. What I have done is have Braintree's drop-in UI and a form recording eg. email, number of tickets bought, such that when submitted and the payment is successful, I add to my database the transaction ID, status, number of tickets bought and the email. However I have no idea about how secure it is or whether there is a "proper way" to do this so I was wondering if anyone could give any advice on my implementation. -
How to use Shopify Python API RecurringApplicationCharge
When I try to do the following in a view for a valid user, I get an error. How do I use the RecurringApplicationCharge? @login_required def confirm(request, *args, **kwargs): with request.user.session: # Tried this: charge = shopify.RecurringApplicationCharge.create(name="Test", test="true") # Tried this: charge = shopify.RecurringApplicationCharge.customize(name="Test", test="true") # Tried this: charge = shopify.RecurringApplicationCharge(name="Test", test="true") I can see that the RecurringApplicationCharge class has a method customize which does load_attributes_from_response(self.put("customize", recurring_application_charge= kwargs)) but I am not sure what to do with this. .create gives me: TypeError: create() got an unexpected keyword argument 'name' .customize gives me: bound method customize() must be called with RecurringApplicationCharge instance as first argument (got nothing instead) the last gives me: recurring_application_charge(None) Do I need to create a usage charge first and add it as pre-fix options? -
Django AJAX requests during regular request not going through
I have a Django site with a login webpage. When the login form on the page is submitted, it executes the login view, which runs a function inside it that takes a long time to process (30 seconds or so). So in order to show progress to the client during login, as soon as the form is submitted, a JS function on the login page starts making AJAX POST requests to the server (to a poll_state view), which returns the state of the login. It then updates the html of the login page to show the state (like a loading bar). My question or problem is that when I do the regular python manage.py runserver with an NGINX proxy server it works flawlessly. But when I use Gunicorn instead of python manage.py runserver the AJAX requests don't go through until the login view has completely processed and returned a response (which is the next webpage). Instead of polling the state of the login, it just returns a bunch of errors for the poll_state view after the next webpage has loaded. Does anybody know if Gunicorn can take AJAX requests from the same client as it's processing a normal request from … -
Django or flask
Am new to python and wanted to convert one of my existing application builds using visual studio (c#), I want to write code in python from scratch. But am not sure whether python is the right choice for it or not. First let me give brief requirements here what I wanted to achieve - 1) User enabled login page 2) Form to collect user input on his daily purchases through text boxes or another input box. 6-7 input is required here. 2) In the same form when he is giving the item name, providing him auto fill kind of functionality based on previous items loaded in DB 3) Generate a monthly report (some aggregation) based on user choice of month and year. Now my previous application was for windows, this time using Django or flask I want to make it as a web application which can be accessed using the browser. As my requirement is pretty much simple and more front end oriented not sure if Django or Flask is suitable for this kind of work. Please share your expert opinion and any possible challenge which I need to foresee. -
Difficulty Unpacking Custom Template Filter Args
I have some Django Template Code that is as follows: {% with key=clothes_item.name %} {% for item in clothes_images|get:key %} {% thumbnail item.image "300x300" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} {% endfor %} {% endwith %} That is based on a custom template filter: @register.filter(name='get') def get(dictionary, arg): if arg is None: return False return dictionary.get(arg) Essentially, I have a collection of clothes item objects. For each of these objects, I need to unpack the values of a dictionary (key: string, value: list of querysets) that was passed to the template, and iterate over all the values that were contained in this list. The thumbnail code (using sorl-thumbnail) is all functional, so my error is either in the second line of my template html or in my implementation of the filter function. I'm getting a Value Error and it says there are two many values to unpack, so I presume I'm not correctly accessing the data using proper template syntax. Any Suggestions? Here is an example of the value of clothes_images when the error occurs: clothes_images = {u'blue shirt / green pants': <QuerySet [<Clothes_Image: Clothes_Image object>, <Clothes_Image: Clothes_Image object>]>} -
Most performant way to retrieve a Django queryset sorted in accordance to a redis sorted set
I have a redis sorted set containing object ids and their respective sorting scores. I need to retrieve a Django query set of these objects, sorted in accordance to the sorted set's scores. What's the most efficient way to do this? Currently, I'm retrieving the redis sorted set and the unsorted queryset. Next, I sort the queryset in accordance to the sorted set's scores in python. Can steps be cut here, e.g. somehow sorting the queryset at the point of retrieval, etc.? obj_ids_with_scr = get_ids_w_scr() #retrieves redis sorted set with scores obj_ids = map(itemgetter(0),obj_ids_with_scr) # filters sorted set for just the obj ids queryset = Widget.objects.filter(id__in=obj_ids) #unsorted queryset a = dict(obj_ids_with_scr) #turning the sorted set into a dictionary for obj_pk, sort_score in a: obj = queryset.get(id=obj_pk) #get object with id equalling obj_pk sort_score = obj #assign the object to the 'score' value of this key-value result = a.values() #making a list of all values, that are now in sorted order return result -
How can I can access other users profiles with an authenticated account from url?
On my website I would like to access other users profiles with entering an username in the url, I'm having some trouble accessing other users informations on their profile while using the authentified account. The code below always show the authentified user's informations. urls.py url(r'^profile/(?P<username>\w+)/$', profile_views.UserProfile, name='profile'), views.py def UserProfile(request, username): u = User.objects.get(username=username) user = request.user context = {'user': user} template = 'account/profile.html' return render(request, template, context) template file <div class="jumbotron"> <p>{{ user.username }}</p> <p>{{ user.email }}</p> </div> How can I do it ? -
Why am I unable to run django migrations via the 'docker-compose run web' command?
So I am deploying django, postgress and nginx containers via docker-compose and I have an issue that I can't seem to figure out. In order to resolve the following error in my Django app, I knew I just had to run a Django migration. docker@postgres ERROR: relation "accounts_myprofile" does not exist In an attempt to run migrations, I tried: docker-compose run web python manage.py makemigrations docker-compose run web python manage.py migrate which returned the following: Migrations for 'accounts': accounts/migrations/0001_initial.py: - Create model Entry - Create model MyProfile Running migrations: No migrations to apply. I was only able to successfully migrate from within the Django container, example: docker exec -i -t 6dc97c6a305c /bin/bash python manage.py makemigrations python manage.py migrate Although I have resolved the issue, I still don't understand why running the migrate via docker-compose run does not actually migrate anything. I'm hoping someone can maybe point me in the right direction on this. Also, I don't know if this is a related issue or not, but when I run those docker-compose run web commands, they seem to be creating new containers that won't shutdown unless I manually stop them, docker-compose stop doesn't remove them. CONTAINER ID IMAGE COMMAND CREATED STATUS … -
Django filter().exists always returns false
I've started making a website in Django and I'm attempting to write unit tests for it, however, I'm unable to get one this unit test to pass. def test_email_already_in_use(self): user_email = 'testing_email@testing.com' password = 'testing_password' User.objects.create_user(username=user_email, password=password) tmp = User.objects.filter(email=user_email).exists() form_data = {'email': user_email, 'password': password} with self.assertRaises(ValidationError): form = UserForm(data=form_data) form.clean_email() The problem is that tmp is always false (tmp is just used to help me debug without having to step any further. The exists check is done in clean_email normally). However, when I attempt to create a new user with an existing email when the website running the code run properly. I'm obviously missing something with how create_user works. This is the code that properly checks against an email already being in use when I attempt to create a new user with the same email. def clean_email(self): email = self.data['email'] if User.objects.filter(email=email).exists(): raise ValidationError("Email already in use") if len(email) > 100: raise ValidationError("Email length exceeds 100") return email -
Transaction on bank transaction with python/django
Currently I've a model that does deposit and withdrawal with django but honestly I've no Idea how to do a transaction that would be effective, since I'm not 100% sure if everything works. If you have 10 minutes so I can learn this dummy way it would be appreciate it. the code I've is: Transaction Withdraw with transaction.atomic(): # Withdraw Payment Log WithdrawTransactionLog = Client_Transaction( ClientData=ClientSenderObject, Reference=TransactionReferenceKey, Amount=PaymentAmount, Balance=((ClientSenderObject.Balance - PaymentAmount) - settings.SERVICE_FEE), Description=Description, Operation=2, Fee=settings.SERVICE_FEE, IpAddress=ClientIp, Origin=1) WithdrawTransactionLog.save() # withdraw Amount ClientSenderObject.withdraw(PaymentAmount) ClientSenderObject.withdraw(settings.SERVICE_FEE) # Deposit Payment Log DepositTransactionLog = Client_Transaction(ClientData=client_recipient_object, Reference=TransactionReferenceKey,Amount=PaymentAmount, Balance=(client_recipient_object.Balance + PaymentAmount), Description=Description, Fee=0, Operation=1, IpAddress=ClientIp, Origin=1) DepositTransactionLog.save() # Reciever Deposit client_recipient_object.deposit(PaymentAmount) -
How to store ModelChoicieField value?
I'm new with Django and I have a little problem : I have a DB (MyClass) with several attributes and I would like to print on a web page only those who have their category attributes equal to one of the elements of the DB Categories. For this, I want to use a ModelChoiceField which will display all the possibilities from the Categories DB. Then, I think that I have to store the one chosen by the user in order to display in the webpage the corresponding element of the MyClass DB. I tried the following code : views.py def my_view(request): test = False if request.method == 'POST': form = MyForm(data=request.POST) if form.is_valid(): cat = form.save(commit = False) test = True my_var = MyClass.objects.filter(category = cat.category) else: form = MyForm() var = MyClass.objects.all() return render(request, '/path/to/template.html', {'form': form, 'my_var': my_var, 'test': test}) forms.py class MyForm(forms.Form): category = forms.ModelChoiceField(queryset = Categories.objects.all().order_by('name')) page.html {% extends "base.html" %} {% block content %} {% if test %} <p> {% for element in my_var %} <td>{{ element.title }}</td><br> {% endfor %} </p> {% else %} <strong>Select the category : </strong><br> <form id="form" action="{% url 'page' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" … -
Why when i edit a MultiPolygon type geometry in the map it changes to Polygon type?
Im working with GeoDjango and drawing with google maps api 3. When i turn editable:True and edit a MultiPolygon type geometry, it changes to a Polygon type in the GeoJson properties, but i need to work all my geometries in MultiPolygon. I search in the web, but all what i found was "how to change MultiPolygon to Polygon", but i dont want that. This is my model in django class Potrero(models.Model): sector = models.ForeignKey(Sector,editable=False) nombre = models.CharField(max_length=30) superficie = models.FloatField(editable=False) vector = models.MultiPolygonField(srid=4326,default=None) objects = models.GeoManager() class Meta: unique_together = (("nombre","sector"),) def __unicode__(self): return self.nombre I transform the geodjango data in json with geojson method and transfer it with the HttpResponse in the variable "lhope". My code in javascript: This is how is drawing the features: map.data.addGeoJson(lhope); map.data.setStyle(function (feature) { var fcolor = feature.getProperty('fillColor'); var scolor = feature.getProperty('strokeColor'); var sopacity = feature.getProperty('strokeOpacity'); var edit = feature.getProperty('editable'); return { fillColor: fcolor, strokeColor: scolor, strokeOpacity: sopacity, editable:edit, strokeWeight: 2.0 }; }); when i begin to edit: var f = map.data.getFeatureById(feature_id); f.setProperty('editable',true); And when i finish the edition: var f = map.data.getFeatureById(feature_id); f.setProperty('editable',false); var new_potrero; f.toGeoJson(function(new_potrero){ alert(JSON.stringify( new_potrero,null,4)); $.get( {dataType:"json",url:"{% url 'geoinfo:get_edit_potrero' %}", data:{ idi: f.getId(), poly: JSON.stringify( new_potrero,null,4) }}) ; }); when … -
FactoryBoy "create" strategy doesn't seem to save django model
Probably a silly question, but I've been banging my head against a wall for a little while now. I decided to try factory-boy library to simplify my tests and defined a factory: from . import models import factory class QualtricsSurveyCacheFactory(factory.Factory): class Meta: model = models.QualtricsSurveyCache survey_id = "SR_1234" qualtrics_username = "bla@blah.bla#bla" survey_name = "fake" However, when I do QualtricsSurveyCacheFactory.create() it returns model with id = None >>> survey = QualtricsSurveyCacheFactory() >>> print survey.id None I can .save() model after creation, but just curious why it doesn't do it automatically. -
Set python workspace environment to Debian VM when on OSX in VS Code
I am experimenting with setting up Visual Studio Code as my Django IDE, however I'm having difficulty configuring my python workspace environment correctly, such that I can get intellisense for 3rd party modules (like Django) working. My desktop is Mac OSX, but I run my actual Django environment in a Debian instance inside of virtual box, running on my Mac. I also run Debian in production. I use an NFS share my django project files and virtualenv files between Debian and OSX. I tried following these instructions for configuring my interpreter, however if I set a custom path like: /Users/myusername/.virtualenv/myenv/bin/python2.7 It won't work, because that's a debian binaries, not Mac OSX. In PyCharm I believe there is a way to specify remote interpreters, even on different architectures. There's no way to do something like this in VS Code, right? -
How to create a login form for Users in Django
What is the Django way of creating a User? I am not talking about the super user, just a simple form for users and creating an account -
Visual Studio PyTools Create Django project from existing code
I'm working on some django project. Previously i've been using Visual Studio Code, but now I would like to switch to Visual Studio 2015 with pytools. What I've done so far 1. Clone my git repository 2. Create new python project From existing python code (There was no 'create django project from existing python code..) 3. The project was created, all files are imported 4. When I was trying to run project I've received multiple-missing-packages errors. I used Python.InstallPackage and installed all packages from requirements.txt. 5. Now when I start project I can see only a windows command window with information Type 'manage.py help < subcommand >' for help on a specific subcommand Available subcommands: [auth] etc When I create a clear, new django project and click run it opens Google Chrome with django template site (even on the running button there is 'Google Chrome' text). In my created-from-existing-code project there is only 'Start' text. What should I to to make my created-from-existing-code-project act like clear django project (it sould run postgresql server and Google chrome)?