Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Developing a web application similar to "Upwork" using Django
I need to develop a web application that fulfills the purpose of the currently available web applications such as: "Freelancer", "Upwork", "Fiverr", "Guru", etc , for my region and in the most optimal and time efficient way. I am currently developing in Django and would appreciate any kind of expert recommendation and/or suggestion about the project development such as what packages to use. -
django - why is my serializer not showing all the data?
I am serializing data from one model, which is properly inserted, but the external serialized data I bring in is not showing when I call it and print out the serialized data. When I print out the serialized information here is what I have: {'iter_as_report': u'14', 'test_status': 305L, 'result_string': u'xxxxxxxxxx', 'id': 1} As you can see there is no tc_name included in the JSON string. What am I doing wrong? models.py class TestCase(models.Model): campaign_name = models.CharField(max_length=1000) qc_tc_id = models.CharField(max_length=1000) tc_name = models.CharField(max_length=1000) tc_description = models.CharField(max_length=1000) operator = models.CharField(max_length=1000) mobility_type = models.CharField(max_length=1000) unit_type = models.CharField(max_length=1000) class Meta: managed = False db_table = 'test_case' class Result(models.Model): test_status = models.ForeignKey('TestStatus', models.DO_NOTHING, related_name='teststatus') iter_as_report = models.CharField(max_length=2000) result_string = models.CharField(max_length=2000) class Meta: managed = False db_table = 'result' serializers.py class TestCaseNameSerializer(serializers.ModelSerializer): class Meta: model = TestCase fields = '__all__' class ResultsUserViewSerializer(serializers.ModelSerializer): tc_name = TestCaseNameSerializer(read_only=True) class Meta: model = Result fields = ('id', 'test_status', 'iter_as_report', 'result_string', 'tc_name') views.py def get_results(request): .... tempTest = Result.objects.get(test_status=305) tempTestSerializer = ResultsUserViewSerializer(tempTest) print('Serialized data: ' + str(tempTestSerializer.data)) -
Single Sign On in FF or Chrome creates 502 NGINX Error while IE works
I have a Django, NGINX setup that integrates with Singe-Sign-On. Recently we had to change domain names, and are using Akamai to spoof the new URL, while the old domain still resolved to our loadbalancer. SSO attempts to log in are successful in IE but in Chrome or Firefox there is instead a 502 error. When IE logs in there is a post from oktapreview.com that generates a 302. When its firefox or Chrome, there are 3 consecutive posts from oktapreview.com that each creates a 502. The first 2 posts have identical timestamps and the 3rd is 3-4 seconds later. For both Firefox and Chrome, upon refreshing the user finds they are actually logged in. Any advice on what is causing this? Why are there 3 logs of posts from the SSO server? Why would IE (not edge, but IE) work while Chrome and FF fail? -
How to import excel/csv data into Django and make it update periodically?
I'm really new to this and I been trying to learn Django. I need to make a local website that just spits out a set amount of data points (let's say like 5 data points) every 2 minutes or so. The data points are all from stagnant excel sheets/csv file (the data is already predetermined, it isn't live data and there are like hundreds of data points) so the data points aren't really updating dynamically. Since iam a beginner, I would like to just spit out the data (5 points or so) into the webpage without no visualization such as a graph for now ! How can I do this ? -
Variable from url in django base template file
I would like to use on my django base template file variable that will be depends on my part of url adress. for an instance, these are my urls: http://localhost:8000/name1/start http://localhost:8000/name2/start and in base html file I'd like to write it between h1 tags: {{ name }} and depending on the url, I should see name1 name2 important information, I don't like to create a block for it, because that informaton will be on each page so I don't want to write the same block in each views/ template Thanks -
Javascript - CORRECTLY append new comments without reloading
I have asked a question, how to append comments already. I got quite great answer. BUt now i want to know how to append new comments correctly, without refreshing! RIght now I add new comments with just creating new element containing comment and comment user, but they dont appear "from database". Is there any way to append new comments without having to reload whole page, but just the div containing comments, and just adding new comment? I have this code for now: $(".comments input[name='post']").keydown(function (evt) { var keyCode = evt.which?evt.which:evt.keyCode; if (keyCode == 13) { var form = this.closest("form"); var container = form.closest(".comments"); var olist = $(container).find(".clearfix"); var input = this; $.ajax({ url: "{% url 'comment' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}", data: $(form).serialize(), type: 'post', cache: false, beforeSend: function () { $(input).val(""); $(input).blur(); }, success: function (data) { alert(data.comment); clearfix = $(container).children(".clearfix"); clearfix.append("<small>"+data.user+"</small>" + "<br>" + data.comment) } }); } }); I have this in the views: def comment(request, letnik_id, classes_id, subject_id): if request.method == 'POST': exam_id = request.POST.get('exam_id') exam = get_object_or_404(Exam, id=exam_id) comment = request.POST.get('post') comment = comment.strip() if len(comment) > 0: instance = ExamComment( exam=exam, comment=comment, comment_user=request.user) instance.save() user = request.user.username return JsonResponse({'comment': comment, 'user': user}) else: return HttpResponseBadRequest() -
How to duplicate field value during migration?
I had a model that only stored a single value: class Number(models.Model): id = models.AutoField(primary_key=True, unique=True) Now I want to change the behavior so the number I need is not unique anymore. class Number(models.Model): id = models.AutoField(primary_key=True, unique=True) number = models.IntegerField(blank=True) How to tell the migration to use the ID field as the "one-off value"? -
ImportError: No module named apps
I want to create a new project and for that I am using django-admin startproject command but it is giving me error "No module named apps". I have checked that django is installed and confirmed using django-admin --version. I stuck at this point for very long time, may be silly mistake but I don't have any idea what I am missing. There is full stack trace in given below image. Any single hint would be really helpful. PS: I am working on windows OS. -
How to apply ajax to get data in dropdown?
i am using django as a backend to query my result.Like i have three dropdown and in my views I am using the value from first two drop down to bind the data in third dropdown. I know i have to apply ajax but i am totally new to ajax call.By the way my desired data is comming in my views. my views goes here:- def send_notification(request): try: university_all_list = Universities.objects.using("cms").all() master_user_types = MasterUserTypes.objects.using("cms").all() university = request.POST.getlist('universityId') masterUser = request.POST.getlist('masterUserId') users = Users.objects.using("cms").filter(userTypeId_id__in=masterUser, universityId_id__in=university) print university print masterUser print users result_for_user =[] for list in users: result_for_user = list print result_for_user.name return render(request, 'templates/push-notification/push_notification.html', {'university_all_list':university_all_list,'master_user_types':master_user_types ,'result_for_user':result_for_user}) except Exception as e: print e raise Http404 my html goes here where you can see i have three drop down named university,userType and users :- <div class="clearfix margin_bottom30"> <div class="form-group"> <label class="col-sm-4 control-label text_left">University</label> <div class="col-sm-8 multiselect_container"> <select class="mutisel" multiple="multiple" value="university_all_list.id" name="universityId" id="userName" required> {% for university_name in university_all_list %} {% if university_name.id == university_list.id%} <option value="{{ university_name.id }}" selected>{{ university_name.name }}</option> {% else %} <option value="{{ university_name.id }}" >{{ university_name.name }}</option> {% endif %} {% endfor %} </select> <script> $("select.mutisel").multipleSelect({ filter: false, placeholder: "Select", }); </script> </div> </div> <div class="form-group"> <label class="col-sm-4 … -
How to start from last page in Django ListView?
I have a ListView, that displays list of my objects. By default, ListView will start from the first page. But I need to start from the last page and then paginate to the previous ones without reversing the queryset ordering. I know that it can be solved by passing page parameter with value of the last page, but I don't know it when generating links. Is there any beautiful way to do this? -
Django: knowing when the database is queried
There's this app I'm working on that processes a medium to big sized set of data so I am trying to keep the database hits to a minimum. A particular module is about tournament scheduling. It allocates a given collection of matches in a given collection of timeslots (comprised of a time slot and a venue) while having to handle several different constraints. Keeping it simple, the algorithm goes: for match in schedule_generator.matches: # here the database would be hit as `schedule_generator.matches` is a `QuerySet` for timeslot in schedule_generator.timeslots: # same thing allocate(match, timeslot) When a match fits a timeslot, it is allocated in place and saved: def allocate(match, timeslot): # no constraint violations, we can allocate the `match` in the `timeslot` if check_allocation(match, timeslot): match.timeslot = timeslot match.save() # database is hit to save the match But in the function that checks if a match can be fit into a timeslot, we look at other matches and timeslots (among many other things). Let's say we have a constraint that says team must have at least a 30 minute break between games. def check_allocation(match, timeslot): # checking other constraints... # check there are no matches where any of the teams … -
No HTTP_CONTENT_DISPOSITION header received by Django Rest Framework for file upload
I have an AngularJS 1.6.4 frontend and a Django (1.9.7) (DRF 3.5.3) backend. Packet has POST data according to Network tab that looks like this: "postData": { "mimeType": "multipart/form-data; boundary=---------------------------16851752314922", "params": [], "text": "-----------------------------16851752314922\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.zip\"\r\nContent-Type: application/x-zip-compressed\r\n\r\nPK\u0005\u0006\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\r\n-----------------------------16851752314922--\r\n" } As you can see, the Content-Disposition has form-data, name and filename parameters, yet the request that is parsed by the backend does not parse out a HTTP_CONTENT_DISPOSITION header. Here is the content of the response that comes back, telling me that the packet is missing a Content-Disposition field: "response": { "status": 400, "statusText": "Bad Request", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Tue, 02 May 2017 22:52:51 GMT" }, { "name": "Server", "value": "Apache/2.2.15 (CentOS)" }, { "name": "Vary", "value": "Accept" }, { "name": "X-Frame-Options", "value": "SAMEORIGIN" }, { "name": "Allow", "value": "GET, POST, OPTIONS" }, { "name": "Connection", "value": "close" }, { "name": "Transfer-Encoding", "value": "chunked" }, { "name": "Content-Type", "value": "application/json" } ], "cookies": [], "content": { "mimeType": "application/json", "size": 109, "text": "{\"detail\":\"Missing filename. Request should include a Content-Disposition header with a filename parameter.\"}" }, "redirectURL": "", "headersSize": 246, "bodySize": 109 }, I can provide any other information at request, but this does not make any sense. -
Send a fax to a specific place
I have to send a fax to a certain place. The way it works is we have to send a specific message (e.g. a contract or PDF) for a specific email address and the message will print automatically when it will be in the mailbox. Could anyone have an idea how I could do such thing in Django? An example should be appreciated (please indicate the file where I will put the information (e.g. models.py, views.py, utils.py)). Here, you could take the email : test@email.com and the document sending would be PDF_test. -
How to use channels to send real time notifications based on python code?
I'm new here, so please bear with me. I'm building a monitoring system using Django, and i want to add real time alerts to it. Searching through the webs lead me to channels which promises to add event-driven functionality to Django, I've read the docs and followed this noob-friendly tutorial on how to build a simple notification system within a group of users, based on logins and logouts. But that did not help me; in that example, the dev defines functions that are directly mapped to 'websocket.connect' and 'websocket.diconnect' to send data (in this case username + is_logged_in) which is very limiting if you want to send information at any arbitrary point in time. What i want to do is send a notification to an admin as soon as a security event is detected. in other words, i want to send data using channels based on information i have in my python code. DISCLAIMER: i have no experience with channels or websockets, so i may be missing the obvious here! Any help would be much appreciated. -
datatable react-material-ui doesn't work
Someone knows how I can load a datatable, I'm trying with mui-data-table And the example works me perfectly because the data is in a constant but at the moment of Use my data that I bring from a call with axios does not load anything, does the render but the table is Empty, verify and if you make the call correctly it brings me the information but does not add it I do not know what's wrong with the table Here my code: import React from 'react'; import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import axios from 'axios'; import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; import Notifications, {notify} from 'react-notify-toast'; import { MuiDataTable } from 'mui-data-table'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import DialogoUnidades from '../componentes/dialogo_unidades'; function cargatabla() { axios.get('maquilas/cartones/', { claveempresa:'20' } ).then(response => { console.log(response.data); return response.data; }) .catch((error) => { console.log("error",error) }); } export default class Cartones extends React.Component { constructor(props) { super(props); this.state = { open: false, operacion:'Agregar Carton', data: "", paginated: true, search: 'numero\|generacion\|tipo', columns: [ { property: 'id', title: 'ID'}, { property: 'numero', title: '# Economico' }, { property: 'tipo', title: 'Tipo' }, { property: 'generacion', title: … -
How to make new DRF 3.6 built-in documentation work?
I tried to setup the new Django Rest Framework built-in documentation, following the (unusually succint) documentation. For now, I get a page with a 401 unauthorized error, and I can't see my endpoints. When clicking on session authentication, I get the message bellow. However, I'm already session-logged as a superuser in another tab. Here is the code I have so far: urls.py root_urlpatterns = [ url(r'^api/v', include('api.urls', namespace='api')), # Api endpoints url(r'^admin/', admin.site.urls, name="admin"), # Admin url(r'^docs/', include_docs_urls(title='My API')), # Built-in DRF documentation ] urlpatterns = [ url(r'^backend/', include(root_urlpatterns)) ] api/urls.py endpoints_urlpatterns = [ url(regex=r'^customers/activate/$', view=views_customer.ActivateCustomerView.as_view(), name="activate-customer"), ] VERSION = 1 urlpatterns = [ url(r'^{}/'.format(VERSION), include(endpoints_urlpatterns)) ] All required packages (coreapi, Pygments, markdown) are pip-installed. Any idea? Thanks a lot. -
How to trace this? AttributeError: 'NoneType' object has no attribute 'is_relation' during makemigrations
I'm getting a confusing error for the second time since yesterday. Last time I just flattened my whole migrations, but I've never actually found what caused the problem. So this comes up when I try to makemigrations for my python project. Where should I look for errors? I have feeling it's not actually about the migrations, but rather about errors in views.py or models.py even though I absolutely don't understand why this influences db migration. Anyway, none of theses errors points to code that I have written. It's all in Django. So how to find the error that causes that? (testenv1) C:\Users\user\eclipse_workspace\test1\test1>python manage.py makemigrations --trace Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\testenv1\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python27\testenv1\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\testenv1\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\testenv1\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python27\testenv1\lib\site-packages\django\core\management\commands\makemigrations.py", line 150, in handle loader.project_state(), File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\loader.py", line 323, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\graph.py", line 409, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\operations\fields.py", line 148, in state_forwards delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute … -
SAML / Shibb authrntication in Django
I am newbie to Django, but I know how to create a simple application in python-Django how to add new page , how to link it into url file etc. Now what I am trying to do, I am trying to create a very simple webapp where On the landing page I will have a login link. when the user clicks on this link it should go to george washington universities authentication window and then I can enter my uiversities credential and it should authenticate and come back to a page stating ** Login Successful** I have gone through many tutorials , but all looks very confusing. I have installed xmlsec1 , pysaml2, djangosaml2 modules but even after that I was clueless what to do next. I never felt so much clueless like I am feeling for this authentication module. It will be great if anyone can guide me with the process. -
JSONDecodeError on pythonanywhere
I'm trying to deploy my app on pythoneverywhere. Everything is running ok, but when I call a function, my app fails. Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Error dpaste I have been reading another answers, but no one is working for me. The problem is this peace of code: parametros = {'location': lugar, 'API_KEY': api_code} url = 'http://servizos.meteogalicia.es/apiv3/findPlaces' # Enviamos la peticion peticion = requests.get(url, parametros) # Obtenemos la respuesta respuesta = json.loads(peticion.text) Thank you so much. -
Working on two branches for two different 'local servers' simultaneously
I am currently working on a Django project. I would need to work on two branches simultaneously. To be precise, I'd like to work on two local servers for two different branches. How could I use git worktree ... to to such thing? An example would be appreciated... I know I could work with two 'local servers' with python manage.py runserver and python manage.py runserver 127.0.0.1:8001. The reason why I need to do that is I was moving back in forth systematically in different branches ... not really useful. It'll be more convenient to work with two different branches in the same time. Thanks! I am having the following issue when I typed python manage.py runserver in the directory /home/jeremie/Projects/24-django/test: django.db.utils.OperationalError: (1045, "Access denied for user 'jeremie'@'localhost' (using password: NO)". In fact, my problem is that the server runs in main tree, but not in the attached worktree. Here is the content of git worktree list : /home/jeremie/Projects/24-django 70197e0 [dev/max/operations-refact] /home/jeremie/Projects/24-django/test 70197e0 [test-worktree] In settings.py file, I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '24h_dev', 'USER': 'root', 'PASSWORD': 'wd959', }, 'old_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '24h_old', 'USER': 'root', 'PASSWORD': 'wd959', } } -
How to pass JSON from Django to Angular
Usually Angular get from HTTP request the JSON from server side (like Django). But, to accelerate rendering, would like to write down on server side the JSON into a Javascript VAR and let proceed Angular on this javascript variable containing the JSON. My question are: 1) How to pass this javascript var to angular $scope variable ? (without HTTP). 2) Is writing down the JSON into the HTML a bad/good practice ? (given my web app is fairly static). -
Heroku Could not find a version that satisfies the requirement Python==3.6.1
I am trying to deploy python 3 django my web app using Heroku and am getting the following issue when trying to git push heroku master: Counting objects: 251, done. Delta compression using up to 4 threads. Compressing objects: 100% (128/128), done. Writing objects: 100% (251/251), 408.77 KiB | 0 bytes/s, done. Total 251 (delta 122), reused 241 (delta 117) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-2.7.13 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting Python==3.6.1 (from -r /tmp/build_e93a318fd7d055dbf50a8f1974aa0537/requirements.txt (line 1)) remote: Could not find a version that satisfies the requirement Python==3.6.1 (from -r /tmp/build_e93a318fd7d055dbf50a8f1974aa0537/requirements.txt (line 1)) (from versions: ) remote: No matching distribution found for Python==3.6.1 (from -r /tmp/build_e93a318fd7d055dbf50a8f1974aa0537/requirements.txt (line 1)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to willrholmes-organiser. remote: To https://git.heroku.com/willrholmes-organiser.git ! [remote rejected] master -> master (pre-receive hook declined) My requirements.txt, runtime.txt and Procfile look as follows: Requirements: aadict==0.2.3 appdirs==1.4.2 arrow==0.10.0 asset==0.6.12 binaryornot==0.4.3 chardet==3.0.2 click==6.7 cookiecutter==1.5.1 dj-database-url==0.4.2 Django==1.10.6 django-bootstrap-datepicker==1.2.2 docker==2.2.1 docker-pycreds==0.2.1 future==0.16.0 globre==0.1.5 gunicorn==19.7.1 Jinja2==2.9.6 jinja2-time==0.2.0 lessc==0.1.2 MarkupSafe==1.0 packaging==16.8 poyo==0.4.1 psycopg2==2.7.1 pyparsing==2.1.10 python-dateutil==2.6.0 requests==2.13.0 selenium==3.0.2 six==1.10.0 … -
How to render formset with django_widget_tweaks?
How render formset with django_widget_tweaks? Here below code which render formset in template and it works but I want to know how it make the same with django_widget_tweaks? html: {{ formset.management_form }} {% for form in formset %} <label for="{{ form.field_name.id_for_label }}"> {{ form.field_name }} {{ form.field_name.label }} </label> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endfor %} -
Efficient data structure for comparing dates/statuses of open/closed ports in SQLite3 database?
I'm using Django 1.10, Python 2.7, and SQLite3 to build a web app that keeps track of the status of an object and when it was last changed. For example, every 24 hours, the user will import a list (such as the one below) of open ports for a host: 05/01/2017 ========== Host Open-Ports 123.45.67.89 22, 80, 443 ... ... A port (or multiple ports) may close one day: 05/02/2017 ========== Host Open-Ports 123.45.67.89 443 ... ... I want my Django app to display this data: IPv4 123.45.67.89 Ports 22 [Closed on 05/02/2017] 80 [Closed on 05/02/2017] 443 [Open] What would be the most efficient way of keeping track of the status of ports? This information will be stored in a SQLite3 database. How should my SQL table be setup? How should I compare the dates to know when a port is closed? Will I need two tables to store today's info and yesterday's? There could potentially be 100,000+ hosts, so I would need this method to be as optimized as possible. Thank you! -
How to have continuous ids for multiple models?
I wrote my own billing software, but I don't know how to approach this problem. Right now I have 3 models: Number Receipt Milage Receipt The point is I need to write two kinds of receipts to my costumers. But for the ministry of finance, they have to have a continuous ID over them. So Number just contains an auto field and Receipt and MilageReceipt just has a Foreign key to that. This way I have an ID over two different models. But now I want to expand this to also handle multiple companies. So there are two different types of Receipts that need to have a continuous number, but there will be multiple users who all need their own continuous numbers. I want to have something that results in: Receipt: company:1, id:1 Receipt: company:2, id:1 Receipt: company:1, id:2 MilageReceipt: company:1, id:3 Receipt: company:2, id:2 MilageReceipt: company:1, id:4 Receipt: company:1, id:5 MilageReceipt: company:2, id:3 I hope it is somewhat clear what I want to achieve. Can you please point me in the direction on how to set up models to get this behavior? I want to keep the admin as original as possible so I'd like to do this on …