Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Submitting form with multiple inputs for same field
Forewarning: I'm very new to Django (and web development, in general). I'm using Django to host a web-based UI that will take user input from a short survey, feed it through some analyses that I've developed in Python, and then present the visual output of these analyses in the UI. My survey consists of 10 questions asking a user how much they agree with a a specific topic. Example of UI for survey: Example of UI input screen For models.py, I have 2 fields: Question & Choice class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text I am wanting to have a user select their response to all 10 questions, and then click submit to submit all responses at once, but I'm having trouble with how that would be handled in Django. Here is the html form that I'm using, but this code snippet places a "submit" button after each question, and only allows for a single submission at a time. NOTE: The code below is creating a question-specific form for each iteration. {% for question in latest_question_list %} <form action="{% url 'polls:vote' question.id … -
iterate specific dictinary values in django template
I new to django when i receive a associative array namely dictionaries in python which as follows "receivable_aging": { "age5": 235114.91999999998, "age4": 235114.91999999998, "age3": 0, "age2": 0, "age1": 0 } I want to print age1 to age4 in ascending order. how can i achieve this without if or minimal steps. -
Bigchaindb program running
When I am trying to run the program in https://docs.bigchaindb.com/projects/py-driver/en/latest/usage.html I got the following error. please help me to solve the query. Traceback (most recent call last): File "bdb.py", line 1, in from bigchaindb_driver import BigchainDB File "/usr/local/lib/python3.5/dist-packages/bigchaindb_driver/init.py", line 1, in from .driver import BigchainDB # noqa File "/usr/local/lib/python3.5/dist-packages/bigchaindb_driver/driver.py", line 16 def init(self, *nodes, transport_class=Transport, headers=None): ^ SyntaxError: invalid syntax -
How to install JSONFields properly?
I just wanted to upload my django project on digitalocean, but ran into multiple problems, of which I can not solve the last one. I am using a restframework. After getting an error, that there is No module named rest_framework.views I installed but therefore get the error: AttributeError at / 'module' object has no attribute 'JSONField' Simply installing JSONField does not change anything. I think it still has to do with the restframework module. /usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py in <module> ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField I have been trying to solve it for hours already but nothing helps... Has someone had the same problem or knows how to fix it? Thanks a lot and kind regards -
Does django_celery_beat support crontab schedules with multiple minutes/hours?
I am using django-celery (https://pypi.python.org/pypi/django-celery/) to store celery beat (Periodic Task) schedules in the DB. But it doesn't support celery beyond version 3.1.25. I want to move to celery 4.1.0 and so I was looking at moving to django_celery_beat (https://pypi.python.org/pypi/django_celery_beat) for db based schedules. I was able to successfully migrate the table structures along with data. However, I see that django_clery_beat does not support crontab schedules with multiple minutes and hours which djcelery supported. For example, consider this crontab schedule - 15,30,45 0,1 * * * The task will run everyday at 12:15, 12:30, 12:45, 1:15, 1:30, 1:45. This used to work in django-celery. But in django_clery_beat, it only seems to execute at 12:15 (first one). Old setup - Django==1.10, celery==3.1.24, django-celery==3.1.17 New setup - Django==1.11.7, celery==4.1.0, django-celery-beat==1.1.0 Can anyone confirm if that support for such crontab schedules has been dropped in django_celery_beat? If it is supposed to work, is it an issue with celery or django_celery_beat? Thanks -
Eoor given In Django template loop for javascript
I am tried store value in javascript from django loop. But when I load the browser it showing error"mxwaterlv is not defined". But I already defined the variable. here is my code. {% if all_FloodLocs %} {% for map in all_FloodLocsMAX %} // max foolf can be location using twiiter API var confirmaddress ="{{ map.LocName }}"; var twicount ={{map.count}}; {% endfor %} {% else %} {% endif %} {% if all_waterLevels %} {% for waterLevel in all_waterLevelsMAX %} // max foolf can be location using twiiter API var mxwaterlv ={{ waterLevel.W_height }}; {% endfor %} {% else %} {% endif %} views.py def compare(request): end_date = timezone.localtime(timezone.now()).replace(tzinfo=pytz.timezone('America/Guatemala')) start_date = end_date + relativedelta(hours=-83) all_waterLevels = waterLevel.objects.filter(date__range=(start_date, end_date))[:5] all_waterLevelsMAX = waterLevel.objects.filter(date__range=(start_date, end_date))[:1] all_FloodLocs = Map.objects.values('LocName').annotate(count=Count('LocName')).order_by('-count')[:5] all_FloodLocsMAX = Map.objects.values('LocName').annotate(count=Count('LocName')).order_by('-count')[:1] context = {'all_waterLevels': all_waterLevels, 'all_FloodLocs' : all_FloodLocs, 'all_FloodLocsMAX':all_FloodLocsMAX, } return render(request, 'Home/compare.html', context) please help me to solve this. var confirmaddress and var twicount working perfectly -
Сheck user permissions not working in template after AJAX refresh?
I have strange behavior. Can someone say whats wrong? In template I show list of objects as in the picture below. When user add/edit/delete any data by form I update list of users by AJAX. Problem is that after refresh by AJAX buttons disappear in list. It seems like {% if perms.foo.do_something %} dont work with AJAX. Whats wrong and how to fix this problem? P.S. In the same time if I refresh page by browser {% if perms.foo.do_something %} works perfect. Show permissions correct. I am confused. At start: After refresh list by AJAX: Below example of code: javascript: // Submit Form $(function () { var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#users").html(data.html_users); $("#user-modal").modal("hide"); } else { $("#user-modal .modal-content").html(data.html_form); } } }); return false; }; // Update User Data $("#users").on("click", ".user-edit-btn", loadForm); $("#user-modal").on("submit", ".user-edit-form", saveForm); }); views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm model = User permission_required = ('auth.change_user') def form_valid(self, form): form.save() data = dict() data['form_is_valid'] = True context = {'users': User.objects.order_by('username')} data['html_users'] = render_to_string('users/users.html', context) return JsonResponse(data) *** users.html: {% for user in users %} <div … -
How Can I get the data from Django JSONField
I am having JSONField in my model class Activity(models.Model): extra = JSONField(null=True, blank=True) And this is my serializer class. There is a field run_id in extra. How can I take run_id in Serializer? class ActivitySerializer(serializers.ModelSerializer): extra = serializers.CharField(read_only=True) def get_extra(self, model): return model.extra['run_id'] I tried this, But not Working -
If I'm deploying a Django website with Nginx, do I need a service such as Digital Ocean on top of that?
I want to launch a website I've written in Python/Django. I want to host it on an Nginx Web Server. However I'm not sure if I need a service such as Digital Ocean or Heroku. What benefits do these services provide that I can't get with only Nginx? -
SECRET_KEY improperly configured in Apache(error log), but works in runserver
This is the full error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty I develop in GNU/Linux(Arch) and deploy to Windows 10. Django's internal server runserver works in both environments, but Apache throws the above error in both environments. I have separate settings files in settings folder(package) with base.py, local.py and production.py. SECRET_KEY is set in base.py and both local.py and production.py import * from base.py. Earlier I tried an environment variable set in .bashrc like this export MYPROJECT_SECRET_KEY="very_long_fake_key" but simplified back to string version, but the problem persists. I deployed to pythonanywhere PAAS service and it worked there. -
Django hide all form field errors
Is there a straightforward way to hide all Django form field errors (preferably using CSS)? I ultimately want to hide them and then display my own custom errors. I have tried the code presented here: django hide all form errors but they still keep reappearing. Thanks! -
Trouble parsing orderddict in django template
I'm having trouble trying to parse an orderddict in my django template. This is an example dict: OrderedDict([ (u'header-1510123912515', '"{u\'label\': u\'label\'}"'), (u'input-1510215273074', '"{u\'label\': u\'Preferred Assignment Area\'}"'), (u'input-1510215283971', '"{u\'label\': u\'Expected Salary\'}"'), (u'input-1510215288135', '"{u\'label\': u\'Last Drawn Salary\'}"'), ]) From the above, I would want to get the content of label. This is how I'm currently going through the dict in the template: {% for form in document.forms.all %} {% for k,v in form.hdict.items %} {% if 'header' not in k %} {"key": {{k}}, "label": "{{v.label}}"}, {% endif %} {% endfor %} {% endfor %} I'm able to successfully get the key, but not the values part (label). I hope you can help me with this as I'm quite new to django. Thanks -
Does python2.7 support Chinese path?
The python2.7 do not support Chinese path? File "/Users/denghaibing/Desktop/Test/TestPython/testDemo02/apps/用户首页/ordermanage/api/views.py", line 11, in <module> from .serializers import OrderSerializer File "/Users/denghaibing/Desktop/Test/TestPython/testDemo02/apps/用户首页/ordermanage/api/serializers.py", line 46 from 用户后台.产品管理.productmanage.models import ( ^ SyntaxError: invalid syntax In my project: You see, I use two level Chinese directories to group my apps in my Test project. but this works in Python3.5, but if use the Python2.7 Interpreter, there will comes the SyntaxError: invalid syntax issue. It do not supports Chinese path. Is there a way to let Python2.7 support Chinese path? -
Error when reading csv: coercing to Unicode: need string or buffer
I am receiving the following error when I am reading a csv file in my Django project. coercing to Unicode: need string or buffer, file found I have searched the forum already, but could not find a solution to my problem. I also have no idea how to solve this. When I run this code locally I don't have the problem. Once I execute the script from my django views I get the error from above. coercing to Unicode: need string or buffer, file found import os from django.conf import settings path = os.path.join(settings.BASE_DIR, 'technicalAnalalysis/EUR_USD') def index(request): return render(request, 'technicalAnalysis/home.html') class carouselData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): import csv EUR_USD_closeBid = [] with open(path) as csvfile: readCSV = csv.reader(open(csvfile), delimiter=str(',').encode('utf-8'), ) for row in readCSV: closeBid = row[0] BOP = row[12] EUR_USD_closeBid.append(closeBid) data = { "EUR_USD_closeBid":EUR_USD_closeBid, } return Response(data) this is how the csv was created master.to_csv(eachCurrency, encoding='utf-8', index=False) and this how the csv data looks like 1.4551,2016-08-25T21:00:00.000000Z,1.46613370302,1.4588,1.45146629698,19.2623252118,16.0468541889,18.0294990319,52.3305843166,-0.000955558790503,0.00497888833433,0.00402332954383,-0.228110599078 1.45557,2016-08-28T21:00:00.000000Z,1.46022799941,1.45683,1.45343200059,18.3020335848,15.2573095743,17.1424034245,52.7163692506,-0.00105527020367,0.00471507078342,0.00365980057975,0.655172413793 1.45919,2016-08-29T21:00:00.000000Z,1.459965965,1.456766,1.453566035,17.7461955078,14.6233407849,18.0619294336,55.6907414516,-0.000874414835166,0.00449646707462,0.00362205223946,0.82183908046 Thanks a lot in advance and kind regards -
Got an error creating the test database: Django unittest
When I run python manage.py test, django is asking a strange question each time: $ python manage.py test Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'nyble'@'localhost' to database 'test_nybledb'") Type 'yes' if you would like to try deleting the test database 'test_nybledb', or 'no' to cancel: I was expecting it to just delete and remake a basic sqlite3 DB, and I don't want this behavior. Whether I say yes or no it just exits tests: Destroying old test database for alias 'default'... Got an error recreating the test database: (1044, "Access denied for user 'nyble'@'localhost' to database 'test_nybledb'") In settings I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nybledb', 'USER': 'nyble', 'PASSWORD': 'password', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } How can I stop this and make it use normal sqlite3 db during running tests? Thank you -
Django IntegrityError-NOT NULL constraint failed: portfolio_myportfolio.holder_id
I am trying to make a portfolio manager app in django. I tried making the holder as a primary key. But in that case, the new entry overlaps the old one. So, I deleted that database and started afresh. Now, when I am trying to add a portfolio with a logged in user, I am getting the error as under:- IntegrityError-NOT NULL constraint failed: portfolio_myportfolio.holder_id I also wanted to set my database in such a way that If user adds the quantity of the same stock with same nsecode, it should add up in the previous entry instead of making a new row. In that case, what should be my scenario. Since, I am very new to python and django, my code is not clean and might have few lines of code, which is un-necessary, any help in removing such errors would be much appreciated. My Model is from django.db import models from django.contrib.auth.models import User codes=(tuple of tuples) class MyPortfolio(models.Model): nsecodes = models.CharField(max_length=10, choices=codes) quantity = models.PositiveIntegerField() buyvalue=models.DecimalField(max_digits=15,decimal_places=2) holder = models.ForeignKey(User, related_name='myportfolio') # Create your models here. my views. py is : from django.shortcuts import render,redirect,get_object_or_404 from django.views.generic.edit import CreateView from .models import MyPortfolio from .forms import AddNewForm from … -
Django /admin redirects to /usr/src/app/admin
We have our Django 1.9.6 application running in a Docker container. The docker container has nginx configured to serve the static files. We link to /admin and it will take us to the /admin pages but when we click a link it takes us to /usr/src/app/admin/api/module/ I can tell you Django is running from the directory /usr/src/app. We tried adding FORCE_SCRIPT_NAME='' to the settings and this has not helped. The Django app is running via Daphne (as we are using Channels) Here is our nginx config: server { listen 80 default_server; charset utf-8; # max upload size client_max_body_size 4G; # Django media location /media { alias /usr/src/app/media; } location /static { alias /usr/src/app/static-collect; - amend as required } location / { proxy_pass http://0.0.0.0:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } }` -
Wrong formation of static links in template django
I deployed my Django app using nginx and works fine. But my images doesn't load in pages. Not is problem with static folder, because favicon and css and js files loaded sucessfully. I take a look in a source code formed in webbrowser and i saw that the images have a '/' in the end of link. This is making the address invalid. If a remove manually the '/' i found the resource in site. But i don't know what is causing the insertion this caractere. My sites-available file server { listen 80; server_name localhost; location = /favicon.ico {access_log_off; log_not_found off;} location /static/ { root /home/pi/WebSite; } location / { include proxy_params; proxy_pass http://unix:home/pi/WebSite/Website.sock; } } My settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static/') My template file: <div class='col-md-12 col-xs-12'> <img class="img-rounded img-responsive text-center" src = {% static 'img/sistema.png' %}/> <img class="img-rounded img-responsive text-center" src = {% static 'img/legenda.png' %}/> </div> In the source code of the site, the images appears: <div class='col-md-12 col-xs-12'> <img class="img-rounded img-responsive text-center" src = /static/img/sistema.png/> <img class="img-rounded img-responsive text-center" src = /static/img/legenda.png/> </div> Any ideas, sugestions? Thanks a lot, i no more ideas -
how template POST parameter to view?
Hi~ o( ̄▽ ̄)ブ ,I have a question about django template POST value to view.I have done this: A button passes a unique value to a view's function. and now I want to get this: the left button pass values to the function_1,and the right button pass values to the function_2. when I click one button, only the value passes to the corresponding function.How I change the ajax code and how to get it from view's function? please and thanks! -
How can I pass values/parameters from HTML to Django Views?
I would usually do this in ajax I think. But if for example I have a button and a search input box that will have a query value, how can I pass the search value (and possibly multiple values/parameters that is not obtained through a form field) to Django views on button click to the url? HTML <div> <input id="search" name="search" type="text" class="query-search" placeholder="Search..."> <button onclick="window.location={% url 'view' %};" type="button" class="btn btn-primary">View Details</button> </div> Views def view_detail(request): ... <How to get values from HTML without using ajax? Or its the only way?> URLs url(r'^view/', views.view_detail, name='view_detail') -
How to open and read a csv file in django views.py
I would like to open and read a csv file in my django project. On my local directory everything works. But once I migrate the codes to my django project I get the following error. [Errno 2] No such file or directory: u'EUR_USD' The csv file is in exactly the same directory as the views.py and everything is set up just as in my local project but it still does not work. Likewise, I have tried to move the file into the static directory of the app but it still does not work. Does someone have a solution to my problem? Help is much appreciated. Thanks and kind regards. class carouselData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): import csv EUR_USD_closeBid = [] with open('EUR_USD') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: closeBid = row[0] EUR_USD_closeBid.append(closeBid) data = { "EUR_USD_closeBid":EUR_USD_closeBid } return Response(data) -
Can I use Django REST with custom structures on serializers?
I have a project in which I would like to be able to create a serializer that isn't based on a model and that could accept a custom structure of my choice. Example: class OptionSerializer(serializers.Serializer): option_1 = serializers.IntegerField() option_2 = serializers.IntegerField() option_3 = serializers.IntegerField() option_4 = serializers.IntegerField() option_5 = serializers.IntegerField() class Meta: fields = ('option_1', 'option_2', 'option_3', 'option_4', 'option_5') class QuestionsSerializer(serializers.Serializer): questions = OptionSerializer(data=[], many=True) class Meta: fields = ('questions',) In this example, I would have a custom object called Questions that would have an array of objects, each one containing the keys 'option_1', 'option_2', 'option_3', 'option_4' and 'option_5'. My goal would be to use something like this in a GenericAPIView that would allow me to render a similar structure when attempting a POST operation with the browsable API, and also to minimize validation efforts. Is that possible to be done? -
Join Many to Many tables in Django
I have three models, connected with many to many relationships ModelA - M:N - Model B - M:N - Model C They are defined as ModelA attA1 attA2 ModelB attB1 att1s.ManyToManyField(ModelA) att3s.ManyToManyField(ModelC) ModelC attC1 attC2 I want to store the data from these three on server start, without querying the database again - but I need all the data in each table. The equivalent SQL for what I'm looking for is: SELECT * FROM ModelA, ModelB, ModelC WHERE ModelA.pkA = ModelB.pkA AND ModelC.pkC=ModelB.pkC Any help would be much appreciated! -
In Django, how to re-package a Request.response as a Django response?
I have a Django App that accepts messages from a remote device as a POST message. This fits well with Django's framework! I used the generic View class (from django.views import View) and defined my own POST function. But the remote device requires a special reply that I cannot generate in Django (yet). So, I use the Requests library to re-create the POST message and send it up to the manufacturer's cloud server. That server processes the data, and responds with the special message in the body. Idealy, the entire HTML response message should go back to the remote device. If it does not get a valid reply, it will re-send the message. Which would be annoying! I've been googling, but am having trouble getting a clear picture on how to either: (a): Reply back in Django with the Requests.response object without any edits. (b): Build a Django response and send it back. Actually, I think I do know how to do (b), but its work. I would rather do (a) if its possible. Thanks in Advance! Rich. -
Revert objects on site instead of admin using django simple history
I have employed django simple history package on the admin site to be able to track and revert to previous versions of the object of the model. I am designing a web form that allows users to change instances of the model object using model form on django and would like to allow the users to view and revert to previous versions. Also to allow them to see what are the changes compared to the current version. With the code below I am able to get the list of historical records on my template under histoire. class CompanyDetailView(LoginRequiredMixin,generic.DetailView): model = Company def get_context_data(self, **kwargs): context = super(CompanyDetailView, self).get_context_data(**kwargs) company_instance = self.object context['histoire'] = company_instance.history.all() return context In my template, <p> Previous versions: {% for item in histoire %} <li> {{ item }} submitted by {{ item.history_user }} {{ item.history_object }} </li> {% endfor %} </p> But ideally I want item.history_object to be a link that users can view the previous object and be able to revert if desired.