Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define canvas for pyplot in order to plot in HTML document?
I'm using Django to make a web page. I try to make a bar plot created with matplotlib appear on my web page but receive the following error message saying that I haven't defined the attribute 'canvas': Traceback: File "C:\Python3.6\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JNPou\Desktop\Den bæredygtige back-up\kogebog\opskriftssoegning\views.py" in Opskriftsside 136. json1 = json.dumps(mpld3.fig_to_dict(bar_plot)) File "C:\Python3.6\lib\site-packages\mpld3\_display.py" in fig_to_dict 167. Exporter(renderer, close_mpl=False, **kwargs).run(fig) File "C:\Python3.6\lib\site-packages\mpld3\mplexporter\exporter.py" in run 45. if fig.canvas is None: Exception Type: AttributeError at /opskriftssoegning/kartoffelsuppe-med-porrer/ Exception Value: 'tuple' object has no attribute 'canvas' Here is my Python code for creating the plot: import matplotlib matplotlib.use('Agg') import json import numpy as np import matplotlib.pyplot as plt, mpld3 import pandas as pd [...] def make_bar_plot(): height = [1, 2, 3, 3.33, 3.67, 4, 4.33, 4.67, 5, 6, 7, 8, 9, 10, 11, 11.33, 11.67, 12, 12.33, 12.67, 13, 14, 15] bars = ('1','2','3','4','5','6','7','8','9','10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23') y_pos_prototype = np.arange(len(bars)) y_pos = pd.Series(y_pos_prototype).to_json(orient='values') #y_pos = np.arange(len(bars)) fig = plt.figure() color_set = red_yellow_green_gradient(height) # Create bars plt.bar(y_pos, height, color=color_set, figure=fig) # Create … -
Android Volley - How to use cookie value in headers
I have backend of my app in Django. I set SessionAuthentication in Django REST Framework so it sends CSRF Token. When I log in into my app I get CSRF token as a cookie. It looks like this(Image from postman): Now I need to use value of csrftoken in another POST method in my app, I need to use it ass XCSRFToken header. Here is my code: LoginActivity: private fun login2() { val req = object : StringRequest(Request.Method.POST, LOGIN_API_URL, Response.Listener { response -> Toast.makeText(this, response, Toast.LENGTH_LONG).show() val user = Intent(this, UserActivity::class.java) startActivity(user) }, Response.ErrorListener { e -> Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show() }) { public override fun getParams(): Map<String, String> { val params = HashMap<String, String>() params.put("username", username.text.toString()) params.put("password", passwd.text.toString()) return params } override fun getHeaders(): MutableMap<String, String> { return super.getHeaders() } } req.retryPolicy = DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT) volleyRequest!!.add(req) } Activity where I need to set this header: private fun aktualizacja2() { val req = object : StringRequest(Request.Method.POST, UPDATE_URL, Response.Listener { response -> Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show() Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show() }, Response.ErrorListener { e -> Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show() }) { public override fun getParams(): Map<String, String> { val params = HashMap<String, String>() params.put("librus_user", usernameEdit.text.toString()) params.put("librus_pswd", passwordEdit.text.toString()) return params } override fun getBodyContentType(): String … -
Django Unit test : `freeze_time` not work well in some cases (Seems like a bug..?)
This is my code for testing the role of TIME_ZONE and `USE_TZ: from django.test.utils import override_settings class TimeZoneTest(TestCase): @override_settings(TIME_ZONE='UTC', USE_TZ=True) @freeze_time("2018-01-04 13:30:55", tz_offset=9) # The reason that I add tz_offset=9 is to make local time samw with `Asia/Seoul` def test_freeze_time1(self): print("TIME_ZONE='UTC', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='UTC', USE_TZ=False) @freeze_time("2018-01-04 13:30:55", tz_offset=9) def test_freeze_time2(self): print("TIME_ZONE='UTC', USE_TZ=False") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=True) @freeze_time("2018-01-04 13:30:55", tz_offset=9) def test_freeze_time3(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=False) @freeze_time("2018-01-04 13:30:55", tz_offset=9) def test_freeze_time4(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=False") print(datetime.now()) print(timezone.now()) Result TIME_ZONE='UTC', USE_TZ=True 2018-01-04 22:30:55 2018-01-04 13:30:55+00:00 .TIME_ZONE='UTC', USE_TZ=False 2018-01-04 22:30:55 2018-01-04 22:30:55 .TIME_ZONE='Asia/Seoul', USE_TZ=True 2018-01-04 22:30:55 2018-01-04 13:30:55+00:00 .TIME_ZONE='Asia/Seoul', USE_TZ=False 2018-01-04 22:30:55 2018-01-04 22:30:55 The strange part is test_freeze_time1(), which tests under TIME_ZONE='UTC', USE_TZ=True, the reason that I think it strange is that datetime.now() doesn't print out UTC time, which is not True if I removed @freeze_time("2018-01-04 13:30:55", tz_offset=9) : from django.test.utils import override_settings class TimeZoneTest(TestCase): @override_settings(TIME_ZONE='UTC', USE_TZ=True) def test_freeze_time1(self): print("TIME_ZONE='UTC', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='UTC', USE_TZ=False) def test_freeze_time2(self): print("TIME_ZONE='UTC', USE_TZ=False") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=True) def test_freeze_time3(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=False) def test_freeze_time4(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=False") print(datetime.now()) print(timezone.now()) Result TIME_ZONE='UTC', USE_TZ=True 2018-02-13 09:10:49.715005 2018-02-13 09:10:49.715018+00:00 .TIME_ZONE='UTC', USE_TZ=False 2018-02-13 09:10:49.715970 2018-02-13 09:10:49.715980 .TIME_ZONE='Asia/Seoul', USE_TZ=True 2018-02-13 18:10:49.716758 2018-02-13 09:10:49.716769+00:00 .TIME_ZONE='Asia/Seoul', USE_TZ=False 2018-02-13 18:10:49.717475 2018-02-13 … -
django to IndexDB synchronization
how can i store in IndexDB and user Authentication is possible or not. if it is possible how can I login with IndexDB data of username and password. using django to sync IndexDB. just mention which indexDB is compatible. I am start searching for pouchDB. -
Can I run Django tests in pycharm community edition?
I have a Django project with a bunch of tests that I have just imported into PyCharm. I managed to get it configured so that I can run the server and that works fine but now I want to run the tests as well. I have tried to create a Path based Test Configuration and given the manage.py path and the test command as well as my settings file as parameters but I get the following cryptic error message: Testing started at 10:12 ... /Users/jonathan/anaconda/bin/python "/Applications/PyCharm CE.app/Contents/helpers/pycharm/_jb_unittest_runner.py" --path /Users/jonathan/Work/GenettaSoft/modeling-web/modeling/manage.py -- test --settings=Modeling.settings.tests Launching unittests with arguments python -m unittest /Users/jonathan/Work/GenettaSoft/modeling-web/modeling/manage.py test --settings=Modeling.settings.tests in /Users/jonathan/Work/GenettaSoft/modeling-web/modeling usage: python -m unittest [-h] [-v] [-q] [--locals] [-f] [-c] [tests [tests ...]] python -m unittest: error: unrecognized arguments: --settings=Modeling.settings.tests Process finished with exit code 2 Empty test suite. It must be running things in the wrong way somehow. Can this not be done at all? Ps. I found Running Django tests in PyCharm but it does not seem related at all (much older version?), cause I get different errors and things look very different. -
Django Custom error page's giving error
I'm trying to make custom error page general 404 and 500. I'm not trying to raise just making a default if it happens for a user, but every place I'm trying to search and follows a tutorial and so on I always ends up in getting an internal error on both 500 and 404 I'm running django=1.11.6, and I'm running debug False because I need to see if it work of course. How can I fix this issue and make it work? And how can I make it so it also gives the user the error text so they can send it to me? Views.py (In my app folder) # Error Handlers def handler404(request): return render(request, 'handlers/404.html', status=404) def handler500(request): return render(request, 'handlers/500.html', status=500) Urls.py (in my main config folder) from django.conf.urls import include, url, handler404, handler500 from django.contrib import admin handler404 = 'staff.views.handler404' handler500 = 'staff.views.handler500' urlpatterns = [ url(r'^', include('staff.urls')), url(r'^admin/', admin.site.urls), ] -
Extend User Model Django 2.0
I'm starting a whole new project using Django 2.0 and python, so I'm at the beginning of deciding how to implement the Multiple User Types. What I've read so far is that I can extend the User built-in model for django so that I would get use of django's authentication process, and create another models that links one-to-one with that user model. But actually I can't understand a little bit. My application has three user types: Participant, Admin, Judge, each of them will view certain pages(templates) and as well as permissions. Can someone provide me with the best practice/approach to start working on those user types. Note: In the future, each user may have different fields than the other, for ex. Judge may have Join date while participant won't...etc -
Safety checks in OneToOne Relation, after a relation already exist, not to be added another one
I have 2 models Account and Company. class Company(models.Model): account = models.OneToOneField(Account, related_name='company', on_delete=models.CASCADE) I want in site and in Django Admin, if a company already correspond to an account' to not be possible for another company to be added, because will give a database error. Besides removing the add/select options in Django Admin, for both site and admin, if the url is accessed directly to be redirected with message to the detail page. -
Loop Pandas table in Django template
I have a Pandas table which filled with values in my view. This view send this data to my template. Unfortunately I can't loop the values despite I can it in python shell. I attach my table and my attempt: My table (MyTable): ID day data _|___________|_____ 0| 2017-01-01|100.0| 1| 2017-01-02|99.8 | 2| 2017-01-03|90.0 | My attempt: {%for i, b in MyTable.itertools() %} <td>{{b['day']}}</td><td> {{b['data']}}</td> {%endfor%} I got the following error message: Could not parse the remainder: '()' from 'MyTable.iterools()' In python shell (where I testing) I could loop the table by the method below. How can I loop my pandas table in Django template? Thank you in advance. -
Django, how to reject a object from a @receiver if some int equals to another int
Im having this doubt, I have a model that stores data from a form, when the data is sent this @receiver stores the data in another model. @receiver(post_save, sender=Invitaciones) def crear_invitado(sender, instance, created, **kwargs): if created: Invitados.objects.create(nombre=instance.nombre, apellido=instance.apellido, tipo_de_cedula=instance.tipo_de_cedula, cedula=instance.cedula) I want this receiver to create the object only if there is not another object with the same "instance.cedula" in it. I tried to make a for cicle throught all the objects in "Intivados.cedula" like this @receiver(post_save, sender=Invitaciones) def crear_invitado(sender, instance, created, **kwargs): data = Invitados.objects.all() for c in data: if int(c.cedula) == int(instance.cedula): cedula_invitacion = print("This person already exists") else: cedula_invitacion = Invitados.objects.create(nombre=instance.nombre, apellido=instance.apellido, tipo_de_cedula=instance.tipo_de_cedula, cedula=instance.cedula) if created: cedula_invitacion This does not seem to work, the else statement is always stored in the model multiple times (equal to the quantity of models inside data) and also the print(), show the same has the quantity of models inside data. If someone has a answer, I would really appreciate it. Thanks. -
jquery - not able to display the needed content with the function
I have this jQuery script that I do not fully understand. I was wondering why I cannot replace the siblings('div') with a class or id? I think my code doesn't work properly. What I was trying to do is replace some content with a button click, and then the second content, replace it again with the second function. All courses get replaced by faculties, but faculties dont get replaced by the departments, when I press on a department, they all show one under another <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <ul> <li class="btnClick" id="fac_1">Faculty of Mathematics and Informatics</li> <ul> <li class="btnClick2" id="dep_1">Mathematics and Informatics</li> <ul> <li>Informatics</li> <li>Mathematics</li> </ul> </ul> <li class="btnClick" id="fac_2">Faculty of Medicine</li> <ul> <li class="btnClick2" id="dep_2">Medicine</li> <ul> <li>Medical Sciences</li> </ul> </ul> </ul> </div> </div> <div class="col-md-9"> <div class="jumbotron"> <div> <h3>All courses</h3> <ul> <li> <a class="first" href=artificial-intelligence>Artificial Intelligence</a> </li> <li> <a class="first" href=software-engineering>Software Engineering</a> </li> <li> <a class="first" href=surgery>Surgery</a> </li> </ul> </div> <div id="fac_1_tab" style="display:none;"> <h3> Faculty of Mathematics and Informatics courses</h3> <ul> <li> <a class="first" href=artificial-intelligence>Artificial Intelligence</a> </li> <li> <a class="first" href=software-engineering>Software Engineering</a> </li> </ul> </div> <div id="fac_2_tab" style="display:none;"> <h3> Faculty of Medicine courses</h3> <ul> <li> <a class="first" href=surgery>Surgery</a> </li> </ul> </div> <ul> <div … -
Why does my gunicorn listen to my local Django development server on my live server
When I perform gunicorn --log-file=- draft1.wsgi:application to see the gunicorn log of my app, it says Listening at: http://127.0.0.1:8000 which is the local Django development server. Can somebody tell me why it does this on my live django server? Here is the full log: (env) james@postr:~/postr$ gunicorn --log-file=- draft1.wsgi:application [2018-02-13 07:23:33 +0000] [25004] [INFO] Starting gunicorn 19.7.1 [2018-02-13 07:23:33 +0000] [25004] [INFO] Listening at: http://127.0.0.1:8000 (25004) [2018-02-13 07:23:33 +0000] [25004] [INFO] Using worker: sync [2018-02-13 07:23:33 +0000] [25007] [INFO] Booting worker with pid: 25007 -
Forbidden CSRF token missing or incorrect in Django POST request even though I have csrf token in form
I have included csrf_token in data while making AJAX request. But I keep getting 403 as a response when I make a POST request. I checked whether csrf_token is empty or not before making the request. Everything seems fine, what could be triggering the error? Here is my html code: <form method = "POST" > {% csrf_token %} <div class="form-group"> <label for="name">Name:</label> <input type="text" class="form-control" id="name" placeholder="Enter name" name="name" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" > </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" > </div> <div class="form-group"> <label for="name">Website:</label> <input type="text" class="form-control" id="website" placeholder="Enter website" name="website"> </div> <div class="checkbox"> <label><input type="checkbox" name="remember"> Remember me</label> </div> <input type="text" id="submit" class="btn btn-default" value="Submit"> Javascript Code: $("#submit").click(function(){ var finalData = {}; finalData.name = $('#name').val(); finalData.email = $('#email').val(); finalData.pwd = $('#pwd').val(); finalData.website = $('#website').val(); finalData.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ url: window.location.pathname, type: "POST", data: JSON.stringify(finalData), contentType: "application/json", success: function(data){ alert('Yo man'); }, error: function(xhr, status, error) { alert(xhr.responseText); } }); }); Python code: def signup(request): if request.method == 'POST': response_json = request.POST response_json = json.dumps(response_json) xy = json.loads(response_json) user = User() user.name = xy['name'] user.email = xy['email'] user.password = make_password(xy['pwd']) user.website = xy['website'] … -
how to create separate superuser for diffrent login in django
I have create a user login page authentication and using django admin login.. how to specify superuser for separate login .. ? and django admin login ... how specify super user for separate login pages please help me -
strange seemingly django related importerror
I have a small django project, in which I am trying to import some functions from another script. The files in question both lie in the same directory, and are views.py and lookup.py. Below is the import section of views.py. from django.shortcuts import get_object_or_404, render from django.template import loader from django.http import HttpResponse,HttpResponseRedirect from django.http import Http404 from django.urls import reverse from django.views import generic import json import random from django.views.decorators.csrf import ensure_csrf_cookie from os import listdir, getcwd import os.path from PIL import Image from app.models import ImageToClassify, ClassifiedImage, User import xlrd from lookup import get_colors, find_row, get_all_colors >> cannot import name 'get_all_colors' When I run these same imports in a separate file, there is no problem. If there is anything else I can add please let me know, this has got me very confused. I can't seem to get a minimal example which breaks, I was trying obviously and then the imports work in a new script. The order of the functions in lookup.py don't matter, nor does the import order or how I try and import the functions. -
How to send a considerably large file of any format from express NodeJS server to Django server
I have written this code to send a file using a port from NodeJS server to Django server using multer and Custom Directives from AngularJS const multerConf = { storage:multer.diskStorage({ filename:function(req,file,next){ const etx = file.mimeType.split('/')[1]; next(null,file,fieldname+'-'+Date.now()+'-'+ext); } }) }; var newName = ''; app.post('/upload', multer(multerConf).single('file'), function(req, res){ if(req.files.file){ req.body.file = req.files.filename; var file = req.files.file; var filename = req.files.file.name; newName = './upload/'+Date.now()+filename; file.mv(newName,function(err){ if(err){ console.log(err); res.send("Upload failed"); }else{ var fileUrl='./upload/'+filename; console.log(fileUrl); } }); const options = { url: 'http://localhost:8000/myAssignmentApp/a_n_d', method: 'GET', headers: { 'Accept': 'application/json', 'Accept-Charset': 'utf-8' } }; request(options, function(err, res) { }); } }); The following code is for the port. server.on('request', (req, res) => { fs.readFile(newName, (err, data) => { if (err) throw err; res.end(data); }); }); server.listen(6000); Is there any other more efficient method to do the same? -
Website server communication for compiling code
I’m wanting to have my website compile C code on the servers end. How would I handle this? Are there any resources? Would it need to be queue based since multiple people can submit code for compilation within a short period of time? Thanks! -
offline authentication using cookies, django
I am building offline progressive web application for that I need Authentication in offline for existing user. I am trying to store user authentication values like username and password in browser using cookies. but how to retrieve username and password form cookies and check authentication in offline using service worker. thanks in advance -
Where to store images during Django deployment?
I've deployed my django project onto my Digital Ocean server. However I'm not sure how to deal with image assets in my html, and also image assets generated from users. So an example of assets in my html would be for example, the logo of my website. An example of user-generated images would be the user uploaded a post with an image. In development I could just get my html images from static/image/image.png however this method doesn't seem viable in production. For user-generated images it would go in media. How do these 2 differ when going into production? For static images in my HTML the storage would be quite low so could this just live on the server? However I don't think it's possible to have images in a git repo. -
How to integration CCAvenue with python/Django
I am getting 'Error Code: 10002 Merchant Authentication failed' error on ccavenue site when redirect form my site. IP is verified on ccavenue. My another php site is working on this IP with ccavenue. encryption = encrypt(merchant_data, workingKey) return HttpResponse("""<html><head><title>Payment.</title></head><body><form method="post" name="redirect" action="%s"> <input type="hidden" name="encRequest" value="%s"><input type="hidden" name="Merchant_Id" value="%s"><input type="hidden" name="access_code" id="access_code" value="%s"></form> </body><script language='javascript'>document.redirect.submit();</script> </html> """ % (cc_url, encryption, p_merchant_id, accessCode) -
i need to display loading image when user clicks on submit button using django
I need to display loading image when user clicks on submit button using django framework. As i have a form where user enters integer and waits for response. As getting response might take few minutes till that time loading image as to be displayed and once it get response it should disappear. below is my code: urls.py urlpatterns = patterns('', url(r'^burt/$',burt_id.as_view(),name='burt_id'), ) views.py class burt_id(TemplateView): template_name = 'burt_id.html' def get(self, request): form = Homeform2() test='Please wait page is loading' return render(request,self.template_name, {'form':form,'test':test}) def post(self, request): form = Homeform2(request.POST) d={} if form.is_valid(): text = form.cleaned_data['Burt_id'] <""" few process inside function"" > args = {'form':form,'out_dict':out_dict} return render(request, self.template_name,args) burt_id.html {%load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static "css/main.css" %}"> </head> <body> <div class="block6" style="margin-left:250px;"> <table class="'table table-hover" style="width:53.5%;"> <tr> <td style="text-align:center;"> Burt ID</td> <td style="text-align:center;"><form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="button button2" style="margin-left:80px;">Submit</button> </form> </td> </tr> </table> <div id="loading1"><h3">please wait its loading</h3></div> <div id="content"> <table class="table table-hover" style="width:80%;" > {% if not out_dict %} <tr> <td>No Change Number </td> </tr> {% else %} <tr style="color:white;"> <th>Test Case</th> <th>File Name</th> <th>Coverage</th> </tr> {% for key, value in out_dict.items %} <tr> <td>{{ key }}</td> <td>{{ value.0 }}</td> </tr> … -
I am using Django 1.8 after installing django redux 2.02 it started showing error Django.urls not found before installing redux it was working fine
ModuleNotFoundError at / No module named 'django.urls' enter image description here -
Integration of cloudant with django
I am new to cloudantdb and django. Is there any way to integrate cloudantdb with danjgo framework. Is it possible to connect cloudant with django? -
Savoir JSON-RPC wrapper: JSONDecodeError django
I tried using Savoir Json-RPC wrapper in my django project. After submitting the form it to request API data it sends: JSONDecodeError at /account/login/ Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://localhost:8000/account/login/ Django Version: 1.11.3 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: c:\users\dell\appdata\local\programs\python\python36\Lib\json\decoder.py in raw_decode, line 357 Python Executable: E:\savoir\Scripts\python.exe Python Version: 3.6.4 Python Path: ['E:\\savoir\\src', 'E:\\savoir\\Scripts\\python36.zip', 'E:\\savoir\\DLLs', 'E:\\savoir\\lib', 'E:\\savoir\\Scripts', 'c:\\users\\dell\\appdata\\local\\programs\\python\\python36\\Lib', 'c:\\users\\dell\\appdata\\local\\programs\\python\\python36\\DLLs', 'E:\\savoir', 'E:\\savoir\\lib\\site-packages'] I cannot find any solution of it and I don't know where did I do wrong. In views.py: class Signin(View): template_name = 'login.html' def get(self, request): form = LoginForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): multi = get_object_or_404(RegisterMulti, rpc_user=form.cleaned_data['user']) if form.cleaned_data['passwd1'] != multi.rpc_passwd or form.cleaned_data['host'] != multi.rpc_host or form.cleaned_data['port'] != multi.rpc_port or form.cleaned_data['chname'] != multi.chain_name: messages.error(request, "Error") return render(request, self.template_name, {'form': form}) rpcuser = multi.rpc_user print(rpcuser) rpcpasswd = multi.rpc_passwd print(rpcpasswd) rpchost = multi.rpc_host print(rpchost) rpcport = multi.rpc_port print(rpcport) chainname = multi.chain_name print(chainname) api = Savoir(rpcuser, rpcpasswd, rpchost, rpcport, chainname) print(api.getinfo())` In forms.py: class LoginForm(forms.Form): user = forms.CharField(max_length=32) passwd1 = forms.CharField(max_length=32) host = forms.CharField(max_length=300) port = forms.CharField(max_length=10) chname = forms.CharField(max_length=32) In urls.py: urlpatterns = [ url(r'^login/', … -
Get the correct port number from LiveServerTestCase in Django 2.0
When trying to test the admin login using the following code, I found the self.live_server_url returns something like http://localhost:39346, where the port number is different on each running. from django.test import LiveServerTestCase from selenium import webdriver class AdminLoginTests(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() super(QuestionCreateTests, self).setUp() def tearDown(self): self.selenium.quit() super(QuestionCreateTests, self).tearDown() def test_admin_login(self): # ... print('url: %s' %self.live_server_url) How do I get the correct port number 8000 of the running server? Suppose I run the server through python manage.py runserver 0.0.0.0:8000. Thanks!